### Install pytesseract via pip (Bash) Source: https://github.com/madmaze/pytesseract/blob/master/README.rst Installs the pytesseract Python library using pip, the standard package installer for Python. This command fetches the latest stable version from the Python Package Index (PyPI). ```bash pip install pytesseract ``` -------------------------------- ### Install pytesseract from Git (Bash) Source: https://github.com/madmaze/pytesseract/blob/master/README.rst Installs or updates the pytesseract Python library directly from its Git repository. This is useful for obtaining the latest development version or a specific commit. Requires Git to be installed. ```bash pip install -U git+https://github.com/madmaze/pytesseract.git ``` -------------------------------- ### Configuration - Custom Tesseract path and parameters Source: https://context7.com/madmaze/pytesseract/llms.txt Configures pytesseract to use custom Tesseract installation paths and leverages advanced Tesseract configuration options. Requires Tesseract-OCR installation and optional language data. Supports Windows, Linux, and Mac platforms with optimized PSM/OEM modes and character filtering. ```python import pytesseract # Set custom Tesseract executable path (Windows) pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' # Set custom Tesseract executable path (Linux/Mac) pytesseract.pytesseract.tesseract_cmd = '/usr/local/bin/tesseract' # Page Segmentation Mode (PSM) options psm_configs = { 'osd_only': '--psm 0', # Orientation and script detection only 'auto_osd': '--psm 1', # Auto page segmentation with OSD 'auto': '--psm 3', # Fully automatic without OSD (default) 'single_column': '--psm 4', # Single column of text 'single_block': '--psm 6', # Uniform block of text 'single_line': '--psm 7', # Single line of text 'single_word': '--psm 8', # Single word 'circle_word': '--psm 9', # Single word in circle 'single_char': '--psm 10', # Single character 'sparse_text': '--psm 11', # Sparse text (find as much as possible) 'sparse_osd': '--psm 12', # Sparse text with OSD 'raw_line': '--psm 13' # Raw line } # Use specific PSM mode text = pytesseract.image_to_string('single_line.png', config='--psm 7') # OCR Engine Mode (OEM) text = pytesseract.image_to_string('document.png', config='--oem 1') # Neural nets LSTM only text = pytesseract.image_to_string('document.png', config='--oem 2') # Legacy + LSTM text = pytesseract.image_to_string('document.png', config='--oem 3') # Default # Character whitelist (only recognize specific characters) digits_only = pytesseract.image_to_string( 'numbers.png', config='-c tessedit_char_whitelist=0123456789' ) # Character blacklist no_special = pytesseract.image_to_string( 'text.png', config='-c tessedit_char_blacklist=@#$%^&*' ) # Custom tessdata directory text = pytesseract.image_to_string( 'document.png', lang='chi_sim', config='--tessdata-dir "/opt/tessdata"' ) # Combined configuration options custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' text = pytesseract.image_to_string('license_plate.jpg', config=custom_config) # Process priority (Unix/Linux only) text = pytesseract.image_to_string('document.png', nice=10) # Lower priority ``` -------------------------------- ### Run Tesseract OCR and get raw output (Python) Source: https://github.com/madmaze/pytesseract/blob/master/README.rst Executes Tesseract OCR on an image and retrieves the raw output in a specified format. Allows configuration of output extension and additional Tesseract parameters. Useful for direct access to Tesseract's capabilities. ```python import pytesseract # Assuming 'image' is a loaded image object (e.g., from PIL) cfg_filename = 'words' pytesseract.run_and_get_output(image, extension='txt', config=cfg_filename) ``` -------------------------------- ### List installed Tesseract languages (Python) Source: https://context7.com/madmaze/pytesseract/llms.txt Retrieves the list of language packs available to the current Tesseract installation, enabling validation before processing. Optionally accepts a custom tessdata directory via a config string. ```python import pytesseract # Get all available languages languages = pytesseract.get_languages() print(languages) # Output: ['eng', 'fra', 'deu', 'spa', 'chi_sim', 'chi_tra', 'ara', 'rus', ...] # Check if specific language is available if 'fra' in pytesseract.get_languages(): text = pytesseract.image_to_string('french_doc.jpg', lang='fra') else: print("French language pack not installed") # With custom tessdata directory languages = pytesseract.get_languages(config='--tessdata-dir /custom/tessdata') # Validate multi-language support required_langs = ['eng', 'fra', 'deu'] available_langs = pytesseract.get_languages() missing_langs = [lang for lang in required_langs if lang not in available_langs] if missing_langs: print(f"Missing language packs: {', '.join(missing_langs)}") else: # Process with all required languages text = pytesseract.image_to_string( 'multilingual.png', lang='+'.join(required_langs) ) ``` -------------------------------- ### Check installed Tesseract version (Python) Source: https://context7.com/madmaze/pytesseract/llms.txt Obtains the Tesseract OCR engine version as a Version object for feature detection and compatibility checks. Demonstrates version‑based conditional logic and raises an error for unsupported versions. ```python import pytesseract from packaging.version import Version # Get version information version = pytesseract.get_tesseract_version() print(version) # Output: print(f"Version: {version.major}.{version.minor}.{version.micro}") # Version-based feature detection if pytesseract.get_tesseract_version() >= Version('4.1.0'): # ALTO XML supported xml = pytesseract.image_to_alto_xml('document.png') else: print("ALTO XML requires Tesseract 4.1.0+") if pytesseract.get_tesseract_version() >= Version('3.05'): # TSV output supported data = pytesseract.image_to_data('page.jpg') else: print("TSV output requires Tesseract 3.05+") # Compatibility check MIN_VERSION = Version('4.0.0') current_version = pytesseract.get_tesseract_version() if current_version < MIN_VERSION: raise RuntimeError( f"Tesseract {MIN_VERSION} or higher required. " f"Found version {current_version}" ) ``` -------------------------------- ### Function: get_tesseract_version Source: https://github.com/madmaze/pytesseract/blob/master/README.rst The get_tesseract_version function returns the version of Tesseract OCR installed on the system. This helps in verifying the Tesseract installation and compatibility with pytesseract features. It is particularly useful for debugging version-specific issues. ```APIDOC ## get_tesseract_version ### Description Returns the Tesseract version installed in the system. ### Method Function ### Endpoint get_tesseract_version() ### Parameters No parameters. ### Request Example get_tesseract_version() ### Response #### Success Response - **version** (str) - Tesseract version string #### Response Example '4.1.1' ``` -------------------------------- ### Function: get_languages Source: https://github.com/madmaze/pytesseract/blob/master/README.rst The get_languages function retrieves all currently supported languages by Tesseract OCR installed on the system. It provides a list of language codes that can be used for OCR processing. This is useful for checking available language support before performing recognition tasks. ```APIDOC ## get_languages ### Description Returns all currently supported languages by Tesseract OCR. ### Method Function ### Endpoint get_languages() ### Parameters No parameters. ### Request Example get_languages() ### Response #### Success Response - **languages** (list of str) - List of supported language codes #### Response Example ['eng', 'fra', 'chi_sim'] ``` -------------------------------- ### Get Character Bounding Boxes with pytesseract Source: https://context7.com/madmaze/pytesseract/llms.txt Returns character-level bounding box information for precise positioning of each recognized character. This function can output data as a space-separated string or as a dictionary for structured access. It is useful for applications requiring exact character coordinates and supports multi-language recognition. ```python import pytesseract # String output (default) - space-separated values boxes = pytesseract.image_to_boxes('document.png') print(boxes) # Output: "T 37 464 62 493 0\nh 64 464 84 493 0\ne 86 464 102 486 0..." # Dictionary output for structured access boxes_dict = pytesseract.image_to_boxes('page.jpg', output_type=pytesseract.Output.DICT) print(boxes_dict) # Output: { # 'char': ['T', 'h', 'e', ' ', 'q', 'u', 'i', 'c', 'k'], # 'left': [37, 64, 86, 102, 120, 145, 165, 185, 205], # 'bottom': [464, 464, 464, 464, 464, 464, 464, 464, 464], # 'right': [62, 84, 102, 115, 140, 160, 180, 200, 225], # 'top': [493, 493, 486, 493, 493, 493, 493, 493, 493], # 'page': [0, 0, 0, 0, 0, 0, 0, 0, 0] # } # Parse box data for coordinate extraction for i, char in enumerate(boxes_dict['char']): x1, y1 = boxes_dict['left'][i], boxes_dict['bottom'][i] x2, y2 = boxes_dict['right'][i], boxes_dict['top'][i] print(f"'{char}': ({x1}, {y1}) to ({x2}, {y2})") # With multiple languages boxes = pytesseract.image_to_boxes('multilingual.png', lang='eng+spa') ``` -------------------------------- ### Get Detailed Word-Level Data with pytesseract Source: https://context7.com/madmaze/pytesseract/llms.txt Returns comprehensive word-level data including bounding boxes, confidence scores, and hierarchical text structure information. This function outputs data in a tab-separated values (TSV) format or as a dictionary. It requires Tesseract 3.05 or higher and is ideal for applications needing detailed analysis or quality filtering. ```python import pytesseract import pandas as pd # String output (TSV format) data = pytesseract.image_to_data('document.png') print(data) # Output: Tab-separated values with columns: # level, page_num, block_num, par_num, line_num, word_num, left, top, width, height, conf, text # Dictionary output for programmatic access data_dict = pytesseract.image_to_data('invoice.jpg', output_type=pytesseract.Output.DICT) print(data_dict) # Output: { # 'level': [1, 2, 3, 4, 5, 5, 5], # 'page_num': [1, 1, 1, 1, 1, 1, 1], # 'block_num': [0, 1, 1, 1, 1, 1, 1], # 'par_num': [0, 0, 1, 1, 1, 1, 1], # 'line_num': [0, 0, 0, 1, 1, 1, 1], # 'word_num': [0, 0, 0, 0, 1, 2, 3], # 'left': [0, 11, 11, 11, 11, 56, 102], # 'top': [0, 12, 12, 12, 12, 12, 12], # 'width': [800, 765, 765, 765, 42, 43, 54], # 'height': [600, 576, 576, 25, 18, 18, 18], # 'conf': [-1, -1, -1, -1, 96, 95, 93], # 'text': ['', '', '', '', 'Invoice', 'Number:', '12345'] # } ``` -------------------------------- ### Extract Table Data Using pytesseract and pandas Source: https://context7.com/madmaze/pytesseract/llms.txt This function extracts data from an image containing a table. It uses pytesseract to get raw data, then pandas to group text by vertical and horizontal positions to infer rows and columns, finally pivoting the data into a table format. It requires an image path as input and returns a DataFrame representing the extracted table. ```python # Table extraction - detect grid structure def extract_table_data(image_path): df = pytesseract.image_to_data(image_path, output_type=pytesseract.Output.DATAFRAME) df = df[(df['conf'] > 60) & (df['text'].notna())] # Group by vertical position to identify rows df['row'] = pd.cut(df['top'], bins=20, labels=False) # Group by horizontal position to identify columns df['col'] = pd.cut(df['left'], bins=5, labels=False) # Pivot to table format table = df.pivot_table( values='text', index='row', columns='col', aggfunc=lambda x: ' '.join(x.astype(str)) ) return table table = extract_table_data('table_document.png') print(table) ``` -------------------------------- ### Basic CLI usage of pytesseract (Bash) Source: https://github.com/madmaze/pytesseract/blob/master/README.rst Demonstrates the basic command-line interface (CLI) usage for pytesseract. This command processes an image file using Tesseract OCR, optionally specifying the language. The output is typically printed to standard output. ```bash pytesseract [-l lang] image_file ``` -------------------------------- ### Run Tesseract with custom output formats (Python) Source: https://context7.com/madmaze/pytesseract/llms.txt Executes Tesseract with a specified output extension (e.g., txt, box, tsv, pdf, xml). Accepts optional language, config file, and return_bytes parameters. Returns the result as a string or bytes depending on the return_bytes flag. ```python import pytesseract # Get text output text = pytesseract.run_and_get_output('document.png', extension='txt') # Get box file output boxes = pytesseract.run_and_get_output('page.jpg', extension='box') # Get TSV data tsv_data = pytesseract.run_and_get_output('invoice.png', extension='tsv') # Get OSD information osd = pytesseract.run_and_get_output('rotated.jpg', extension='osd') # Get ALTO XML xml = pytesseract.run_and_get_output('manuscript.png', extension='xml') # With language specification text = pytesseract.run_and_get_output( 'spanish_doc.jpg', extension='txt', lang='spa' ) # With custom config file (Tesseract config file in tessdata/configs/) output = pytesseract.run_and_get_output( 'document.png', extension='txt', config='words' # Use tessdata/configs/words config ) # Return as bytes instead of string pdf_bytes = pytesseract.run_and_get_output( 'page.png', extension='pdf', return_bytes=True ) with open('output.pdf', 'wb') as f: f.write(pdf_bytes) ``` -------------------------------- ### Function: run_and_get_multiple_output Source: https://github.com/madmaze/pytesseract/blob/master/README.rst The run_and_get_multiple_output function is similar to run_and_get_output but handles multiple output formats in a single Tesseract call, improving efficiency. It takes a list of extensions and returns corresponding data. This reduces overhead when needing several outputs like text and boxes. ```APIDOC ## run_and_get_multiple_output ### Description Returns output for multiple extensions in one Tesseract call. ### Method Function ### Endpoint run_and_get_multiple_output(image, extension=['txt'], lang=None, config='', nice=0, timeout=0) ### Parameters - **extension** (list of str) - Required - List of extensions - Other params as above ### Request Example run_and_get_multiple_output(image, extension=['txt', 'box']) ### Response #### Success Response - **outputs** (list of str) - List of raw outputs corresponding to extensions #### Response Example ['Hello, World!', 'H 10 20...'] ``` -------------------------------- ### Function: run_and_get_output Source: https://github.com/madmaze/pytesseract/blob/master/README.rst The run_and_get_output function provides more control over Tesseract parameters and returns the raw OCR output. It allows specifying output extensions directly. This is for users needing finer-grained control over the Tesseract invocation. ```APIDOC ## run_and_get_output ### Description Returns the raw output from Tesseract OCR. Gives more control over parameters. ### Method Function ### Endpoint run_and_get_output(image, extension='txt', lang=None, config='', nice=0, timeout=0) ### Parameters - **image** - Required - Image to process - **extension** (str) - Optional - Output extension, e.g., 'txt' - Other params similar to image_to_string ### Request Example run_and_get_output(image, extension='txt', config=cfg_filename) ### Response #### Success Response - **output** (str) - Raw Tesseract output #### Response Example 'Hello, World!' ``` -------------------------------- ### Basic pytesseract Usage for Image to String Conversion Source: https://github.com/madmaze/pytesseract/blob/master/README.rst Demonstrates the fundamental use of pytesseract to extract text from an image file. It includes setting the Tesseract executable path and performing OCR on a PNG image. Supports direct file paths and Pillow Image objects. ```python from PIL import Image import pytesseract # If you don't have tesseract executable in your PATH, include the following: pytesseract.pytesseract.tesseract_cmd = r'' # Example tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract' # Simple image to string print(pytesseract.image_to_string(Image.open('test.png'))) # In order to bypass the image conversions of pytesseract, just use relative or absolute image path # NOTE: In this case you should provide tesseract supported images or tesseract will return error print(pytesseract.image_to_string('test.png')) # List of available languages print(pytesseract.get_languages(config='')) # French text image to string print(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='fra')) # Batch processing with a single file containing the list of multiple image file paths print(pytesseract.image_to_string('images.txt')) # Timeout/terminate the tesseract job after a period of time try: print(pytesseract.image_to_string('test.jpg', timeout=2)) # Timeout after 2 seconds print(pytesseract.image_to_string('test.jpg', timeout=0.5)) # Timeout after half a second except RuntimeError as timeout_error: # Tesseract processing is terminated pass ``` -------------------------------- ### Custom Configuration for pytesseract OCR Source: https://github.com/madmaze/pytesseract/blob/master/README.rst Explains how to apply custom configurations to the Tesseract OCR engine using the `config` parameter in pytesseract. This includes specifying OCR Engine Modes (OEM) and Page Segmentation Modes (PSM) for tailored recognition. ```python import pytesseract from PIL import Image # Example of adding any additional options custom_oem_psm_config = r'--oem 3 --psm 6' image = Image.open('test.png') pytesseract.image_to_string(image, config=custom_oem_psm_config) # Example of using pre-defined tesseract config file with options # config_file_path = r'path/to/your/tesseract_config.cfg' # pytesseract.image_to_string(image, config=f'--config {config_file_path}') ``` -------------------------------- ### Generate ALTO XML output with pytesseract image_to_alto_xml Source: https://context7.com/madmaze/pytesseract/llms.txt Creates ALTO XML files from images, optionally specifying a language, and parses the XML to extract text content with positional metadata. Requires pytesseract and the built‑in xml.etree.ElementTree module. Outputs are XML strings saved to files or processed for layout analysis. ```python import pytesseract import xml.etree.ElementTree as ET # Generate ALTO XML from an image xml_bytes = pytesseract.image_to_alto_xml('manuscript.png') xml_str = xml_bytes.decode('utf-8') with open('output.xml', 'w', encoding='utf-8') as f: f.write(xml_str) # Generate ALTO XML with a specific language xml_bytes = pytesseract.image_to_alto_xml('french_doc.jpg', lang='fra') # Parse ALTO XML to extract text and coordinates xml_str = pytesseract.image_to_alto_xml('document.png').decode('utf-8') root = ET.fromstring(xml_str) ns = {'alto': 'http://www.loc.gov/standards/alto/ns-v4#'} for string_elem in root.findall('.//alto:String', ns): content = string_elem.get('CONTENT') hpos = string_elem.get('HPOS') vpos = string_elem.get('VPOS') width = string_elem.get('WIDTH') height = string_elem.get('HEIGHT') print(f"'{content}' at ({hpos}, {vpos}) size {width}x{height}") ``` -------------------------------- ### Generate searchable PDF or hOCR HTML with pytesseract image_to_pdf_or_hocr Source: https://context7.com/madmaze/pytesseract/llms.txt Shows how to create searchable PDF files and hOCR HTML from single or multiple images, including multi‑language PDFs and custom Tesseract configurations. Requires pytesseract and Pillow. Input images are converted to PDF or hOCR bytes, which are then written to disk or processed further. ```python import pytesseract from PIL import Image # Generate searchable PDF from a single image pdf_bytes = pytesseract.image_to_pdf_or_hocr('document.png', extension='pdf') with open('searchable_output.pdf', 'wb') as f: f.write(pdf_bytes) # Generate hOCR HTML from a single image hocr_bytes = pytesseract.image_to_pdf_or_hocr('page.jpg', extension='hocr') hocr_html = hocr_bytes.decode('utf-8') with open('output.html', 'w', encoding='utf-8') as f: f.write(hocr_html) # Multi‑language searchable PDF pdf_bytes = pytesseract.image_to_pdf_or_hocr( 'multilingual_doc.png', lang='eng+fra+deu', extension='pdf' ) with open('multilingual_searchable.pdf', 'wb') as f: f.write(pdf_bytes) # hOCR with custom configuration hocr_bytes = pytesseract.image_to_pdf_or_hocr( 'document.jpg', config='--psm 6', extension='hocr' ) # Batch processing: combine several images into PDF pages images = ['page1.jpg', 'page2.jpg', 'page3.jpg'] pdf_pages = [] for img_path in images: pdf_bytes = pytesseract.image_to_pdf_or_hocr(img_path, extension='pdf') pdf_pages.append(pdf_bytes) # Combine PDFs using PyPDF2 or similar library (not shown) ``` -------------------------------- ### pytesseract with OpenCV Image Objects Source: https://github.com/madmaze/pytesseract/blob/master/README.rst Illustrates how to use pytesseract with images loaded by OpenCV. It covers the necessary color conversion from BGR (OpenCV default) to RGB (pytesseract expected) format, enabling seamless integration between the two libraries. ```python import cv2 import pytesseract from PIL import Image img_cv = cv2.imread(r'//digits.png') # By default OpenCV stores images in BGR format and since pytesseract assumes RGB format, # we need to convert from BGR to RGB format/mode: img_rgb = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB) print(pytesseract.image_to_string(img_rgb)) # OR img_rgb = Image.frombytes('RGB', img_cv.shape[:2], img_cv, 'raw', 'BGR', 0, 0) print(pytesseract.image_to_string(img_rgb)) ``` -------------------------------- ### Configure Tessdata Directory for pytesseract (Python) Source: https://github.com/madmaze/pytesseract/blob/master/README.rst Sets a custom directory for Tesseract's language data files (`tessdata`). This is crucial for resolving 'Error opening data file...' errors, ensuring Tesseract can find the necessary language models. Requires replacing a placeholder with the actual path. ```python # Example config: r'--tessdata-dir "C:\Program Files (x86)\Tesseract-OCR\tessdata"' # It's important to add double quotes around the dir path. tessdata_dir_config = r'--tessdata-dir ""' # Assuming 'image' is a loaded image object (e.g., from PIL) pytesseract.image_to_string(image, lang='chi_sim', config=tessdata_dir_config) ``` -------------------------------- ### Advanced pytesseract Outputs: Boxes, Data, OSD, PDF, HOCR, ALTO Source: https://github.com/madmaze/pytesseract/blob/master/README.rst Shows how to obtain more detailed information from OCR, including bounding box coordinates, confidence levels, orientation and script detection, and different output formats like PDF, HOCR, and ALTO XML. This enables richer data extraction and processing. ```python from PIL import Image import pytesseract # Get bounding box estimates print(pytesseract.image_to_boxes(Image.open('test.png'))) # Get verbose data including boxes, confidences, line and page numbers print(pytesseract.image_to_data(Image.open('test.png'))) # Get information about orientation and script detection print(pytesseract.image_to_osd(Image.open('test.png'))) # Get a searchable PDF pdf = pytesseract.image_to_pdf_or_hocr('test.png', extension='pdf') with open('test.pdf', 'w+b') as f: f.write(pdf) # pdf type is bytes by default # Get HOCR output hocr = pytesseract.image_to_pdf_or_hocr('test.png', extension='hocr') # Get ALTO XML output xml = pytesseract.image_to_alto_xml('test.png') # getting multiple types of output with one call to save compute time # currently supports mix and match of the following: txt, pdf, hocr, box, tsv text, boxes = pytesseract.run_and_get_multiple_output('test.png', extensions=['txt', 'box']) ``` -------------------------------- ### Extract Multiple Tesseract formats in a single call (Python) Source: https://context7.com/madmaze/pytesseract/llms.txt Runs Tesseract once and returns several requested output formats simultaneously, reducing processing time when multiple representations are needed. Supports optional language selection, timeout, and control over byte return. Returns a tuple matching the order of the requested extensions. ```python import pytesseract # Get both text and boxes in one call text, boxes = pytesseract.run_and_get_multiple_output( 'document.png', extensions=['txt', 'box'] ) print("Text:", text) print("Boxes:", boxes) # Get multiple formats for comprehensive analysis text, data, boxes, pdf, hocr = pytesseract.run_and_get_multiple_output( 'invoice.jpg', extensions=['txt', 'tsv', 'box', 'pdf', 'hocr'] ) # Save all outputs with open('text.txt', 'w') as f: f.write(text) with open('data.tsv', 'w') as f: f.write(data) with open('boxes.box', 'w') as f: f.write(boxes) with open('output.pdf', 'wb') as f: f.write(pdf) with open('output.html', 'w') as f: f.write(hocr.decode('utf-8')) # With language and timeout results = pytesseract.run_and_get_multiple_output( 'large_document.jpg', extensions=['txt', 'tsv'], lang='eng+fra', timeout=15 ) text, tsv_data = results # All available extensions all_formats = pytesseract.run_and_get_multiple_output( 'page.png', extensions=['txt', 'box', 'tsv', 'pdf', 'hocr', 'xml'], return_bytes=False ) ``` -------------------------------- ### Integration - OpenCV and computer vision pipelines Source: https://context7.com/madmaze/pytesseract/llms.txt Integrates pytesseract with OpenCV for comprehensive image preprocessing and text extraction workflows. Requires opencv-python and numpy dependencies. Includes noise removal, thresholding, rotation correction, and bounding box detection capabilities for enhanced OCR accuracy. ```python import cv2 import pytesseract import numpy as np # Basic OpenCV integration img = cv2.imread('document.jpg') img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) text = pytesseract.image_to_string(img_rgb) # Preprocessing pipeline for better OCR accuracy def preprocess_image(image_path): # Read image img = cv2.imread(image_path) # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply thresholding thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] # Noise removal denoised = cv2.medianBlur(thresh, 3) # Dilation and erosion kernel = np.ones((1, 1), np.uint8) processed = cv2.dilate(denoised, kernel, iterations=1) processed = cv2.erode(processed, kernel, iterations=1) return processed # Use preprocessed image processed = preprocess_image('noisy_document.jpg') text = pytesseract.image_to_string(processed) # Detect and extract text regions with bounding boxes img = cv2.imread('page.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Get bounding box data data = pytesseract.image_to_data(gray, output_type=pytesseract.Output.DICT) # Draw boxes on image for i in range(len(data['text'])): if int(data['conf'][i]) > 60: # Confidence threshold x, y, w, h = data['left'][i], data['top'][i], data['width'][i], data['height'][i] cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(img, data['text'][i], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.imwrite('annotated_output.jpg', img) # Rotation correction img = cv2.imread('rotated.jpg') osd = pytesseract.image_to_osd(img, output_type=pytesseract.Output.DICT) angle = osd['rotate'] if angle != 0: (h, w) = img.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, angle, 1.0) img = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) text = pytesseract.image_to_string(img) ``` -------------------------------- ### Detect orientation and script with pytesseract image_to_osd Source: https://context7.com/madmaze/pytesseract/llms.txt Demonstrates retrieving orientation and script information as both string and dictionary outputs, auto‑rotating images based on detected orientation, and selecting OCR language according to the identified script. Requires pytesseract and Pillow. Inputs are image files; outputs include orientation data and corrected OCR text. ```python import pytesseract from PIL import Image # String output osd = pytesseract.image_to_osd('rotated_document.png') print(osd) # Dictionary output osd_dict = pytesseract.image_to_osd('tilted_page.jpg', output_type=pytesseract.Output.DICT) print(osd_dict) # Auto‑rotate image based on orientation img = Image.open('rotated.png') osd = pytesseract.image_to_osd(img, output_type=pytesseract.Output.DICT) if osd['orientation'] != 0: img_rotated = img.rotate(osd['rotate'], expand=True) text = pytesseract.image_to_string(img_rotated) else: text = pytesseract.image_to_string(img) # Select OCR language according to detected script if osd_dict['script'] == 'Arabic': text = pytesseract.image_to_string(img, lang='ara') elif osd_dict['script'] == 'Han': text = pytesseract.image_to_string(img, lang='chi_sim') else: text = pytesseract.image_to_string(img, lang='eng') ``` -------------------------------- ### Function: image_to_alto_xml Source: https://github.com/madmaze/pytesseract/blob/master/README.rst The image_to_alto_xml function outputs OCR results in ALTO XML format, which is a standard for archiving and exchanging digital content. This format includes detailed structural information about the text. It is suitable for long-term preservation and interoperability. ```APIDOC ## image_to_alto_xml ### Description Returns result in the form of Tesseract's ALTO XML format. ### Method Function ### Endpoint image_to_alto_xml(image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0) ### Parameters Similar to image_to_string. ### Request Example image_to_alto_xml(image) ### Response #### Success Response - **xml** (str) - ALTO XML formatted string #### Response Example '...' ``` -------------------------------- ### Extract structured data with pandas DataFrame using pytesseract Source: https://context7.com/madmaze/pytesseract/llms.txt Loads OCR results into a pandas DataFrame, filters high‑confidence text, extracts monetary amounts with regex, groups text by line with average confidence, and demonstrates custom pandas configuration. Requires pandas and pytesseract. Input images are processed to produce tabular OCR data; outputs are printed to the console. ```python import pytesseract import pandas as pd # Load OCR data into a pandas DataFrame df = pytesseract.image_to_data('receipt.png', output_type=pytesseract.Output.DATAFRAME) # Filter rows with high confidence high_confidence = df[df['conf'] > 80] print(high_confidence[['text', 'conf']]) # Extract monetary amounts using a regex pattern amounts = df[df['text'].str.match(r'^\$?\d+\.\d{2}$', na=False)] print("Detected amounts:", amounts['text'].tolist()) # Group text by line number and compute average confidence per line for line_num, line_data in df[df['text'].notna()].groupby('line_num'): line_text = ' '.join(line_data['text'].astype(str)) avg_conf = line_data['conf'].mean() print(f"Line {line_num} (conf: {avg_conf:.1f}): {line_text}") # Custom pandas configuration for OCR output df = pytesseract.image_to_data( 'document.png', output_type=pytesseract.Output.DATAFRAME, pandas_config={'sep': '\t', 'quoting': 0, 'dtype': {'text': str}} ) ``` -------------------------------- ### Integration - Pandas data analysis workflows Source: https://context7.com/madmaze/pytesseract/llms.txt Processes OCR results with pandas for data extraction, filtering, validation, and structured analysis from documents. Note: This snippet is incomplete and shows only the initial import statement. Requires pandas and optional dependencies like re for advanced text processing and data manipulation. ```python import pytesseract import pandas as pd import re ``` -------------------------------- ### Function: image_to_boxes Source: https://github.com/madmaze/pytesseract/blob/master/README.rst The image_to_boxes function performs OCR and returns recognized characters along with their bounding box coordinates. This is useful for applications requiring precise character positioning. It provides detailed character-level information for analysis or visualization. ```APIDOC ## image_to_boxes ### Description Returns result containing recognized characters and their box boundaries. ### Method Function ### Endpoint image_to_boxes(image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0) ### Parameters Similar to image_to_string: image, lang, config, nice, output_type, timeout. ### Request Example image_to_boxes(image) ### Response #### Success Response - **boxes** (str) - String with characters and bounding box info (format: char left top right bottom) #### Response Example 'H 10 20 15 30\ne 15 20 20 30' ``` -------------------------------- ### Function: image_to_data Source: https://github.com/madmaze/pytesseract/blob/master/README.rst The image_to_data function extracts detailed OCR data including bounding boxes, confidences, and other metadata. It requires Tesseract 3.05+ and is ideal for advanced analysis. Users can output in string or DataFrame format for integration with pandas. ```APIDOC ## image_to_data ### Description Returns result containing box boundaries, confidences, and other information. Requires Tesseract 3.05+. ### Method Function ### Endpoint image_to_data(image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0, pandas_config=None) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **image** (PIL Image, NumPy array, or str) - Required - The image to be processed by Tesseract. If object, converted to RGB. - **lang** (str) - Optional - Tesseract language code string. Defaults to 'eng'. Example: 'eng+fra'. - **config** (str) - Optional - Additional custom configuration flags. - **nice** (int) - Optional - Modifies processor priority. - **output_type** (enum) - Optional - Defaults to string; can be DataFrame. - **timeout** (int or float) - Optional - Timeout in seconds. - **pandas_config** (dict) - Optional - For DataFrame output, custom args for pandas.read_csv. ### Request Example image_to_data(image, lang='eng') ### Response #### Success Response - **data** (str or DataFrame) - TSV or DataFrame with columns like level, page_num, block_num, etc. (see Tesseract TSV docs) #### Response Example 'level\tpage_num\t...\n1\t1\t...' ``` -------------------------------- ### Extract Text from Images using pytesseract Source: https://context7.com/madmaze/pytesseract/llms.txt Extracts and returns text content from an image as a string. Supports file paths, PIL Image objects, or NumPy arrays as input. It can process multiple languages and accept custom configurations for Tesseract's OCR engine, such as Page Segmentation Modes (PSM). Timeout protection is also available. ```python import pytesseract from PIL import Image import numpy as np # Basic usage with file path text = pytesseract.image_to_string('document.jpg') print(text) # With PIL Image object img = Image.open('invoice.png') text = pytesseract.image_to_string(img, lang='eng') # With NumPy array img_array = np.array(Image.open('receipt.jpg')) text = pytesseract.image_to_string(img_array) # Multiple languages text = pytesseract.image_to_string('multilingual.png', lang='eng+fra+deu') # With custom configuration (PSM mode) custom_config = r'--psm 6' # Uniform block of text text = pytesseract.image_to_string('single_block.png', config=custom_config) # With timeout protection try: text = pytesseract.image_to_string('large_document.jpg', timeout=10) except RuntimeError as e: print(f"Processing timeout: {e}") # Different output types text_str = pytesseract.image_to_string(img, output_type=pytesseract.Output.STRING) text_bytes = pytesseract.image_to_string(img, output_type=pytesseract.Output.BYTES) text_dict = pytesseract.image_to_string(img, output_type=pytesseract.Output.DICT) # Output: {'text': 'Extracted text content...'} ``` -------------------------------- ### Function: image_to_osd Source: https://github.com/madmaze/pytesseract/blob/master/README.rst The image_to_osd function analyzes the image for orientation and script detection, returning information about the layout and text direction. This helps in preprocessing images before full OCR. It is particularly useful for documents with varying orientations. ```APIDOC ## image_to_osd ### Description Returns result containing information about orientation and script detection. ### Method Function ### Endpoint image_to_osd(image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0) ### Parameters Similar to image_to_string. ### Request Example image_to_osd(image) ### Response #### Success Response - **osd** (str) - String with orientation, script, and confidence info #### Response Example 'Page number: 0\nOrientation in degrees: 0\n...' ``` -------------------------------- ### Function: image_to_string Source: https://github.com/madmaze/pytesseract/blob/master/README.rst The image_to_string function processes an image and returns the recognized text as an unmodified string from Tesseract OCR. It is the primary function for basic OCR tasks. Users can specify language, configuration options, and other parameters to customize the recognition process. ```APIDOC ## image_to_string ### Description Returns unmodified output as string from Tesseract OCR processing. ### Method Function ### Endpoint image_to_string(image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **image** (PIL Image, NumPy array, or str) - Required - The image to be processed by Tesseract. Can be a PIL Image, NumPy array, or file path. - **lang** (str) - Optional - Tesseract language code string. Defaults to 'eng'. Example: 'eng+fra' for multiple languages. - **config** (str) - Optional - Additional custom configuration flags, e.g., '--psm 6'. - **nice** (int) - Optional - Modifies processor priority (not supported on Windows). - **output_type** (enum) - Optional - Specifies output type, defaults to string. See pytesseract.Output class for options. - **timeout** (int or float) - Optional - Timeout in seconds, raises RuntimeError if exceeded. ### Request Example image_to_string(image, lang='chi_sim', config=tessdata_dir_config) ### Response #### Success Response - **text** (str) - Recognized text from the image #### Response Example 'Hello, World!' ``` -------------------------------- ### Reconstruct Text Structure Line by Line Source: https://context7.com/madmaze/pytesseract/llms.txt This code groups the cleaned OCR data by line number to reconstruct the text structure of the document. It calculates the average confidence for each line and stores the results in a pandas DataFrame, which is then printed. ```python # Group by lines to reconstruct text structure lines = [] for line_num in df_clean['line_num'].unique(): line_data = df_clean[df_clean['line_num'] == line_num] line_text = ' '.join(line_data['text'].astype(str)) avg_conf = line_data['conf'].mean() lines.append({'line_num': line_num, 'text': line_text, 'confidence': avg_conf}) lines_df = pd.DataFrame(lines) print(lines_df) ``` -------------------------------- ### Perform OCR Quality Analysis Source: https://context7.com/madmaze/pytesseract/llms.txt This snippet calculates an OCR quality score based on the confidence levels of the extracted words. It compares the count of words with high confidence (above 90) to the total number of extracted words to determine the quality percentage. ```python # Quality analysis total_words = len(df_clean) high_conf_words = len(df_clean[df_clean['conf'] > 90]) quality_score = (high_conf_words / total_words) * 100 print(f"OCR Quality Score: {quality_score:.1f}%") ``` -------------------------------- ### Extract Monetary Amounts from Cleaned Data Source: https://context7.com/madmaze/pytesseract/llms.txt This code defines a function to identify monetary amounts (e.g., $123.45) using regular expressions and applies it to the cleaned DataFrame. It then prints the detected amounts along with their confidence scores and positions. ```python # Extract monetary amounts def is_amount(text): return bool(re.match(r'^\$?\d+\.\d{2}$', str(text))) amounts = df_clean[df_clean['text'].apply(is_amount)] print("Detected amounts:") print(amounts[['text', 'conf', 'left', 'top']]) ``` -------------------------------- ### Extract and Clean Invoice Data with pytesseract Source: https://context7.com/madmaze/pytesseract/llms.txt This snippet shows how to use pytesseract to extract data from an invoice image into a pandas DataFrame. It then cleans the data by removing entries with no text, empty strings, or low confidence scores (below 60). ```python import pytesseract import pandas as pd import re # Extract structured data from invoice df = pytesseract.image_to_data('invoice.png', output_type=pytesseract.Output.DATAFRAME) # Clean data - remove empty text and low confidence df_clean = df[(df['text'].notna()) & (df['text'].str.strip() != '') & (df['conf'] > 60)] ``` -------------------------------- ### Extract Dates from Cleaned Data Source: https://context7.com/madmaze/pytesseract/llms.txt This snippet extracts date-like strings (e.g., 12/25/2023 or 01-15-99) from the cleaned OCR data using a regular expression pattern. It filters the DataFrame to include only rows where the text matches the date pattern. ```python # Extract dates date_pattern = r'\d{1,2}[/-]\d{1,2}[/-]\d{2,4}' dates = df_clean[df_clean['text'].str.match(date_pattern, na=False)] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.