tesserocr

sirfzMIT活跃维护

用 Cython 封装的 Tesseract OCR Python 库,可直接调用底层 API 做文字识别,比命令行调用更高效、控制更细。

A Python wrapper for the tesseract-ocr API

v2.12.0发布于 2026-10-22 16:36 UTC2,181star262fork同步于 2026-11-10 17:47 UTC

怎么上手

由 README 提炼,执行前请确认
pip install tesserocr
硬件要求按 README 说明

README 未说明显存或 GPU 要求;OCR 由 Tesseract 在 CPU 上执行。预编译 wheel 已内置 Tesseract、Leptonica 及其运行时依赖,无需单独安装 Tesseract。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

用 Cython 直接封装 Tesseract C++ API 的 Python OCR 库,比调命令行更快更省事

用 Cython 封装的 Tesseract OCR Python 库,可直接调用底层 API 做文字识别,比命令行调用更高效、控制更细。

核心能力

  • 用 Cython 直接绑定 Tesseract C++ API,源码简洁易读
  • 识别时释放 GIL,配合 threading 实现真正的并发执行
  • 对 Pillow 友好,可直接传入 PIL.Image 对象或图片文件
  • 提供 PyTessBaseAPI 上下文管理器,可复用实例批量识别多张图
  • 支持取词框、置信度、OSD 方向检测和逐字符候选迭代

容易踩的坑

语言数据(.traineddata)需单独下载,且版本要与 tesseract --version 匹配;tessdata 路径无法自动检测时需设置 TESSDATA_PREFIX 或传给 PyTessBaseAPI;没有可用 wheel 时会从源码编译,需先装 libtesseract(>=3.04)、libleptonica(>=1.71) 和 Cython(>=3.1.8,<3.4);多线程时每个 worker 要用独立的 PyTessBaseAPI 实例,部分 Tesseract 参数是进程级全局的

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v2.12.0
  1. v2.12.0tesserocr v2.12.0最新正式版2026-10-22 · 2026-10-22 16:36 UTC

    Binary wheels built with:

    • Leptonica v1.87.0
    • Tesseract v5.5.3

    What's Changed

    New Contributors

    Full Changelog: https://github.com/sirfz/tesserocr/compare/v2.11.0...v2.12.0

  2. v2.11.0tesserocr v2.11.02026-08-04 · 2026-08-04 12:28 UTC
    查看更新说明

    What's Changed

    New Contributors

    Full Changelog: https://github.com/sirfz/tesserocr/compare/v2.10.0...v2.11.0

  3. v2.10.0tesserocr v2.10.02026-01-13 · 2026-01-13 15:39 UTC
    查看更新说明

    What's Changed

    Full Changelog: https://github.com/sirfz/tesserocr/compare/v2.9.2...v2.10.0

  4. v2.9.2tesserocr v2.9.22025-12-18 · 2025-12-18 08:51 UTC
    查看更新说明

    What's Changed

    Full Changelog: https://github.com/sirfz/tesserocr/compare/v2.9.1...v2.9.2

  5. v2.9.1tesserocr v2.9.12025-10-10 · 2025-10-10 13:15 UTC
    查看更新说明

    (fixed) Python 3.14 wheels have landed!

    Binary wheels built with:

    • Leptonica v1.85.0
    • Tesseract v5.5.1

    What's Changed

    Full Changelog: https://github.com/sirfz/tesserocr/compare/v2.9.0...v2.9.1

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    ========= tesserocr

    A simple, |Pillow|_-friendly, wrapper around the tesseract-ocr API for Optical Character Recognition (OCR).

    .. image:: https://github.com/sirfz/tesserocr/actions/workflows/build.yml/badge.svg :target: https://github.com/sirfz/tesserocr/actions/workflows/build.yml :alt: Github Actions build status

    .. image:: https://img.shields.io/pypi/v/tesserocr.svg?maxAge=2592000 :target: https://pypi.python.org/pypi/tesserocr :alt: Latest version on PyPi

    .. image:: https://img.shields.io/pypi/pyversions/tesserocr.svg?maxAge=2592000 :alt: Supported python versions

    tesserocr integrates directly with Tesseract's C++ API using Cython which allows for a simple Pythonic and easy-to-read source code. It enables real concurrent execution when used with Python's threading module by releasing the GIL while processing an image in tesseract.

    tesserocr is designed to be |Pillow|_-friendly but can also be used with image files instead.

    .. |Pillow| replace:: Pillow .. _Pillow: http://python-pillow.github.io/

    Requirements

    Python 3.10+ is required. tesserocr no longer supports Python 2.

    Building from source requires libtesseract (>=3.04) and libleptonica (>=1.71).

    On Debian/Ubuntu:

    ::

    $ apt-get install tesseract-ocr libtesseract-dev libleptonica-dev pkg-config
    

    You may need to manually compile tesseract_ for a more recent version. Note that you may need to update your LD_LIBRARY_PATH environment variable to point to the right library versions in case you have multiple tesseract/leptonica installations.

    |Cython|_ (>=3.1.8,<3.4) is required for building and optionally |Pillow|_ to support PIL.Image objects.

    .. _manually compile tesseract: https://github.com/tesseract-ocr/tesseract/wiki/Compiling .. |Cython| replace:: Cython .. _Cython: http://cython.org/

    Installation

    Install from PyPI:

    ::

    $ pip install tesserocr
    

    Pre-built wheels for Linux, macOS, and 64-bit Windows bundle Tesseract, Leptonica, and their runtime dependencies. No separate Tesseract installation is required to use these wheels. Language data must still be installed separately (see tessdata_).

    Conda

    Alternatively, install from the conda-forge <https://anaconda.org/conda-forge/tesserocr>_ channel:

    ::

    $ conda install -c conda-forge tesserocr
    

    Build from source

    If a wheel is not available for your platform or Python version, pip will build from source using the dependencies listed above.

    The setup script attempts to detect the include/library dirs (via |pkg-config|_ if available) but you can override them with your own parameters, e.g.:

    ::

    $ CPPFLAGS=-I/usr/local/include pip install tesserocr
    

    or

    ::

    $ python setup.py build_ext -I/usr/local/include
    

    For Windows source builds, see Windows.build.md_.

    The build renders tesserocr/tesserocr.templ.pyx and tesserocr/tesseract.templ.pxd using Cython's bundled Tempita engine before running Cython. Edit these templates, not the generated .pyx and .pxd files. Templates keep their Cython extensions for editor support and put Tempita directives on ### {{...}} comment lines. No separate Tempita installation is needed. Rendering uses the detected Tesseract version and updates generated files only when their contents change. Use separate source trees for concurrent builds against different Tesseract versions.

    To run the build-time template and version-branch checks from a checkout:

    ::

    $ pip install -r requirements-dev.txt
    $ python -m unittest tests.test_build -v
    

    .. |pkg-config| replace:: pkg-config .. _pkg-config: https://pkgconfig.freedesktop.org/ .. _Windows.build.md: Windows.build.md

    tessdata

    You may need to point to the tessdata path if it cannot be detected automatically. This can be done by setting the TESSDATA_PREFIX environment variable or by passing the path to PyTessBaseAPI (e.g.: PyTessBaseAPI(path='/usr/share/tessdata')). The path should contain .traineddata files which can be found at https://github.com/tesseract-ocr/tessdata.

    Make sure you have the correct version of traineddata for your tesseract --version.

    You can list the current supported languages on your system using the get_languages function:

    .. code:: python

    from tesserocr import get_languages
    
    print(get_languages('/usr/share/tessdata'))  # or any other path that applies to your system
    

    Usage

    Initialize and re-use the tesseract API instance to score multiple images:

    .. code:: python

    from tesserocr import PyTessBaseAPI
    
    images = ['sample.jpg', 'sample2.jpg', 'sample3.jpg']
    
    with PyTessBaseAPI() as api:
        for img in images:
            api.SetImageFile(img)
            print(api.GetUTF8Text())
            print(api.AllWordConfidences())
    # api is automatically finalized when used in a with-statement (context manager).
    # otherwise api.End() should be explicitly called when it's no longer needed.
    

    PyTessBaseAPI exposes several tesseract API methods. Make sure you read their docstrings for more info.

    Basic example using available helper functions:

    .. code:: python

    import tesserocr
    from PIL import Image
    
    print(tesserocr.tesseract_version())  # print tesseract-ocr version
    print(tesserocr.get_languages())  # prints tessdata path and list of available languages
    
    image = Image.open('sample.jpg')
    print(tesserocr.image_to_text(image))  # print ocr text from image
    # or
    print(tesserocr.file_to_text('sample.jpg'))
    

    Thread safety and free-threaded Python

    tesserocr supports free-threaded CPython without enabling the GIL on import. image_to_text and file_to_text can process independent images concurrently. The same ownership rules apply with or without the GIL:

    • Use a separate PyTessBaseAPI instance per worker. Instances and their iterators have no internal lock. Do not call an active instance from another thread or re-enter it from a signal handler, including Clear and End.
    • Keep the API alive while using its iterators. Calls such as Init, SetImage, Recognize, Clear and End invalidate existing iterators.
    • Some Tesseract parameters, particularly in classify and textord, are process-wide even with separate API instances. Configure these before starting parallel native work and do not change them while it runs. This applies to SetVariable, SetDebugVariable, config files and InitFull variables.
    • Leptonica's log level and Tesseract's persistent cache are also process-wide. Set set_leptonica_log_level and call ClearPersistentCache only while no native work is running. Use separate processes for independent settings that must change during OCR.

    Recognize, GetUTF8Text, image_to_text and file_to_text use Tesseract's cooperative cancellation to propagate Python signal exceptions (such as KeyboardInterrupt) after recognition unwinds safely. Python handles signals only on the main thread: interrupting the main thread does not cancel OCR running in a worker. Layout analysis and other native operations without cancellation checkpoints may delay signal handling until they return.

    Advanced API Examples

    GetComponentImages example:

    
    .. code:: python
    
        from PIL import Image
        from tesserocr import PyTessBaseAPI, RIL
    
        image = Image.open('/usr/src/tesseract/testing/phototest.tif')
        with PyTessBaseAPI() as api:
            api.SetImage(image)
            boxes = api.GetComponentImages(RIL.TEXTLINE, True)
            print(f'Found {len(boxes)} textline image components.')
            for i, (im, box, _, _) in enumerate(boxes):
                # im is a PIL image object
                # box is a dict with x, y, w and h keys
                api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
                ocrResult = api.GetUTF8Text()
                conf = api.MeanTextConf()
                print(f"Box[{i}]: x={box['x']}, y={box['y']}, w={box['w']}, h={box['h']}, "
                      f"confidence: {conf}, text: {ocrResult}")
    
    Orientation and script detection (OSD):
    

    .. code:: python

    from PIL import Image
    from tesserocr import PyTessBaseAPI, PSM
    
    with PyTessBaseAPI(psm=PSM.AUTO_OSD) as api:
        image = Image.open("/usr/src/tesseract/testing/eurotext.tif")
        api.SetImage(image)
        api.Recognize()
    
        it = api.AnalyseLayout()
        orientation, direction, order, deskew_angle = it.Orientation()
        print("Orientation: {:d}".format(orientation))
        print("WritingDirection: {:d}".format(direction))
        print("TextlineOrder: {:d}".format(order))
        print("Deskew angle: {:.4f}".format(deskew_angle))
    

    or more simply with OSD_ONLY page segmentation mode:

    .. code:: python

    from tesserocr import PyTessBaseAPI, PSM
    
    with PyTessBaseAPI(psm=PSM.OSD_ONLY) as api:
        api.SetImageFile("/usr/src/tesseract/testing/eurotext.tif")
    
        os = api.DetectOS()
        print("Orientation: {orientation}\nOrientation confidence: {oconfidence}\n"
              "Script: {script}\nScript confidence: {sconfidence}".format(**os))
    

    more human-readable info with tesseract 4+ (demonstrates LSTM engine usage):

    .. code:: python

    from tesserocr import PyTessBaseAPI, PSM, OEM
    
    with PyTessBaseAPI(psm=PSM.OSD_ONLY, oem=OEM.LSTM_ONLY) as api:
        api.SetImageFile("/usr/src/tesseract/testing/eurotext.tif")
    
        os = api.DetectOrientationScript()
        print("Orientation: {orient_deg}\nOrientation confidence: {orient_conf}\n"
              "Script: {script_name}\nScript confidence: {script_conf}".format(**os))
    

    Iterator over the classifier choices for a single symbol:

    
    .. code:: python
    
        from tesserocr import PyTessBaseAPI, RIL, iterate_level
    
        with PyTessBaseAPI() as api:
            api.SetImageFile('/usr/src/tesseract/testing/phototest.tif')
            api.SetVariable("save_blob_choices", "T")
            api.SetRectangle(37, 228, 548, 31)
            api.Recognize()
    
            ri = api.GetIterator()
            level = RIL.SYMBOL
            for r in iterate_level(ri, level):
                symbol = r.GetUTF8Text(level)  # r == ri
                conf = r.Confidence(level)
                if symbol:
                    print(f'symbol {symbol}, conf: {conf}', end='')
                indent = False
                ci = r.GetChoiceIterator()
                for c in ci:
                    if indent:
                        print('\t\t ', end='')
                    print('\t- ', end='')
                    choice = c.GetUTF8Text()  # c == ci
                    print(f'{choice} conf: {c.Confidence()}')
                    indent = True
                print('---------------------------------------------')