在 Python 中使用 Tesseract OCR
借助 pytesseract。
完整且经过验证的 pytesseract 指南:安装、核心 API、图像预处理、PDF、置信度分数、PSM/OEM 配置、性能以及最常见的错误。
快速开始(三行代码)
先安装引擎,再运行以下代码。完整配置见下文。
import pytesseract
from PIL import Image
text = pytesseract.image_to_string(Image.open("image.png"))
print(text)安装 pytesseract
pytesseract 只是一个封装,它调用 Tesseract 二进制文件,因此必须先安装引擎。
pip install pytesseract pillow
# 可选,用于预处理:
pip install opencv-python numpy
# 可选,用于 PDF 输入:
pip install pdf2image如果引擎不在 PATH 中(Windows 常见),请显式指定:
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"初次使用引擎?请参阅适用于 Windows、macOS、Linux、Docker 和 WSL 的安装指南。
核心 API
pytesseract 为每种输出类型提供一个函数,按需选择。
| 函数 | 返回 | 适用场景 |
|---|---|---|
image_to_string | 纯文本 | 只需要识别出的文字 |
image_to_data | 逐词边界框 + 置信度 | 高亮文字、过滤低置信度词 |
image_to_boxes | 逐字符边界框 | 字符级几何信息 |
image_to_pdf_or_hocr | 可搜索 PDF 或 hOCR | 生成可搜索 PDF 或网页叠加层 |
image_to_osd | 方向与文字体系检测 | OCR 前检测旋转或文字体系 |
image_to_alto_xml | ALTO XML | 档案 / 图书馆流水线 |
配置:PSM、OEM、语言与字符白名单
将选项作为空格分隔的字符串传给 config=。
# 单一文本块,LSTM 引擎,简体中文
text = pytesseract.image_to_string(img, lang="chi_sim", config="--oem 3 --psm 6")
# 仅数字(小票合计、仪表读数)
text = pytesseract.image_to_string(img, config="--psm 7 -c tessedit_char_whitelist=0123456789.")
# 组合语言
text = pytesseract.image_to_string(img, lang="eng+chi_sim")| PSM | 模式 | 适用场景 |
|---|---|---|
| 3 | 全自动(默认) | 标准文档 |
| 4 | 可变大小的单列文本 | 文章、单栏页面 |
| 6 | 单一均匀文本块 | 段落、标签 |
| 7 | 单行文本 | 单行标题、单个字段 |
| 8 | 单个词 | 单个词 |
| 11 | 稀疏文本 | 小票、分散的界面文字 |
| 13 | 原始行 | 不经 Tesseract 处理的单行 |
OEM 模式:--oem 1(仅 LSTM,v5 默认)、--oem 0(旧版)、--oem 3(自动)。完整参考见文档。
图像预处理
干净的输入是提升准确率最重要的因素。以下步骤最关键。
import cv2, numpy as np, pytesseract
from PIL import Image
image = cv2.imread("receipt.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 将小字放大到约 300 DPI 等效
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
# 去噪,然后用 Otsu 阈值转成纯黑白
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
text = pytesseract.image_to_string(Image.fromarray(binary))- 灰度 — 阈值处理前去掉颜色通道。
- 放大 — 小于约 20 像素的文字识别很差,需要放大。
- 阈值 — 均匀光照用 Otsu,不均匀光照用自适应阈值。
- 去噪 — 轻度模糊可去除被误读为标点的噪点。
- 纠偏 — OCR 前用
cv2.minAreaRect校正旋转。 - 裁掉边缘 — 去除干扰版面分析的深色扫描边缘。
文字位置与置信度分数
用 image_to_data 获取逐词边界框和 0–100 的置信度,并过滤噪声。
from pytesseract import Output
data = pytesseract.image_to_data(img, output_type=Output.DICT)
for text, conf in zip(data["text"], data["conf"]):
if text.strip() and float(conf) > 60: # 丢弃低置信度噪声
print(round(float(conf)), text)在 Python 中对 PDF 做 OCR
Tesseract 处理的是图片,因此先用 pdf2image(需要 poppler)把 PDF 页面栅格化。
import io, pytesseract
from pdf2image import convert_from_path
from pypdf import PdfWriter, PdfReader
pages = convert_from_path("scan.pdf", dpi=300) # 需要 poppler
writer = PdfWriter()
for page in pages:
pdf_bytes = pytesseract.image_to_pdf_or_hocr(page, extension="pdf")
writer.add_page(PdfReader(io.BytesIO(pdf_bytes)).pages[0])
with open("scan_searchable.pdf", "wb") as f:
writer.write(f)在 Windows 上,通过 poppler_path= 传入 poppler 的 bin 文件夹。更完整的流程请参阅输出格式文档。
性能
pytesseract 每次调用都会调用 CLI,因此吞吐量取决于你的组织方式。
| 方式 | 适用场景 | 取舍 |
|---|---|---|
每次调用 pytesseract | 脚本和一次性任务 | 每次调用启动进程 — 循环中很慢 |
| 合并为多页 TIFF | 多页、相同设置 | 一个进程处理多页 |
multiprocessing | 大量独立图片 | 使用所有核心;内存更高 |
tesserocr | 高吞吐、进程内 | 原生绑定,配置更复杂 |
错误目录
以下错误涵盖了 pytesseract 的绝大多数问题。
| 错误 | 原因 | 解决方法 |
|---|---|---|
TesseractNotFoundError | 二进制未安装或不在 PATH | 安装引擎或设置 pytesseract.pytesseract.tesseract_cmd。 |
(-215:Assertion failed) src.type() == CV_8UC1 | 对 3 通道图像做阈值处理 | 先用 cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 转换。 |
Error opening data file ...fra.traineddata | 缺少语言包 | 安装该语言或设置 TESSDATA_PREFIX。 |
| 输出为空 | DPI 低、PSM 错误或没有文字 | 放大,尝试 --psm 6/7/11,并预处理。 |
| 循环中非常慢 | 每次调用启动一个进程 | 批量处理、使用 multiprocessing 或 tesserocr。 |
测量准确率
测量字符和词的错误率,而不是凭肉眼判断输出。
import pytesseract, jiwer
from PIL import Image
hypothesis = pytesseract.image_to_string(Image.open("sample.png"))
reference = open("sample.gt.txt").read()
print("CER:", jiwer.cer(reference, hypothesis))
print("WER:", jiwer.wer(reference, hypothesis))保留一小组有基准文本的代表性图片作为回归测试,在更改预处理或配置后重新运行。
Python 常见问题
如何在 Python 中使用 Tesseract OCR?
先安装引擎,再运行 pip install pytesseract pillow。用 Pillow 打开图片并调用 pytesseract.image_to_string(img)。
为什么会出现 TesseractNotFoundError?
pytesseract 找不到二进制文件。安装引擎、把它放入 PATH,或将 pytesseract.pytesseract.tesseract_cmd 设为完整路径。
如何提升准确率?
放大到约 300 DPI、灰度、阈值、去噪、纠偏,并使用正确的 --psm。使用合适的 lang=,对固定字段使用字符白名单。
如何对 PDF 做 OCR?
用 pdf2image(配合 poppler)把页面转为图片,对每页运行 pytesseract,并用 image_to_pdf_or_hocr(..., extension="pdf") 合并。
如何获取置信度分数?
使用 image_to_data(..., output_type=Output.DICT),并按 conf 列表过滤。
pytesseract 很慢吗?
每次调用都会启动一个进程。可批量处理、使用 multiprocessing,或改用进程内的 tesserocr。
后续步骤
深入了解引擎与生态。