Convert Figma logo to code with AI

sirfz logotesserocr

A Python wrapper for the tesseract-ocr API

1,989
255
1,989
52

Top Related Projects

Tesseract Open Source OCR Engine (main repository)

A Python wrapper for Google Tesseract

Pure Javascript OCR for more than 100 Languages 📖🎉🖥

Trained models with fast variant of the "best" LSTM models + legacy models

13,565

OCRmyPDF adds an OCR text layer to scanned PDF files, allowing them to be searched

Quick Overview

Tesserocr is a Python wrapper for the Tesseract OCR engine. It provides a simple, Pythonic interface to Tesseract, allowing developers to easily integrate optical character recognition capabilities into their Python projects. The library combines the speed of the Tesseract C++ API with the ease of use of Python.

Pros

  • Easy to use Pythonic interface for Tesseract OCR
  • Supports both Python 2 and 3
  • Provides access to low-level Tesseract API features
  • Faster than using Tesseract through subprocess calls

Cons

  • Requires Tesseract to be installed separately
  • Installation can be complex on some systems
  • Limited documentation compared to some other OCR libraries
  • Depends on the accuracy and limitations of the underlying Tesseract engine

Code Examples

Basic usage to read text from an image:

from tesserocr import PyTessBaseAPI

with PyTessBaseAPI() as api:
    api.SetImageFile('path/to/image.png')
    print(api.GetUTF8Text())

Reading text with a specific language:

from tesserocr import PyTessBaseAPI

with PyTessBaseAPI(lang='fra') as api:
    api.SetImageFile('path/to/french_text.png')
    print(api.GetUTF8Text())

Getting word-level bounding boxes:

from tesserocr import PyTessBaseAPI, RIL

with PyTessBaseAPI() as api:
    api.SetImageFile('path/to/image.png')
    boxes = api.GetComponentImages(RIL.WORD, True)
    for i, (im, box, _, _) in enumerate(boxes):
        api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
        ocrResult = api.GetUTF8Text()
        conf = api.MeanTextConf()
        print(f"Word {i}: {ocrResult} (Confidence: {conf})")

Getting Started

  1. Install Tesseract OCR on your system (follow instructions for your OS)
  2. Install tesserocr using pip:
pip install tesserocr
  1. Use in your Python code:
from tesserocr import PyTessBaseAPI

with PyTessBaseAPI() as api:
    api.SetImageFile('path/to/your/image.png')
    print(api.GetUTF8Text())

Note: On Windows, you may need to specify the Tesseract data path:

from tesserocr import PyTessBaseAPI, get_tesseract_version
import os

tessdata_path = 'C:\\Program Files\\Tesseract-OCR\\tessdata'
with PyTessBaseAPI(path=tessdata_path) as api:
    api.SetImageFile('path/to/your/image.png')
    print(api.GetUTF8Text())

Competitor Comparisons

Tesseract Open Source OCR Engine (main repository)

Pros of tesseract

  • Provides pre-built binaries for Windows, making installation easier
  • Offers a wider range of language data files for OCR
  • Includes additional tools and utilities for image processing

Cons of tesseract

  • Larger repository size due to included binaries and language data
  • May require more setup for non-Windows platforms
  • Less focused on Python integration compared to tesserocr

Code Comparison

tesseract (command-line usage):

tesseract image.png output -l eng

tesserocr (Python integration):

from tesserocr import PyTessBaseAPI

with PyTessBaseAPI() as api:
    api.SetImageFile('image.png')
    print(api.GetUTF8Text())

tesseract focuses on providing a complete OCR solution with pre-built binaries and language data, making it easier to use out-of-the-box, especially on Windows. It offers a command-line interface and additional tools for image processing.

tesserocr, on the other hand, is a Python wrapper for Tesseract OCR, providing a more streamlined integration for Python developers. It has a smaller repository size and is more focused on providing a Python API for Tesseract functionality.

The choice between the two depends on the specific use case, development environment, and preferred programming language.

A Python wrapper for Google Tesseract

Pros of pytesseract

  • Easier to install and set up, as it's a pure Python wrapper
  • More widely used and has a larger community
  • Supports a broader range of image formats out of the box

Cons of pytesseract

  • Generally slower performance compared to tesserocr
  • Less direct access to Tesseract's C++ API
  • May have limitations when dealing with complex OCR tasks

Code Comparison

pytesseract

import pytesseract
from PIL import Image

text = pytesseract.image_to_string(Image.open('image.png'))
print(text)

tesserocr

from tesserocr import PyTessBaseAPI

with PyTessBaseAPI() as api:
    api.SetImageFile('image.png')
    print(api.GetUTF8Text())

Both libraries provide Python bindings for Tesseract OCR, but tesserocr offers more direct access to Tesseract's C++ API, potentially allowing for more advanced usage and better performance. pytesseract, on the other hand, is easier to set up and use, making it a popular choice for simpler OCR tasks. The code examples demonstrate the basic usage of each library to extract text from an image file.

Pure Javascript OCR for more than 100 Languages 📖🎉🖥

Pros of tesseract.js

  • Runs in the browser, making it more accessible for web-based applications
  • Easier to set up and use, with no need for complex system dependencies
  • Supports a wider range of platforms due to its JavaScript implementation

Cons of tesseract.js

  • Generally slower performance compared to native implementations
  • May have limitations in handling complex OCR tasks or large-scale processing
  • Potentially less accurate for certain languages or specialized use cases

Code Comparison

tesseract.js:

Tesseract.recognize(
  'https://tesseract.projectnaptha.com/img/eng_bw.png',
  'eng',
  { logger: m => console.log(m) }
).then(({ data: { text } }) => {
  console.log(text);
})

tesserocr:

from tesserocr import PyTessBaseAPI

with PyTessBaseAPI() as api:
    api.SetImageFile('/path/to/image.png')
    print(api.GetUTF8Text())

The code examples demonstrate the different approaches: tesseract.js uses a Promise-based API in JavaScript, while tesserocr utilizes a Python wrapper around the Tesseract C++ library. tesseract.js is more suited for web environments, while tesserocr offers tighter integration with the native Tesseract engine, potentially providing better performance and more advanced features for desktop or server-side applications.

Trained models with fast variant of the "best" LSTM models + legacy models

Pros of tessdata

  • Comprehensive collection of trained language data for Tesseract OCR
  • Regularly updated with new language models and improvements
  • Official repository maintained by the Tesseract OCR team

Cons of tessdata

  • Limited to providing language data, not a full OCR solution
  • Requires additional setup and integration with Tesseract OCR engine

Code comparison

tessdata doesn't contain code, as it's a repository for language data. tesserocr, on the other hand, provides Python bindings for Tesseract OCR. Here's a basic example of using tesserocr:

from tesserocr import PyTessBaseAPI

with PyTessBaseAPI() as api:
    api.SetImageFile('image.png')
    print(api.GetUTF8Text())

Additional notes

tessdata is essential for Tesseract OCR functionality, providing the necessary language models. tesserocr, while not an official Tesseract project, offers a convenient way to integrate Tesseract OCR into Python applications. The choice between them depends on your specific needs: if you're looking for language data, tessdata is the go-to repository. If you need Python bindings for Tesseract, tesserocr is more suitable.

13,565

OCRmyPDF adds an OCR text layer to scanned PDF files, allowing them to be searched

Pros of OCRmyPDF

  • Designed specifically for PDF processing, offering a more comprehensive solution for PDF-related tasks
  • Provides additional features like PDF optimization, metadata handling, and automatic image processing
  • Supports batch processing of multiple PDF files

Cons of OCRmyPDF

  • Limited to PDF files, while tesserocr can work with various image formats
  • May have a steeper learning curve due to its more extensive feature set
  • Requires additional dependencies for full functionality

Code Comparison

OCRmyPDF:

import ocrmypdf

ocrmypdf.ocr('input.pdf', 'output.pdf', deskew=True, optimize=3, skip_text=True)

tesserocr:

from tesserocr import PyTessBaseAPI

with PyTessBaseAPI() as api:
    api.SetImageFile('input.png')
    text = api.GetUTF8Text()
    print(text)

OCRmyPDF is tailored for PDF processing with built-in optimization and OCR capabilities, while tesserocr provides a more low-level interface to Tesseract OCR for various image formats. OCRmyPDF offers a higher-level API for PDF-specific tasks, whereas tesserocr gives more fine-grained control over the OCR process itself.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

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

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('---------------------------------------------')