简介:本文系统阐述Python图像处理中的OCR技术,涵盖基础原理、主流工具库对比、代码实现及优化策略,助力开发者快速构建高效文字识别系统。
OCR(Optical Character Recognition)技术通过图像处理与模式识别将图片中的文字转换为可编辑文本,其核心流程包括图像预处理、特征提取、文字检测与识别四个阶段。Python凭借丰富的图像处理库(如OpenCV、Pillow)和机器学习框架(如TensorFlow、PyTorch),成为OCR开发的优选语言。
cv2.threshold()实现自适应二值化,可有效分离文字与背景。| 工具库 | 类型 | 优势 | 适用场景 |
|---|---|---|---|
| Tesseract | 开源传统OCR | 支持100+语言,可训练自定义模型 | 多语言文档识别 |
| EasyOCR | 深度学习 | 开箱即用,支持80+语言 | 快速原型开发 |
| PaddleOCR | 深度学习 | 中文识别率高,支持垂直场景 | 中文文档、复杂排版识别 |
| PyTesseract | Tesseract封装 | 简化Python调用流程 | 兼容Tesseract所有功能 |
# 基础环境pip install opencv-python pillow numpy# 选择OCR引擎(以EasyOCR为例)pip install easyocr# 或Tesseract(需单独安装引擎)# sudo apt install tesseract-ocr # Linux# brew install tesseract # Macpip install pytesseract
import cv2import numpy as npdef preprocess_image(img_path):# 读取图像img = cv2.imread(img_path)# 灰度化gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 高斯降噪blurred = cv2.GaussianBlur(gray, (5,5), 0)# 自适应阈值二值化binary = cv2.adaptiveThreshold(blurred, 255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY, 11, 2)# 倾斜校正(简化示例)coords = np.column_stack(np.where(binary > 0))angle = cv2.minAreaRect(coords)[-1]if angle < -45:angle = -(90 + angle)else:angle = -angle(h, w) = binary.shape[:2]center = (w // 2, h // 2)M = cv2.getRotationMatrix2D(center, angle, 1.0)rotated = cv2.warpAffine(binary, M, (w, h))return rotated
import pytesseractfrom PIL import Imagedef tesseract_ocr(img_path):# 调用预处理函数processed_img = preprocess_image(img_path)# 保存临时文件供Tesseract使用temp_path = "temp_processed.png"cv2.imwrite(temp_path, processed_img)# 配置Tesseract参数(示例:仅识别中文)custom_config = r'--oem 3 --psm 6 -l chi_sim'# 执行识别text = pytesseract.image_to_string(Image.open(temp_path),config=custom_config)return text
import easyocrdef easyocr_demo(img_path):# 创建reader对象(指定语言)reader = easyocr.Reader(['ch_sim', 'en'])# 执行识别result = reader.readtext(img_path)# 提取文本text = '\n'.join([item[1] for item in result])return text
cv2.equalizeHist())或CLAHE算法。
import pdf2imagedef pdf_to_text(pdf_path):images = pdf2image.convert_from_path(pdf_path)full_text = ""for i, img in enumerate(images):img.save(f"page_{i}.png")text = tesseract_ocr(f"page_{i}.png")full_text += text + "\n"return full_text
import albumentations as Atransform = A.Compose([A.RandomRotate90(),A.OneOf([A.GaussianBlur(p=0.5),A.MotionBlur(p=0.5)]),A.RandomBrightnessContrast(p=0.2)])
app = FastAPI()
class OCRRequest(BaseModel):
image_path: str
engine: str = “easyocr” # 可选tesseract/easyocr/paddle
@app.post(“/ocr”)
async def ocr_endpoint(request: OCRRequest):
if request.engine == “easyocr”:
return {“text”: easyocr_demo(request.image_path)}
# 其他引擎实现...
```
中文识别率低:
-l chi_sim+eng多语言混合模式复杂背景干扰:
多语言混合文档:
本文系统梳理了Python实现OCR的全流程,从基础原理到实战代码,覆盖了传统方法与深度学习方案。开发者可根据具体场景选择Tesseract(低成本)、EasyOCR(快速开发)或PaddleOCR(高精度)作为技术栈,并通过图像预处理、模型调优和后处理技术持续提升识别效果。实际项目中,建议先通过小规模测试验证技术路线,再逐步扩展至生产环境。