图片中的文字提取是办公自动化中的高频需求——扫描件转文字、截图识别、发票信息提取。Python 中有两个主流的 OCR 库,这篇从安装到实战完整讲解。
一、方案选择:PaddleOCR vs Tesseract
| 对比 | PaddleOCR | Tesseract |
|---|---|---|
| 中文识别 | ⭐⭐⭐⭐⭐ 优秀 | ⭐⭐⭐ 一般 |
| 安装难度 | ⭐⭐(稍大) | ⭐(简单) |
| 识别速度 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| 准确率 | 95%+ | 80%-90% |
| 版面分析 | ✅ 支持 | ❌ 不支持 |
建议:中文场景无脑选 PaddleOCR,英文场景两个都可以。
二、PaddleOCR
pip install paddlepaddle paddleocrfrompaddleocrimportPaddleOCR ocr=PaddleOCR(use_angle_cls=True,lang='ch')result=ocr.ocr('invoice.jpg')forlineinresult[0]:text=line[1][0]confidence=line[1][1]print(f'{text}(置信度:{confidence:.2%})')三、Tesseract
pip install pytesseract# 还需要安装 Tesseract-OCR 引擎importpytesseractfromPILimportImage text=pytesseract.image_to_string(Image.open('text.png'),lang='chi_sim+eng')print(text)四、发票识别案例
frompaddleocrimportPaddleOCRimportre ocr=PaddleOCR(use_angle_cls=True,lang='ch')result=ocr.ocr('invoice.jpg')texts=[line[1][0]forlineinresult[0]]full_text=''.join(texts)# 提取关键信息invoice_no=re.search(r'发票号码[::](\d+)',full_text)total=re.search(r'价税合计[::]?¥?([\d,]+\.\d{2})',full_text)print(f'发票号码:{invoice_no.group(1)ifinvoice_noelse"未识别"}')print(f'价税合计:{total.group(0)iftotalelse"未识别"}')💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!