1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
|
=========
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
============
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|_ (>=0.23) 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
============
Linux and BSD/MacOS
-------------------
::
$ pip install tesserocr
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
Tested on Linux and BSD/MacOS
.. |pkg-config| replace:: **pkg-config**
.. _pkg-config: https://pkgconfig.freedesktop.org/
Windows
-------
The proposed downloads consist of stand-alone packages containing all the Windows libraries needed for execution. This means that no additional installation of tesseract is required on your system.
The recommended method of installation is via Conda as described below.
Conda
`````
You can use the `simonflueckiger <https://anaconda.org/simonflueckiger/tesserocr>`_ channel to install from Conda:
::
> conda install -c simonflueckiger tesserocr
Or alternatively the `conda-forge <https://anaconda.org/conda-forge/tesserocr>`_ channel:
::
> conda install -c conda-forge tesserocr
pip
```
Download the wheel file corresponding to your Windows platform and Python installation from `simonflueckiger/tesserocr-windows_build/releases <https://github.com/simonflueckiger/tesserocr-windows_build/releases>`_ and install them via:
::
> pip install <package_name>.whl
Build from source
`````````````````
If you need Windows tessocr package and your Python version is not supported by above mentioned project,
you can try to follow `step by step instructions for Windows 64bit` in `Windows.build.md`_.
.. _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'))
``image_to_text`` and ``file_to_text`` can be used with ``threading`` to
concurrently process multiple images which is highly efficient.
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('Found {} textline image components.'.format(len(boxes)))
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(u"Box[{0}]: x={x}, y={y}, w={w}, h={h}, "
"confidence: {1}, text: {2}".format(i, conf, ocrResult, **box))
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 __future__ import print_function
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(u'symbol {}, conf: {}'.format(symbol, 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(u'{} conf: {}'.format(choice, c.Confidence()))
indent = True
print('---------------------------------------------')
|