在日常开发中,我们经常遇到需要从图片中提取文字的场景。比如财务人员需要从发票图片中自动识别金额和税号,图书馆管理员需要将古籍扫描件转为可编辑文本,甚至是你想快速提取截图中的代码片段。这时候光学字符识别(OCR)技术就能派上大用场。
Python生态中有两个主流的OCR工具:PaddleOCR和pytesseract。我在实际项目中都使用过它们,发现各有特点。PaddleOCR像是配备了AI引擎的超级跑车,识别精度高但需要更多计算资源;pytesseract则像是经济实用的小轿车,安装简单但功能相对基础。下面我会结合具体场景,带你了解如何选择最适合的工具。
安装PaddleOCR只需要一条命令:
bash复制pip install paddleocr paddlepaddle
不过这里有个坑要注意:如果你的机器没有NVIDIA显卡,记得安装CPU版本:
bash复制pip install paddlepaddle-cpu
基础识别代码非常简单:
python复制from paddleocr import PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang="ch")
result = ocr.ocr("invoice.jpg", cls=True)
for line in result:
print(line[1][0])
我测试过一张包含中英文混合文字的发票图片,PaddleOCR的识别准确率能达到95%以上。特别是对中文手写体的识别,效果远超其他开源工具。
PaddleOCR真正强大的地方在于它的高级功能:
表格识别示例:
python复制from paddleocr import PaddleOCR
ocr = PaddleOCR()
result = ocr.ocr("table.png", rec=False, cls=False, det=False, table=True)
print(result)
我在处理财务报表时,这个功能帮了大忙。传统OCR工具会把表格识别成杂乱无章的文本,而PaddleOCR能完美还原表格结构。
pytesseract的安装更简单:
bash复制pip install pytesseract
但要注意,它需要依赖Tesseract OCR引擎。在Ubuntu上需要额外安装:
bash复制sudo apt install tesseract-ocr
基础识别代码:
python复制import pytesseract
from PIL import Image
text = pytesseract.image_to_string(Image.open('receipt.jpg'))
print(text)
我测试同样的发票图片,pytesseract对印刷体英文识别不错,但中文准确率只有70%左右,而且对手写体几乎无能为力。
虽然功能相对简单,但pytesseract有些实用技巧:
python复制import cv2
img = cv2.imread('blurry_text.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
text = pytesseract.image_to_string(thresh)
python复制text = pytesseract.image_to_string(img, lang='chi_sim+eng')
python复制data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)
为了更直观地比较两者差异,我做了组对比测试:
| 测试项目 | PaddleOCR | pytesseract |
|---|---|---|
| 中文印刷体准确率 | 98% | 75% |
| 英文手写体准确率 | 85% | 40% |
| 处理速度(秒/张) | 1.2 | 0.3 |
| 内存占用(MB) | 1200 | 200 |
| 表格识别支持 | 是 | 否 |
| 多语言混合识别 | 是 | 有限支持 |
从测试结果看,PaddleOCR在精度和功能上全面领先,但资源消耗也更大。pytesseract的优势在于轻量和快速。
如果是增值税发票识别,我强烈推荐PaddleOCR。因为发票上的关键信息(如金额、税号)必须100%准确,PaddleOCR的深度学习模型在这方面表现更好。
优化建议:
python复制ocr = PaddleOCR(
det_model_dir='./ch_PP-OCRv3_det_infer',
rec_model_dir='./ch_PP-OCRv3_rec_infer',
cls_model_dir='./ch_ppocr_mobile_v2.0_cls_infer',
use_angle_cls=True
)
对于大批量扫描文档转文字,如果主要是英文内容,pytesseract可能是更好的选择。它的处理速度更快,对服务器资源要求更低。
批量处理示例:
python复制from pathlib import Path
docs = Path('scanned_docs').glob('*.jpg')
for doc in docs:
text = pytesseract.image_to_string(str(doc))
with open(f'output/{doc.stem}.txt', 'w') as f:
f.write(text)
如果需要在手机端集成OCR功能,PaddleOCR提供了轻量级模型:
python复制ocr = PaddleOCR(use_gpu=False, lang="ch", rec_model_dir='./ch_ppocr_mobile_v2.0_rec_infer')
这个配置内存占用可以控制在300MB以内,适合移动设备。
在实际使用中,我遇到过几个典型问题:
python复制ocr = PaddleOCR(rec_batch_num=4)
bash复制sudo apt install tesseract-ocr-chi-sim
python复制def preprocess(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
return cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
对于需要处理大量图片的场景,这些优化很有效:
python复制from multiprocessing import Pool
def ocr_task(img_path):
return ocr.ocr(img_path)
with Pool(4) as p:
results = p.map(ocr_task, image_files)
python复制def enhance_image(img):
img = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21)
img = cv2.detailEnhance(img, sigma_s=10, sigma_r=0.15)
return img
当基础功能不能满足需求时,可以考虑:
python复制from paddleocr import PPOCR
ppocr = PPOCR(
det_model_dir='./custom_det_model',
rec_model_dir='./custom_rec_model'
)
python复制roi = img[y1:y2, x1:x2]
text = pytesseract.image_to_string(roi)
python复制from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/ocr")
async def ocr_endpoint(file: UploadFile = File(...)):
contents = await file.read()
return {"text": ocr.ocr(contents)}
经过多个项目的实战检验,我发现没有绝对最好的OCR工具,只有最适合特定场景的选择。对于需要高精度的场景,PaddleOCR是不二之选;而对于简单的、大批量的英文文档处理,pytesseract可能更经济高效。关键是要先明确自己的需求,然后做针对性测试。