跳转至正文内容
开发者指南

在 Python 中使用 Tesseract OCR
借助 pytesseract。

完整且经过验证的 pytesseract 指南:安装、核心 API、图像预处理、PDF、置信度分数、PSM/OEM 配置、性能以及最常见的错误。

本页内容

    快速开始(三行代码)

    先安装引擎,再运行以下代码。完整配置见下文。

    ocr.py
    import pytesseract
    from PIL import Image
    
    text = pytesseract.image_to_string(Image.open("image.png"))
    print(text)

    视频:在 Python 中使用 Tesseract OCR

    3 行代码、置信度分数、OpenCV 预处理和常见错误,约 3 分钟讲完。

    3:08 · 英语旁白,画面带英文字幕

    安装 pytesseract

    pytesseract 只是一个封装,它调用 Tesseract 二进制文件,因此必须先安装引擎。

    bash
    pip install pytesseract pillow
    # 可选,用于预处理:
    pip install opencv-python numpy
    # 可选,用于 PDF 输入:
    pip install pdf2image

    如果引擎不在 PATH 中(Windows 常见),请显式指定:

    python
    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_xmlALTO XML档案 / 图书馆流水线
    api.py
    import pytesseract
    from PIL import Image
    from pytesseract import Output
    
    img = Image.open("image.png")
    
    text = pytesseract.image_to_string(img)                 # 纯文本
    data = pytesseract.image_to_data(img, output_type=Output.DICT)  # 文本框 + 置信度
    osd  = pytesseract.image_to_osd(img)                    # 方向 / 文字系统
    pdf  = pytesseract.image_to_pdf_or_hocr(img, extension="pdf")   # 可搜索 PDF

    配置:PSM、OEM、语言与字符白名单

    将选项作为空格分隔的字符串传给 config=。

    config.py
    # 单一文本块,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 3(默认:可用时使用 LSTM)、--oem 1(仅 LSTM)、--oem 0(旧版;需要包含旧版引擎数据的模型)。完整参考见文档。

    图像预处理

    干净的输入是提升准确率最重要的因素。以下步骤最关键。

    preprocess.py
    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 的置信度,并过滤噪声。

    confidence.py
    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 页面栅格化。

    pdf.py
    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。

    测量准确率

    测量字符和词的错误率,而不是凭肉眼判断输出。

    eval.py
    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。

    深入了解引擎与生态。