### Build and Install libpng (Windows Command Line) Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md Downloads, unzips, configures with CMake, builds, and installs the libpng library, a PNG image format reference library. It uses the same INSTALL_DIR for installation. ```batch 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 and Install zlib (Windows Command Line) Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md Downloads, unzips, configures with CMake, builds, and installs the zlib compression library. It specifies the installation directory using the INSTALL_DIR environment variable. ```batch 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 ..\.. ``` -------------------------------- ### Tesserocr Build and Installation (Windows Command Line) Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md Clones the tesserocr repository, sets up necessary environment variables for the compiler and linker, installs development requirements, cleans previous builds, and then builds and installs the tesserocr Python wheel package. ```batch git clone https://github.com/sirfz/tesserocr.git cd tesserocr 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 ``` -------------------------------- ### Check Tesseract Installation (Windows Command Line) Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md Verifies the Tesseract installation by running `tesseract -v` and displays the version information along with details about its dependencies and enabled features. ```batch %INSTALL_DIR%\bin\tesseract -v ``` -------------------------------- ### Build and Install Tesseract OCR (Windows Command Line) Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md Downloads or clones the Tesseract OCR engine, configures it with CMake, and builds/installs it. It specifies installation paths, build type, and disables training tools and OpenMP support. ```batch 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 or git clone -b 4.1.1 --depth 1 https://github.com/tesseract-ocr/tesseract.git cd tesseract Then: 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 ..\.. ``` -------------------------------- ### Project Structure Initialization (Windows Command Line) Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md Sets up the necessary directory structure and environment variables for the Tesseract installation on Windows. It creates a destination directory for dependencies and adds it to the system's PATH. ```batch mkdir F:\win64 set INSTALL_DIR=F:\win64 set PATH=%PATH%;%INSTALL_DIR%\bin ``` -------------------------------- ### Tesseract Post-Installation Setup (Windows Command Line) Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md Clones the tessconfigs repository for language configuration files and downloads the English (`eng.traineddata`) and OSD (`osd.traineddata`) model files. It then sets the TESSDATA_PREFIX environment variable to point to the downloaded data. ```batch 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 ``` -------------------------------- ### Initialize VS Environment (Windows Command Line) Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md Calls the Visual Studio 2019 64-bit environment setup script to ensure the compiler and tools are available in the command prompt. ```batch call "c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" x64 ``` -------------------------------- ### Verify Tesserocr Installation and Perform OCR Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md This snippet demonstrates how to check the installed Tesserocr version, list available language data, and use the PyTessBaseAPI to extract text from an image file using the PIL library. ```python import tesserocr from PIL import Image # Check version and languages print(tesserocr.PyTessBaseAPI.Version()) print(tesserocr.get_languages()) # Perform OCR on an image image = Image.open(r'F:\Project\tesserocr\tests\eurotext.png') with tesserocr.PyTessBaseAPI() as api: api.SetImage(image) print(api.GetUTF8Text()) ``` -------------------------------- ### Perform OCR on Multiple Images with Tesserocr Source: https://github.com/sirfz/tesserocr/blob/master/README.rst Shows a basic example of initializing the Tesserocr API and processing multiple images. It iterates through a list of image files, sets each as the current image for the API, and extracts UTF-8 text and word confidences. The example utilizes a context manager for automatic API finalization. ```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. ``` -------------------------------- ### GetComponentImages Example Source: https://github.com/sirfz/tesserocr/blob/master/README.rst Shows how to extract individual text line components from an image and perform OCR on each. ```APIDOC ## GetComponentImages Example ### Description This example demonstrates how to use `GetComponentImages` to extract bounding boxes and images of text lines from a larger image, and then perform OCR on each extracted component. ### Method N/A (Python script) ### Endpoint N/A (Python script) ### Parameters N/A ### Request Example ```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}") ``` ### Response Prints the number of textline components found, followed by details for each component including its bounding box, OCR text, and confidence score. ``` -------------------------------- ### Build and Install Leptonica (Windows Command Line) Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md Downloads or clones the Leptonica image processing library, configures it with CMake, and builds/installs it. It sets specific CMake options to disable certain features and enable shared libraries. ```batch 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 or "C:\Program Files\Git\cmd\git.exe" clone --depth 1 https://github.com/DanBloomberg/leptonica.git cd leptonica Then: 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 ..\.. ``` -------------------------------- ### Basic Tesserocr Usage Source: https://github.com/sirfz/tesserocr/blob/master/README.rst Demonstrates how to get tesseract version, available languages, and perform basic OCR on an image file. ```APIDOC ## Basic Tesserocr Usage ### Description This section shows how to retrieve the tesseract version, list available languages, and perform OCR on an image file using tesserocr. ### Method N/A (Python script) ### Endpoint N/A (Python script) ### Parameters N/A ### Request Example ```python 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)) # or print(tesserocr.file_to_text('sample.jpg')) ``` ### Response Output will be printed to the console, including tesseract version, language list, and OCR text from the image. ``` -------------------------------- ### Generating Output Files with Tesserocr's ProcessPages Source: https://context7.com/sirfz/tesserocr/llms.txt This example demonstrates using the `ProcessPages` method in tesserocr to automatically generate output files in various formats like hOCR, PDF, and plain text. It also shows how to process multi-page TIFF files. Requires input image files. ```python from tesserocr import PyTessBaseAPI with PyTessBaseAPI() as api: # Enable desired renderers api.SetVariable("tessedit_create_hocr", "1") api.SetVariable("tessedit_create_pdf", "1") api.SetVariable("tessedit_create_txt", "1") # Process single image - outputs: output.hocr, output.pdf, output.txt success = api.ProcessPages( outputbase='output', filename='document.png', timeout=30000 # 30 second timeout ) if success: print("Files generated successfully") else: print("Processing failed") # Process multi-page TIFF with PyTessBaseAPI() as api: api.SetVariable("tessedit_create_pdf", "1") api.ProcessPages('multipage_output', 'multipage.tiff') ``` -------------------------------- ### Tesserocr Post-Installation DLL Copy (Windows Command Line) Source: https://github.com/sirfz/tesserocr/blob/master/Windows.build.md Copies the necessary DLL files from the Tesseract installation directory to the Python site-packages directory to ensure that the tesserocr wrapper can find and load the Tesseract libraries at runtime. ```batch copy F:\win64\bin\*.dll "C:\Program Files\Python38\Lib\site-packages\" ``` -------------------------------- ### Extract text from PIL Image Source: https://context7.com/sirfz/tesserocr/llms.txt Demonstrates how to perform OCR on a PIL Image object using helper functions. Includes examples for language selection, page segmentation modes, and engine configuration. ```python from PIL import Image import tesserocr image = Image.open('document.jpg') text = tesserocr.image_to_text(image) print(text) text = tesserocr.image_to_text(image, lang='deu+eng') text = tesserocr.image_to_text( image, lang='eng', psm=tesserocr.PSM.SINGLE_LINE ) text = tesserocr.image_to_text( image, lang='eng', oem=tesserocr.OEM.LSTM_ONLY ) grayscale_image = image.convert('L') text = tesserocr.image_to_text(grayscale_image, lang='eng') print(text) ``` -------------------------------- ### Getting OCR Results in Various Formats with Tesserocr Source: https://context7.com/sirfz/tesserocr/llms.txt This snippet shows how to obtain OCR results from an image in multiple formats: hOCR (HTML-based), Box (for training), TSV (tab-separated values), and UNLV. It processes a single image and prints the beginning of each output format. Requires an image file. ```python from tesserocr import PyTessBaseAPI with PyTessBaseAPI() as api: api.SetImageFile('document.png') # hOCR format (HTML with OCR metadata) hocr = api.GetHOCRText(0) # 0 = first page print("hOCR output:") print(hocr[:500]) # Box format (for training) box_text = api.GetBoxText(0) print("\nBox format:") print(box_text[:200]) # TSV format (tab-separated values) tsv = api.GetTSVText(0) print("\nTSV format:") print(tsv[:300]) # UNLV format unlv = api.GetUNLVText() print("\nUNLV format:") print(unlv[:200]) ``` -------------------------------- ### Manual API instance management Source: https://context7.com/sirfz/tesserocr/llms.txt Demonstrates manual initialization and termination of the PyTessBaseAPI, useful when the context manager pattern is not applicable. ```python from tesserocr import PyTessBaseAPI, PSM, OEM from PIL import Image api = PyTessBaseAPI(init=False) try: api.Init( path='/usr/share/tessdata/', lang='eng', oem=OEM.LSTM_ONLY, psm=PSM.AUTO ) image = Image.open('document.png') api.SetImage(image) text = api.GetUTF8Text() print(text) finally: api.End() ``` -------------------------------- ### Perform Basic OCR with Tesserocr Source: https://github.com/sirfz/tesserocr/blob/master/README.rst Demonstrates how to initialize the tesserocr library, check versions, and extract text from an image file or PIL object. ```python 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')) ``` -------------------------------- ### List Supported Languages with Tesserocr Source: https://github.com/sirfz/tesserocr/blob/master/README.rst Demonstrates how to retrieve a list of languages supported by Tesserocr, specifying the path to the tessdata directory. This is useful for verifying language data availability. ```python from tesserocr import get_languages print(get_languages('/usr/share/tessdata')) # or any other path that applies to your system ``` -------------------------------- ### Configure Tesseract Parameters Source: https://context7.com/sirfz/tesserocr/llms.txt Illustrates how to set internal Tesseract variables to control character whitelisting, blacklisting, mode selection, and output formats. ```python from tesserocr import PyTessBaseAPI with PyTessBaseAPI() as api: api.SetVariable("tessedit_char_blacklist", "xyz") api.SetVariable("tessedit_char_whitelist", "0123456789") api.SetVariable("classify_bln_numeric_mode", "1") api.SetVariable("tessedit_create_pdf", "1") api.SetImageFile('numbers.png') print(api.GetUTF8Text()) val = api.GetVariableAsString("tessedit_char_blacklist") int_val = api.GetIntVariable("tessedit_pageseg_mode") bool_val = api.GetBoolVariable("tessedit_create_hocr") ``` -------------------------------- ### Load Images for OCR Source: https://context7.com/sirfz/tesserocr/llms.txt Demonstrates how to provide image data to the Tesseract engine using PIL objects or direct file paths, including setting source resolution for improved accuracy. ```python from tesserocr import PyTessBaseAPI from PIL import Image with PyTessBaseAPI() as api: image = Image.open('photo.jpg') api.SetImage(image) text1 = api.GetUTF8Text() api.SetImageFile('document.png') text2 = api.GetUTF8Text() api.SetImage(image) api.SetSourceResolution(300) text3 = api.GetUTF8Text() print(text1, text2, text3) ``` -------------------------------- ### Orientation and Script Detection (OSD) Source: https://github.com/sirfz/tesserocr/blob/master/README.rst Demonstrates how to detect the orientation, script, and writing direction of an image. ```APIDOC ## Orientation and Script Detection (OSD) ### Description This section covers detecting the orientation, script, and writing direction of an image using tesserocr. It shows two methods: one using `AnalyseLayout` and another using `DetectOS` with `OSD_ONLY` page segmentation mode. It also includes an example for tesseract 4+ using the LSTM engine. ### Method N/A (Python script) ### Endpoint N/A (Python script) ### Parameters N/A ### Request Example ```python from PIL import Image from tesserocr import PyTessBaseAPI, PSM # Method 1: Using AnalyseLayout 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)) # Method 2: Using DetectOS with OSD_ONLY 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)) # Method 3: Tesseract 4+ with LSTM engine from tesserocr import 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)) ``` ### Response Prints detected orientation, writing direction, textline order, deskew angle, script name, and their respective confidence scores. ``` -------------------------------- ### Detecting Orientation and Script with Tesserocr Source: https://context7.com/sirfz/tesserocr/llms.txt Demonstrates how to detect the orientation and script of a document image using Tesserocr. It shows basic detection with `DetectOS` and more detailed detection with `DetectOrientationScript`, including orientation degrees, confidence levels, and script names. ```python from tesserocr import PyTessBaseAPI, PSM with PyTessBaseAPI(psm=PSM.AUTO_OSD) as api: api.SetImageFile('rotated_doc.png') api.Recognize() # Basic orientation and script detection os_result = api.DetectOS() if os_result: print(f"Orientation: {os_result['orientation']}") # 0-3 print(f"Orientation confidence: {os_result['oconfidence']}") print(f"Script index: {os_result['script']}") print(f"Script confidence: {os_result['sconfidence']}") # More detailed detection (Tesseract 4+) with PyTessBaseAPI(psm=PSM.OSD_ONLY) as api: api.SetImageFile('document.png') result = api.DetectOrientationScript() if result: print(f"Rotation needed: {result['orient_deg']} degrees") print(f"Orientation confidence: {result['orient_conf']}") print(f"Script: {result['script_name']}") # e.g., "Latin" print(f"Script confidence: {result['script_conf']}") ``` -------------------------------- ### Iterate Over Classifier Choices Source: https://github.com/sirfz/tesserocr/blob/master/README.rst Demonstrates how to iterate through symbols in an image and retrieve multiple classifier choices for each symbol with their respective confidence levels. ```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.Recognize() ri = api.GetIterator() for r in iterate_level(ri, RIL.SYMBOL): symbol = r.GetUTF8Text(RIL.SYMBOL) ci = r.GetChoiceIterator() for c in ci: print(f'{c.GetUTF8Text()} conf: {c.Confidence()}') ``` -------------------------------- ### Selecting OCR Engine Modes (OEM) with Tesserocr Source: https://context7.com/sirfz/tesserocr/llms.txt Shows how to select different OCR Engine Modes (OEM) for Tesseract using PyTessBaseAPI. It demonstrates using the default OEM, LSTM_ONLY for higher accuracy (Tesseract 4+), and TESSERACT_ONLY for legacy engines. The selected engine mode and recognized text are printed. ```python from tesserocr import PyTessBaseAPI, OEM # Different OEM modes with PyTessBaseAPI(oem=OEM.DEFAULT) as api: api.SetImageFile('document.png') print(f"Engine mode: {api.oem()}") print(api.GetUTF8Text()) # LSTM only (Tesseract 4+, most accurate) with PyTessBaseAPI(oem=OEM.LSTM_ONLY) as api: api.SetImageFile('document.png') print(api.GetUTF8Text()) # Legacy Tesseract only (faster, less accurate) with PyTessBaseAPI(oem=OEM.TESSERACT_ONLY) as api: api.SetImageFile('document.png') print(api.GetUTF8Text()) ``` -------------------------------- ### Perform OCR using PyTessBaseAPI context manager Source: https://context7.com/sirfz/tesserocr/llms.txt Uses the PyTessBaseAPI class as a context manager to process multiple images efficiently while ensuring proper resource cleanup. ```python from tesserocr import PyTessBaseAPI from PIL import Image images = ['page1.jpg', 'page2.jpg', 'page3.jpg'] with PyTessBaseAPI() as api: for img_path in images: api.SetImageFile(img_path) text = api.GetUTF8Text() confidences = api.AllWordConfidences() print(f"File: {img_path}") print(f"Text: {text}") print(f"Word confidences: {confidences}") print("---") with PyTessBaseAPI(path='/usr/share/tessdata/', lang='eng+fra') as api: api.SetImageFile('multilingual_doc.png') print(api.GetUTF8Text()) ``` -------------------------------- ### Detect Orientation and Script (OSD) Source: https://github.com/sirfz/tesserocr/blob/master/README.rst Shows how to use Tesseract's OSD capabilities to determine image orientation, writing direction, and script information, including LSTM-based detection. ```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}\nScript: {script_name}".format(**os)) ``` -------------------------------- ### Extracting Text Components with Tesserocr Source: https://context7.com/sirfz/tesserocr/llms.txt Demonstrates how to extract words, text lines with block and paragraph IDs, and regions from an image using Tesserocr's convenience methods. It utilizes PyTessBaseAPI to process an image file and iterate through different text components. ```python from tesserocr import PyTessBaseAPI from PIL import Image with PyTessBaseAPI() as api: api.SetImageFile('document.png') # Get all words as (image, bounding_box) tuples words = api.GetWords() for img, bbox in words: print(f"Word at ({bbox['x']}, {bbox['y']}), " f"size: {bbox['w']}x{bbox['h']}") # Get text lines with block IDs textlines = api.GetTextlines(blockids=True, paraids=True) for img, bbox, block_id, para_id in textlines: print(f"Line in block {block_id}, para {para_id}") # Get regions (layout analysis results) regions = api.GetRegions() for img, bbox in regions: print(f"Region: {bbox}") ``` -------------------------------- ### Analyzing Layout and Iterating Results with Tesserocr Source: https://context7.com/sirfz/tesserocr/llms.txt Explains how to access detailed layout analysis and recognition results using Tesserocr. It covers obtaining layout information like orientation and deskew angle, and iterating through words with their text, confidence, bounding box, and font attributes. ```python from tesserocr import PyTessBaseAPI, RIL, PSM, iterate_level from PIL import Image with PyTessBaseAPI(psm=PSM.AUTO_OSD) as api: image = Image.open('document.png') api.SetImage(image) api.Recognize() # Get layout iterator layout = api.AnalyseLayout() if layout: # Get orientation info orientation, direction, order, deskew_angle = layout.Orientation() print(f"Orientation: {orientation}") print(f"Writing direction: {direction}") print(f"Textline order: {order}") print(f"Deskew angle: {deskew_angle:.4f} radians") # Iterate through words with detailed info with PyTessBaseAPI() as api: api.SetImageFile('document.png') api.Recognize() iterator = api.GetIterator() level = RIL.WORD for word in iterate_level(iterator, level): text = word.GetUTF8Text(level) conf = word.Confidence(level) bbox = word.BoundingBox(level) # Font attributes font_attrs = word.WordFontAttributes() print(f"Word: '{text}', Confidence: {conf:.1f}%") print(f" Bounding box: {bbox}") print(f" Font: {font_attrs['font_name']}, " f"Bold: {font_attrs['bold']}, " f"Italic: {font_attrs['italic']}") # Check word properties if word.WordIsFromDictionary(): print(" (found in dictionary)") if word.WordIsNumeric(): print(" (numeric)") ``` -------------------------------- ### Tesseract Configuration Source: https://context7.com/sirfz/tesserocr/llms.txt Configures Tesseract's internal parameters using key-value pairs. Supports setting variables and retrieving their values. ```APIDOC ## SetVariable ### Description Configures Tesseract internal parameters. ### Method `SetVariable(key: str, value: str)` `GetVariableAsString(key: str)` `GetIntVariable(key: str)` `GetBoolVariable(key: str)` ### Endpoint N/A (Methods within PyTessBaseAPI class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from tesserocr import PyTessBaseAPI with PyTessBaseAPI() as api: # Blacklist characters (won't be recognized) api.SetVariable("tessedit_char_blacklist", "xyz") # Whitelist only digits api.SetVariable("tessedit_char_whitelist", "0123456789") # Enable numeric-only mode api.SetVariable("classify_bln_numeric_mode", "1") # Suppress debug output api.SetVariable("debug_file", "/dev/null") # Configure PDF output api.SetVariable("tessedit_create_pdf", "1") api.SetVariable("textonly_pdf", "0") api.SetImageFile('numbers.png') print(api.GetUTF8Text()) # Get variable values with PyTessBaseAPI() as api: val = api.GetVariableAsString("tessedit_char_blacklist") int_val = api.GetIntVariable("tessedit_pageseg_mode") bool_val = api.GetBoolVariable("tessedit_create_hocr") print(f"Blacklist: {val}, PSM: {int_val}, hOCR: {bool_val}") ``` ### Response #### Success Response (200) N/A (Methods modify internal state or return variable values) #### Response Example N/A ``` -------------------------------- ### Perform Recognition and Analyze Confidence Source: https://context7.com/sirfz/tesserocr/llms.txt Explains how to execute the recognition process with timeouts and retrieve confidence scores for the overall text or individual words. ```python from tesserocr import PyTessBaseAPI with PyTessBaseAPI() as api: api.SetImageFile('document.png') success = api.Recognize(timeout=5000) if success: text = api.GetUTF8Text() mean_conf = api.MeanTextConf() word_conf_pairs = api.MapWordConfidences() for word, conf in word_conf_pairs: print(f"'{word}': {conf}%") ``` -------------------------------- ### Image Input Methods Source: https://context7.com/sirfz/tesserocr/llms.txt Methods for providing images to the OCR engine, either from a PIL Image object or a file path. Includes setting source resolution. ```APIDOC ## SetImage and SetImageFile ### Description Methods for providing images to the OCR engine. ### Method `SetImage(image: PIL.Image.Image)` or `SetImageFile(filepath: str)` ### Endpoint N/A (Method within PyTessBaseAPI class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from tesserocr import PyTessBaseAPI from PIL import Image with PyTessBaseAPI() as api: # From PIL Image object image = Image.open('photo.jpg') api.SetImage(image) text1 = api.GetUTF8Text() # From file path api.SetImageFile('document.png') text2 = api.GetUTF8Text() # Set source resolution for accurate font size calculation api.SetImage(image) api.SetSourceResolution(300) # 300 DPI text3 = api.GetUTF8Text() print(text1, text2, text3) ``` ### Response #### Success Response (200) N/A (Methods modify internal state) #### Response Example N/A ``` -------------------------------- ### Query Tesseract system information Source: https://context7.com/sirfz/tesserocr/llms.txt Retrieves available OCR languages and library version information for debugging and configuration purposes. ```python import tesserocr path, languages = tesserocr.get_languages() print(f"Tessdata path: {path}") print(f"Available languages: {languages}") path, languages = tesserocr.get_languages('/opt/tessdata/') print(f"Languages in {path}: {languages}") version_info = tesserocr.tesseract_version() print(version_info) ``` -------------------------------- ### Accessing Alternative Character Choices with Tesserocr Source: https://context7.com/sirfz/tesserocr/llms.txt This snippet demonstrates how to retrieve alternative character recognition choices for each symbol identified by Tesserocr. It iterates through symbols and their confidence levels, then accesses and prints any alternative choices with their respective confidences. Requires an image file with ambiguous text. ```python from tesserocr import PyTessBaseAPI, RIL, iterate_level with PyTessBaseAPI() as api: api.SetImageFile('ambiguous_text.png') api.SetVariable("save_blob_choices", "T") api.SetRectangle(37, 228, 548, 31) # Specific region api.Recognize() iterator = api.GetIterator() level = RIL.SYMBOL for symbol_iter in iterate_level(iterator, level): symbol = symbol_iter.GetUTF8Text(level) conf = symbol_iter.Confidence(level) if symbol: print(f"Symbol: '{symbol}', confidence: {conf:.1f}%") # Get alternative choices choice_iter = symbol_iter.GetChoiceIterator() if choice_iter: print(" Alternatives:") for choice in choice_iter: alt_text = choice.GetUTF8Text() alt_conf = choice.Confidence() print(f" '{alt_text}': {alt_conf:.1f}%") ``` -------------------------------- ### Controlling Page Segmentation Modes (PSM) in Tesserocr Source: https://context7.com/sirfz/tesserocr/llms.txt Illustrates how to control Tesseract's page segmentation modes (PSM) using PyTessBaseAPI. Different PSM modes are shown for various text layouts, from automatic detection to single character recognition. The current PSM and recognized text are printed. ```python from tesserocr import PyTessBaseAPI, PSM # Different PSM modes for different use cases with PyTessBaseAPI() as api: api.SetImageFile('image.png') # Auto - let Tesseract decide (default) api.SetPageSegMode(PSM.AUTO) # Single column of text api.SetPageSegMode(PSM.SINGLE_COLUMN) # Single uniform block of text api.SetPageSegMode(PSM.SINGLE_BLOCK) # Single text line api.SetPageSegMode(PSM.SINGLE_LINE) # Single word api.SetPageSegMode(PSM.SINGLE_WORD) # Single character api.SetPageSegMode(PSM.SINGLE_CHAR) # Sparse text - find as much text as possible api.SetPageSegMode(PSM.SPARSE_TEXT) print(f"Current PSM: {api.GetPageSegMode()}") print(api.GetUTF8Text()) ``` -------------------------------- ### Analyze Image Components with PyTessBaseAPI Source: https://github.com/sirfz/tesserocr/blob/master/README.rst Uses PyTessBaseAPI to segment an image into text lines and perform OCR on individual components, extracting confidence scores and text. ```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) 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}]: confidence: {conf}, text: {ocrResult}") ``` -------------------------------- ### Iterator over Classifier Choices Source: https://github.com/sirfz/tesserocr/blob/master/README.rst Demonstrates iterating through classifier choices for individual symbols within a recognized text region. ```APIDOC ## Iterator over Classifier Choices ### Description This example shows how to iterate over the classifier choices for a single symbol within a specified region of an image. It involves setting a variable to save blob choices and then using `GetIterator` and `iterate_level` to access symbol-level information and their associated confidence scores. ### Method N/A (Python script) ### Endpoint N/A (Python script) ### Parameters N/A ### Request Example ```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('---------------------------------------------') ``` ### Response For each recognized symbol in the specified region, this will print the symbol itself, its confidence score, and then a list of alternative choices with their confidence scores. ``` -------------------------------- ### Extract text from image file path Source: https://context7.com/sirfz/tesserocr/llms.txt Shows how to extract text directly from an image file path. This method is efficient for direct processing without manual image loading. ```python import tesserocr text = tesserocr.file_to_text('invoice.png') print(text) text = tesserocr.file_to_text( 'receipt.jpg', lang='eng', psm=tesserocr.PSM.SINGLE_BLOCK ) text = tesserocr.file_to_text( 'document.tif', lang='fra', path='/usr/local/share/tessdata/' ) print(text) ``` -------------------------------- ### PyTessBaseAPI Class Source: https://context7.com/sirfz/tesserocr/llms.txt The main API class for advanced Tesseract interaction, providing fine-grained control over the recognition process. ```APIDOC ## PyTessBaseAPI ### Description Provides a full-featured interface for Tesseract. It is recommended to use this as a context manager to ensure proper resource cleanup. ### Methods - **SetImage(image)**: Sets the image to be processed. - **SetImageFile(path)**: Sets the image file path. - **GetUTF8Text()**: Returns the recognized text. - **AllWordConfidences()**: Returns confidence levels for each word. - **Init(...)**: Initializes the API with specific settings. - **End()**: Cleans up resources. ### Request Example ```python from tesserocr import PyTessBaseAPI with PyTessBaseAPI() as api: api.SetImageFile('image.jpg') text = api.GetUTF8Text() ``` ``` -------------------------------- ### Thread-Safe Batch OCR Processing with Tesserocr Source: https://context7.com/sirfz/tesserocr/llms.txt This snippet illustrates how to perform OCR on multiple images concurrently using Python's `ThreadPoolExecutor`. It highlights tesserocr's thread-safe nature, allowing multiple threads to process images simultaneously. It includes a function for processing individual images and an alternative approach for reusing an API instance per thread. Requires image files. ```python import tesserocr from PIL import Image from concurrent.futures import ThreadPoolExecutor import os def process_image(image_path): """Process a single image - thread-safe.""" try: text = tesserocr.file_to_text(image_path, lang='eng') return {'file': image_path, 'text': text, 'error': None} except Exception as e: return {'file': image_path, 'text': None, 'error': str(e)} # Process multiple images concurrently image_files = ['doc1.png', 'doc2.png', 'doc3.png', 'doc4.png'] with ThreadPoolExecutor(max_workers=4) as executor: results = list(executor.map(process_image, image_files)) for result in results: if result['error']: print(f"Error processing {result['file']}: {result['error']}") else: print(f"Processed {result['file']}: {len(result['text'])} chars") # Alternative: reuse API instance per thread def process_with_api(image_paths): """Process multiple images reusing a single API instance.""" results = [] with tesserocr.PyTessBaseAPI() as api: for path in image_paths: api.SetImageFile(path) text = api.GetUTF8Text() conf = api.MeanTextConf() results.append({'file': path, 'text': text, 'confidence': conf}) return results ``` -------------------------------- ### Extract Image Components Source: https://context7.com/sirfz/tesserocr/llms.txt Retrieves specific layout components like text lines, words, or blocks from an image, providing their bounding boxes and associated text content. ```python from tesserocr import PyTessBaseAPI, RIL from PIL import Image image = Image.open('newspaper.png') with PyTessBaseAPI() as api: api.SetImage(image) boxes = api.GetComponentImages(RIL.TEXTLINE, True) for i, (im, box, block_id, para_id) in enumerate(boxes): api.SetRectangle(box['x'], box['y'], box['w'], box['h']) text = api.GetUTF8Text() print(f"Line {i}: {text.strip()}") ``` -------------------------------- ### Component Image Extraction Source: https://context7.com/sirfz/tesserocr/llms.txt Extracts image components at different levels (blocks, paragraphs, lines, words) along with their bounding boxes. ```APIDOC ## GetComponentImages ### Description Extracts image components at different levels (blocks, paragraphs, lines, words). ### Method `GetComponentImages(level: int, add_box: bool = False)` ### Endpoint N/A (Method within PyTessBaseAPI class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from tesserocr import PyTessBaseAPI, RIL from PIL import Image image = Image.open('newspaper.png') with PyTessBaseAPI() as api: api.SetImage(image) # Get text lines with their bounding boxes boxes = api.GetComponentImages(RIL.TEXTLINE, True) print(f'Found {len(boxes)} textline image components.') for i, (im, box, block_id, para_id) in enumerate(boxes): # im is a PIL image of the component # box is dict with x, y, w, h keys api.SetRectangle(box['x'], box['y'], box['w'], box['h']) text = api.GetUTF8Text() conf = api.MeanTextConf() print(f"Line {i}: x={box['x']}, y={box['y']}, " f"w={box['w']}, h={box['h']}, " f"conf={conf}%, text='{text.strip()}'") # Get word-level components words = api.GetComponentImages(RIL.WORD, True) print(f'Found {len(words)} word components.') # Get block-level components (useful for multi-column layouts) blocks = api.GetComponentImages(RIL.BLOCK, True) print(f'Found {len(blocks)} text blocks.') ``` ### Response #### Success Response (200) N/A (Method returns component data) #### Response Example N/A ``` -------------------------------- ### Retrieving LSTM Symbol Choices in Tesserocr (Tesseract 4+) Source: https://context7.com/sirfz/tesserocr/llms.txt This code retrieves detailed LSTM network choices for each word in an image, specifically for Tesseract 4 and later versions. It enables LSTM choice mode, processes an image, and then iterates through words and their corresponding timestep choices, printing the top 3 symbols and their probabilities for each timestep. Requires an image file. ```python from tesserocr import PyTessBaseAPI with PyTessBaseAPI() as api: # Enable LSTM choice mode (1=pure, 2=accumulated) api.SetVariable("lstm_choice_mode", "2") api.SetImageFile('document.png') api.Recognize() # Get LSTM choices for all words lstm_choices = api.GetBestLSTMSymbolChoices() words = api.AllWords() for word, choices in zip(words, lstm_choices): print(f"Word: '{word}'") for timestep_idx, timestep in enumerate(choices): print(f" Timestep {timestep_idx}:") for symbol, probability in timestep[:3]: # Top 3 print(f" '{symbol}': {probability:.3f}") ``` -------------------------------- ### tesserocr.file_to_text Source: https://context7.com/sirfz/tesserocr/llms.txt Extracts text directly from an image file path. ```APIDOC ## file_to_text ### Description Reads an image file from the disk and performs OCR to extract text. ### Method Function Call ### Parameters #### Arguments - **path** (string) - Required - File system path to the image. - **lang** (string) - Optional - Language code. - **psm** (int) - Optional - Page segmentation mode. - **path** (string) - Optional - Custom path to tessdata directory. ### Request Example ```python import tesserocr text = tesserocr.file_to_text('invoice.png', lang='eng') ``` ### Response #### Success Response (200) - **text** (string) - The recognized text. ``` -------------------------------- ### Restrict OCR to Image Regions Source: https://context7.com/sirfz/tesserocr/llms.txt Shows how to limit the OCR process to specific bounding boxes within an image, useful for extracting data from forms or headers. ```python from tesserocr import PyTessBaseAPI from PIL import Image with PyTessBaseAPI() as api: image = Image.open('form.png') api.SetImage(image) api.SetRectangle(0, 0, 800, 100) header_text = api.GetUTF8Text() api.SetRectangle(500, 700, 300, 100) signature_area = api.GetUTF8Text() api.SetImageFile('form.png') full_text = api.GetUTF8Text() ``` -------------------------------- ### tesserocr.image_to_text Source: https://context7.com/sirfz/tesserocr/llms.txt Recognizes text from a PIL Image object using Tesseract OCR. ```APIDOC ## image_to_text ### Description Extracts text from a PIL Image object. Supports language selection, page segmentation modes (PSM), and OCR engine modes (OEM). ### Method Function Call ### Parameters #### Arguments - **image** (PIL.Image) - Required - The image object to process. - **lang** (string) - Optional - Language code (e.g., 'eng', 'deu+eng'). - **psm** (int) - Optional - Page segmentation mode. - **oem** (int) - Optional - OCR engine mode. ### Request Example ```python from PIL import Image import tesserocr image = Image.open('document.jpg') text = tesserocr.image_to_text(image, lang='eng') ``` ### Response #### Success Response (200) - **text** (string) - The recognized text from the image. ```