语言数据(.traineddata)需单独下载,且版本要与 tesseract --version 匹配;tessdata 路径无法自动检测时需设置 TESSDATA_PREFIX 或传给 PyTessBaseAPI;没有可用 wheel 时会从源码编译,需先装 libtesseract(>=3.04)、libleptonica(>=1.71) 和 Cython(>=3.1.8,<3.4);多线程时每个 worker 要用独立的 PyTessBaseAPI 实例,部分 Tesseract 参数是进程级全局的
tesserocr
sirfzMIT活跃维护用 Cython 封装的 Tesseract OCR Python 库,可直接调用底层 API 做文字识别,比命令行调用更高效、控制更细。
A Python wrapper for the tesseract-ocr API
pip install tesserocrREADME 未说明显存或 GPU 要求;OCR 由 Tesseract 在 CPU 上执行。预编译 wheel 已内置 Tesseract、Leptonica 及其运行时依赖,无需单独安装 Tesseract。
用 Cython 直接封装 Tesseract C++ API 的 Python OCR 库,比调命令行更快更省事
用 Cython 封装的 Tesseract OCR Python 库,可直接调用底层 API 做文字识别,比命令行调用更高效、控制更细。
核心能力
- 用 Cython 直接绑定 Tesseract C++ API,源码简洁易读
- 识别时释放 GIL,配合 threading 实现真正的并发执行
- 对 Pillow 友好,可直接传入 PIL.Image 对象或图片文件
- 提供 PyTessBaseAPI 上下文管理器,可复用实例批量识别多张图
- 支持取词框、置信度、OSD 方向检测和逐字符候选迭代
容易踩的坑
- 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
- test LSTM choice wrapping independently of OCR scores by @mvanhorn in https://github.com/sirfz/tesserocr/pull/392
- Build CPython 3.15 and 3.15t wheels by @sirfz in https://github.com/sirfz/tesserocr/pull/393
- Support free-threaded Python with cooperative signal cancellation by @sirfz in https://github.com/sirfz/tesserocr/pull/394
- Windows wheels by @sirfz in https://github.com/sirfz/tesserocr/pull/395
New Contributors
- @mvanhorn made their first contribution in https://github.com/sirfz/tesserocr/pull/392
Full Changelog: https://github.com/sirfz/tesserocr/compare/v2.11.0...v2.12.0
- v2.11.0tesserocr v2.11.02026-08-04 · 2026-08-04 12:28 UTC
查看更新说明
What's Changed
- Catch exception in get_languages() by @cjmayo in https://github.com/sirfz/tesserocr/pull/387
- Fix test_init_full box.train file_type by @cjmayo in https://github.com/sirfz/tesserocr/pull/388
- fix
_pix_to_imagememory leak (#391)
New Contributors
- @cjmayo made their first contribution in https://github.com/sirfz/tesserocr/pull/387
Full Changelog: https://github.com/sirfz/tesserocr/compare/v2.10.0...v2.11.0
- v2.10.0tesserocr v2.10.02026-01-13 · 2026-01-13 15:39 UTC
查看更新说明
What's Changed
- place long running API calls in cysignals blocks by @bertsky in https://github.com/sirfz/tesserocr/pull/384
Full Changelog: https://github.com/sirfz/tesserocr/compare/v2.9.2...v2.10.0
- v2.9.2tesserocr v2.9.22025-12-18 · 2025-12-18 08:51 UTC
查看更新说明
What's Changed
- Make AnalyseLayout interruptible by @bertsky in https://github.com/sirfz/tesserocr/pull/382
- ci: switch to macos-15-intel for x86 build by @sirfz in https://github.com/sirfz/tesserocr/pull/383
Full Changelog: https://github.com/sirfz/tesserocr/compare/v2.9.1...v2.9.2
- 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
- feat(ci): test built wheels by @nijel in https://github.com/sirfz/tesserocr/pull/380
- fix: build against older leptonica version by @nijel in https://github.com/sirfz/tesserocr/pull/381
Full Changelog: https://github.com/sirfz/tesserocr/compare/v2.9.0...v2.9.1
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
========= 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
PyTessBaseAPIinstance 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, includingClearandEnd. - Keep the API alive while using its iterators. Calls such as
Init,SetImage,Recognize,ClearandEndinvalidate existing iterators. - Some Tesseract parameters, particularly in
classifyandtextord, 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 toSetVariable,SetDebugVariable, config files andInitFullvariables. - Leptonica's log level and Tesseract's persistent cache are also process-wide.
Set
set_leptonica_log_leveland callClearPersistentCacheonly 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('---------------------------------------------')