tesserocr Documentation

repository·master·Indexed 24 days ago

https://github.com/sirfz/tesserocr

A Python wrapper around the Tesseract OCR C++ API designed for use with Pillow (PIL) images. It provides high-performance OCR, supports concurrent execution by releasing the GIL, and includes the PyTessBaseAPI class for direct API access as well as high-level helper functions for image and file processing. Features include component image extraction (text lines, words), orientation and script detection (OSD), and support for Tesseract 4+ LSTM engines.

Tokens
3.4K
Snippets
10
Records
12
Agent score
30%

What's inside tesserocr

  1. Install tesserocr on Linux and BSD/MacOS

    master

    To install tesserocr on Linux or BSD/MacOS, you must first ensure the system dependencies libtesseract (>=3.04) and libleptonica (>=1.71) are installed. On Debian/Ubuntu, use:

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

    Once dependencies are installed, you can install the Python package via pip:

    $ pip install tesserocr

    If the setup script cannot detect your include/library directories, you can override them using CPPFLAGS:

    $ CPPFLAGS=-I/usr/local/include pip install tesserocr
  2. Configure Tesseract Data (tessdata)

    master

    After building Tesseract, you must download the trained data files and set the TESSDATA_PREFIX environment variable.

    cd F:\Project
    git clone --depth 1 https://github.com/tesseract-ocr/tessconfigs tessdata
    curl -L https://github.com/tesseract-ocr/tessdata/raw/4.1.0/eng.traineddata --output F:\Project\tessdata\eng.traineddata
    curl -L https://github.com/tesseract-ocr/tessdata/raw/4.1.0/osd.traineddata --output F:\Project\tessdata\osd.traineddata
    SET TESSDATA_PREFIX=F:\Project\tessdata
    cd F:\Project
    git clone --depth 1 https://github.com/tesseract-ocr/tessconfigs tessdata
    curl -L https://github.com/tesseract-ocr/tessdata/raw/4.1.0/eng.traineddata --output F:\Project\tessdata\eng.traineddata
    curl -L https://github.com/tesseract-ocr/tessdata/raw/4.1.0/osd.traineddata --output F:\Project\tessdata\osd.traineddata
    SET TESSDATA_PREFIX=F:\Project\tessdata
  3. Install Tesseract 4.1.1 on Windows (64-bit)

    master

    To build tesserocr on Windows, you must first manually build and install its dependencies: zlib, libpng, leptonica, and tesseract.

    Prerequisites

    1. Initialize Project Structure

    Set up a destination directory for dependencies and initialize the Visual Studio x64 environment.

    mkdir F:\win64
    set INSTALL_DIR=F:\win64
    set PATH=%PATH%;%INSTALL_DIR%\bin
    
    mkdir F:\Project & cd Project
    
    call "c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" x64

    Note: Replace F: with your preferred drive (e.g., C:).

    mkdir F:\win64
    set INSTALL_DIR=F:\win64
    set PATH=%PATH%;%INSTALL_DIR%\bin
    
    mkdir F:\Project & cd Project
    
    call "c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" x64
  4. Build tesserocr from source on Windows

    master

    Once the dependencies and Tesseract are installed, you can build the Python bindings.

    1. Clone the repository:
    git clone https://github.com/sirfz/tesserocr.git
    cd tesserocr
    1. Build and install using setup.py:
    SET VS90COMNTOOLS=%VS140COMNTOOLS%
    SET INCLUDE=%INCLUDE%;%INSTALL_DIR%\include
    SET LIBPATH=%LIBPATH%;%INSTALL_DIR%\lib
    
    pip install -r requirements-dev.txt
    python setup.py clean --all
    python setup.py build
    python setup.py bdist_wheel
    pip uninstall tesserocr
    pip install dist\tesserocr-2.5.2b0-cp38-cp38-win_amd64.whl
    1. Post-installation: Copy the required DLLs to your Python site-packages directory (adjust path to your Python version):
    copy F:\win64\bin\*.dll "C:\Program Files\Python38\Lib\site-packages\"
    SET VS90COMNTOOLS=%VS140COMNTOOLS%
    SET INCLUDE=%INCLUDE%;%INSTALL_DIR%\include
    SET LIBPATH=%LIBPATH%;%INSTALL_DIR%\lib
    
    pip install -r requirements-dev.txt
    python setup.py clean --all
    python setup.py build
    python setup.py bdist_wheel
    pip uninstall tesserocr
    pip install dist\tesserocr-2.5.2b0-cp38-cp38-win_amd64.whl
  5. Build and Install Dependencies (zlib, libpng, leptonica, tesseract)

    master

    Follow these steps in order to build the required C++ dependencies using CMake and Visual Studio.

    Build zlib

    curl https://zlib.net/zlib1211.zip
    "c:\Program Files\Git\usr\bin\unzip.exe" zlib1211.zip
    cd zlib-1.2.11
    mkdir build.msvs && cd build.msvs
    cmake .. -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR%
    "C:\Program Files\CMake\bin\cmake.exe"  --build . --config Release --target install
    cd ..\..

    Build libpng

    curl https://vorboss.dl.sourceforge.net/project/libpng/libpng16/1.6.37/lpng1637.zip
    "c:\Program Files\Git\usr\bin\unzip.exe" lpng1637.zip
    cd lpng1637
    mkdir build.msvs && cd build.msvs
    "C:\Program Files\CMake\bin\cmake.exe" .. -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR%
    "C:\Program Files\CMake\bin\cmake.exe"  --build . --config Release --target install
    cd ..\..

    Build leptonica

    curl -L https://github.com/DanBloomberg/leptonica/archive/master.zip --output leptonica.zip
    "c:\Program Files\Git\usr\bin\unzip.exe" leptonica.zip
    cd leptonica-master
    
    mkdir build.msvs && cd build.msvs
    "C:\Program Files\CMake\bin\cmake.exe" .. -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DCMAKE_PREFIX_PATH=%INSTALL_DIR% -DCMAKE_BUILD_TYPE=Release -DBUILD_PROG=OFF -DSW_BUILD=OFF -DBUILD_SHARED_LIBS=ON
    "C:\Program Files\CMake\bin\cmake.exe" --build . --config Release --target install
    cd ..\..

    Build tesseract

    curl -L https://github.com/tesseract-ocr/tesseract/archive/4.1.1.zip --output tesseract.zip
    "c:\Program Files\Git\usr\bin\unzip.exe" tesseract.zip
    cd tesseract-4.1.1
    
    mkdir build.msvs && cd build.msvs
    "C:\Program Files\CMake\bin\cmake.exe" .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=%INSTALL_DIR% -DCMAKE_PREFIX_PATH=%INSTALL_DIR% -DBUILD_TRAINING_TOOLS=OFF -DSW_BUILD=OFF -DBUILD_SHARED_LIBS=ON -DOPENMP_BUILD=OFF -DLeptonica_DIR=%INSTALL_DIR%\lib\cmake
    "C:\Program Files\CMake\bin\cmake.exe" --build . --config Release --target install
    cd ..\..
  6. Install tesserocr on Windows

    master

    For Windows, the recommended method is using Conda, which provides stand-alone packages containing all necessary Windows libraries (no separate Tesseract installation required).

    Using the simonflueckiger channel:

    > conda install -c simonflueckiger tesserocr

    Using the conda-forge channel:

    > conda install -c conda-forge tesserocr

    Alternatively, you can download pre-built wheel files from the simonflueckiger/tesserocr-windows_build/releases repository and install them via pip:

    > pip install <package_name>.whl
  7. Configure tessdata path

    master

    If tesserocr cannot automatically detect your tessdata path (which contains .traineddata files), you can specify it in two ways:

    1. Set the TESSDATA_PREFIX environment variable.
    2. Pass the path argument when initializing PyTessBaseAPI.

    You can verify available languages and the current tessdata path using get_languages().

  8. Extract component images (text lines, words, etc.)

    master

    You can use api.GetComponentImages to extract specific components of an image (like text lines) as individual PIL image objects and bounding boxes. This is useful for granular analysis.

    from PIL import Image
    from tesserocr import PyTessBaseAPI, RIL
    
    image = Image.open('sample.tif')
    with PyTessBaseAPI() as api:
        api.SetImage(image)
        # RIL.TEXTLINE specifies the level of components to extract
        boxes = api.GetComponentImages(RIL.TEXTLINE, True)
        
        for i, (im, box, _, _) in enumerate(boxes):
            # im is a PIL image object
            # box is a dict with 'x', 'y', 'w', 'h' keys
            api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
            ocr_result = api.GetUTF8Text()
            confidence = api.MeanTextConf()
            print(f"Box[{i}]: {ocr_result} (Conf: {confidence})")
    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):
            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}")
  9. Perform Orientation and Script Detection (OSD)

    master

    You can detect image orientation and script type using different Page Segmentation Modes (PSM).

    Using PSM.AUTO_OSD to analyze layout:

    from PIL import Image
    from tesserocr import PyTessBaseAPI, PSM
    
    with PyTessBaseAPI(psm=PSM.AUTO_OSD) as api:
        api.SetImage(Image.open("image.tif"))
        api.Recognize()
        it = api.AnalyseLayout()
        orientation, direction, order, deskew_angle = it.Orientation()
        print(f"Orientation: {orientation}")

    Using PSM.OSD_ONLY for direct script/orientation detection:

    from tesserocr import PyTessBaseAPI, PSM
    
    with PyTessBaseAPI(psm=PSM.OSD_ONLY) as api:
        api.SetImageFile("image.tif")
        os = api.DetectOS()
        print(f"Orientation: {os['orientation']}")
        print(f"Script: {os['script']}")

    Using LSTM engine for improved detection (Tesseract 4+):

    from tesserocr import PyTessBaseAPI, PSM, OEM
    
    with PyTessBaseAPI(psm=PSM.OSD_ONLY, oem=OEM.LSTM_ONLY) as api:
        api.SetImageFile("image.tif")
        api.Recognize()
        os = api.DetectOrientationScript()
        print(f"Orientation: {os['orient_deg']}")
        print(f"Script: {os['script_name']}")
    from PIL import Image
    from tesserocr import PyTessBaseAPI, PSM
    
    with PyTessBaseAPI(psm=PSM.AUTO_OSD) as api:
        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))
  10. Verify tesserocr installation

    master

    To ensure tesserocr is working correctly, run the following Python script. This checks the version, available languages, and performs a basic OCR task using a PIL image.

    import tesserocr
    print(tesserocr.PyTessBaseAPI.Version())
    print(tesserocr.get_languages())
    
    from PIL import Image
    image = Image.open(r'F:	est_image.png')
    with tesserocr.PyTessBaseAPI() as api:
        api.SetImage(image)
        print(api.GetUTF8Text())
    import tesserocr
    print(tesserocr.PyTessBaseAPI.Version())
    print(tesserocr.get_languages())
    
    from PIL import Image
    image = Image.open(r'F:\Project\tesserocr\tests\eurotext.png')
    with tesserocr.PyTessBaseAPI() as api:
        api.SetImage(image)
        print(api.GetUTF8Text())
  11. Use tesserocr helper functions

    master

    For simple tasks, tesserocr provides high-level helper functions that work directly with Pillow (PIL) images or file paths. These functions are thread-safe and can be used with Python's threading module for efficient concurrent processing.

    import tesserocr
    from PIL import Image
    
    # Check version and available languages
    print(tesserocr.tesseract_version())
    print(tesserocr.get_languages())
    
    # OCR from a PIL Image object
    image = Image.open('sample.jpg')
    print(tesserocr.image_to_text(image))
    
    # OCR from a file path
    print(tesserocr.file_to_text('sample.jpg'))
    import tesserocr
    from PIL import Image
    
    print(tesserocr.tesseract_version())
    print(tesserocr.get_languages())
    
    image = Image.open('sample.jpg')
    print(tesserocr.image_to_text(image))
    print(tesserocr.file_to_text('sample.jpg'))
  12. Use PyTessBaseAPI for OCR tasks

    master

    The PyTessBaseAPI class provides direct access to the Tesseract C++ API. It is highly recommended to use it as a context manager (via a with statement) to ensure the API is automatically finalized. If not using a context manager, you must call api.End() explicitly.

    Example of reusing an API instance for multiple images:

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