This HTML page is not optimized for LLM or AI agent consumption. Fetch the Markdown version instead: /blog/tesseract-python-guide.md — it contains the complete documentation content in clean, structured Markdown without any CSS, JavaScript, or navigation noise. Ultimate guide to Python Tesseract

Table of contents

    This article covers Tesseract OCR with Python: setup, image preprocessing, multilingual text recognition, and performance tuning. It includes working code for each step.
    Ultimate guide to Python Tesseract
    TL;DR

    Tesseract with the pytesseract Python wrapper extracts text from images and scanned documents. This guide covers installation, image preprocessing (grayscale, thresholding, deskewing), multilingual OCR, advanced configuration, and performance tips. For searchable PDFs without manual preprocessing, see the Nutrient OCR API.

    Need production-ready OCR?

    Nutrient OCR API creates searchable PDFs from scanned images — no preprocessing required. 50 free credits/month.

    Tesseract OCR(opens in a new tab) is the most widely used open source optical character recognition (OCR) engine. Its Python wrapper, pytesseract, lets developers extract text from images with a few lines of code.

    What is Tesseract?

    Tesseract is an open source OCR engine that extracts text from images, scanned documents, and PDFs. It’s originally developed by Hewlett-Packard (HP) and maintained by Google since 2006, and it recognizes more than 100 languages. It extracts text from scanned documents, images, and PDFs. With pytesseract, you can integrate Tesseract into Python projects to automate data extraction.

    What is pytesseract?

    pytesseract is a Python wrapper for the Tesseract OCR engine. It provides a Pythonic interface to Tesseract without requiring direct interaction with the C++ engine. For a hands-on tutorial with code examples, see our pytesseract tutorial.

    FeatureTesseractpytesseract
    LanguageC++Python wrapper
    UsageCommand-line tool or C++ APIPython import pytesseract
    InstallationSystem package (brew, apt, installer)pip install pytesseract
    RequiresStandalone installationTesseract must be installed separately
    Output formatsText, hOCR, TSV, PDFString, dict, DataFrame, bytes
    Best forDirect CLI usage, C++ integrationPython scripts, automation, data pipelines

    Prerequisites

    Make sure you have the following installed:

    Terminal window
    python get-pip.py
    • macOS/Linux — Open a terminal and run:
    Terminal window
    sudo apt install python3-pip # For Debian-based Linux
    sudo dnf install python3-pip # For Fedora-based Linux
    brew install python # For macOS (via Homebrew)
    • OpenCV library — This is required for image preprocessing tasks such as grayscale conversion, thresholding, and noise removal. Install it using:
    Terminal window
    pip install opencv-python
    • NumPy library — Used for handling numerical operations on image data. Install it using:
    Terminal window
    pip install numpy
    • Pillow — This is a fork of the Python Imaging Library (PIL), which you’ll need to open image files:
    Terminal window
    pip install Pillow

    Setting up Tesseract with Python

    The setup process covers installing the Tesseract engine and the pytesseract Python wrapper.

    Installation

    Install both the Tesseract OCR engine and the pytesseract(opens in a new tab) library.

    Installing Tesseract

    Terminal window
    brew install tesseract
    • Linux — Most Linux distributions include Tesseract in their package repositories, so you can install it using APT with the following command:
    Terminal window
    sudo apt install tesseract-ocr
    • For Fedora-based distributions, use:
    Terminal window
    sudo dnf install tesseract

    After installation, make sure Tesseract is available in your system’s PATH, or provide the direct path in your code.

    Installing pytesseract

    Once Tesseract is installed on your system, install the pytesseract(opens in a new tab) library using Python’s package manager, pip:

    Terminal window
    pip install pytesseract

    Verifying installation

    To ensure Tesseract has been installed correctly, open a terminal or command prompt and run the following command:

    Terminal window
    tesseract --version

    If the installation was successful, the terminal will display the version number of Tesseract, along with other relevant details.

    How to use Tesseract with Python

    To use Tesseract with Python, install pytesseract, open an image with Pillow, and call pytesseract.image_to_string() to return the recognized text as a string. The example below demonstrates this with a sample image containing printed text.

    Sample image for OCR using Tesseract

    Use this code to get started with OCR using Tesseract and Python:

    from PIL import Image
    import pytesseract
    # Open an image file.
    image = Image.open('example.png')
    # Use pytesseract to do OCR on the image.
    text = pytesseract.image_to_string(image)
    # Print the extracted text.
    print(text)

    In this example:

    • Open an image file using Pillow.
    • Pass the image to pytesseract.image_to_string() to extract the text.

    Terminal output showing the text Tesseract extracted from the sample image

    Understanding OpenCV (cv2)

    Image preprocessing in this guide uses OpenCV(opens in a new tab), an open source computer vision library for Python. The cv2 module provides functions to manipulate and enhance images before passing them to Tesseract.

    Key features of OpenCV (cv2)

    • Reading and writing images — OpenCV enables loading, displaying, and saving images using functions like cv2.imread() and cv2.imwrite().
    • Image preprocessing — It provides various image enhancement techniques, such as grayscale conversion, thresholding, noise removal, and edge detection.
    • Geometric transformations — Functions like rotation, resizing, and deskewing help in improving OCR accuracy.
    • Object and text detection — OpenCV supports contour detection, which is useful for extracting regions of interest in images containing text.

    Image preprocessing for better OCR accuracy

    Tesseract accuracy depends on input image quality. Preprocessing the image before OCR reduces character misreads. For a complete walkthrough of preprocessing pipelines, see our guide on building a document scanner with OCR in Python.

    Grayscale conversion

    Converting an image to grayscale reduces the complexity of the image by eliminating unnecessary color information, making it easier for Tesseract to focus on text detection:

    import cv2
    image = cv2.imread('image.png')
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imwrite('gray_image.png', gray)
    Original imageGrayscale image
    A tiger walks on a forest path, surrounded by trees and warm light. Its black and orange stripes stand out. A tiger walks on a forest path in black and white. The stripes and details are clear, but the colors are gone.

    Thresholding

    Thresholding(opens in a new tab) is a technique that helps separate text from a background by converting an image into a binary format where pixels are either black or white:

    thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    cv2.imwrite('thresholded_image.png', thresh)

    The code above applies Otsu’s thresholding(opens in a new tab) to a grayscale image, converting it into a binary image where pixels are either black or white. The thresholded result is then saved as thresholded_image.png.

    Original imageThresholded image
    A simple image with clear, black text on a white background. The text should read 'The quick brown fox jumps over the lazy dog.' A black-and-white thresholded image with clear, black text on a white background. The text reads: 'The quick brown fox jumps over the lazy dog.'

    Noise removal

    Noise, such as small speckles or distortions, can interfere with OCR. The following code, broken down into steps, applies image processing techniques to remove noise and improve text clarity.

    Step 1

    Load and convert to grayscale:

    import cv2
    import numpy as np
    image = cv2.imread('fax.jpg')
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imwrite('gray_image.png', gray)
    • Loads the image and converts it to grayscale for simpler processing.

    Step 2

    Apply a bilateral filter:

    denoised = cv2.bilateralFilter(gray, 9, 75, 75)
    • Reduces noise while preserving edges using a bilateral filter.

    Step 3

    Sharpen the image:

    kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
    sharpened = cv2.filter2D(denoised, -1, kernel)
    • Sharpens the image by enhancing edges with a kernel filter.

    Step 4

    Save the processed image:

    cv2.imwrite('denoised_image.png', sharpened)
    • Saves the final sharpened and denoised image.

    Why does this matter for OCR?

    • Reduces noise, making text more readable.
    • Preserves important details while removing unwanted distortions.
    • Improves OCR accuracy, as clearer text leads to better recognition.
    Original imageDenoised image
    'A scanned fax from 21 May 1998, with typewritten text, faded black ink, and a yellowed background.' A cleaned-up version of a scanned fax from 21 May 1998, with sharper typewritten text, improved contrast, and reduced noise on a light background.

    Deskewing for better OCR accuracy

    After applying thresholding, some scanned documents may have tilted text, affecting OCR accuracy. Deskewing corrects this misalignment, ensuring Tesseract processes the text properly:

    coords = np.column_stack(np.where(thresh > 0)) # Find non-zero pixel coordinates.
    angle = cv2.minAreaRect(coords)[-1] # Calculate the skew angle
    # Adjust the angle for the correct rotation.
    if angle < -45:
    angle = -(90 + angle)
    else:
    angle = -angle
    # Rotate the image to correct the skew.
    (h, w) = thresh.shape[:2]
    center = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    deskewed = cv2.warpAffine(thresh, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
    cv2.imwrite('deskewed_image.png', deskewed)

    By detecting the text angle and rotating the image, this method straightens skewed text, improving OCR results.

    Original imageDeskewed image
    'A simple image with clear, black text on a white background. The text should read 'The quick brown fox jumps over the lazy dog.' A deskewed image with clear, black text on a white background. The text reads, 'The quick brown fox jumps over the lazy dog.' The alignment is corrected for better readability.

    Multilingual text recognition

    Tesseract supports more than 100 languages, which lets you extract text in different scripts and dialects. To enable multilingual OCR, the required language data files must be correctly installed and configured.

    Language data files

    Tesseract provides language data files that can be downloaded from Tesseract’s language repository(opens in a new tab) and placed in the tessdata directory of the Tesseract installation.

    Configuring language in pytesseract

    To instruct Tesseract to recognize multiple languages in an image, specify the desired languages in the lang parameter of pytesseract.image_to_string():

    import pytesseract
    text = pytesseract.image_to_string(image, lang='eng+fra')
    print(text)

    Advanced configuration options

    These options let you control how Tesseract analyzes page layout, which recognition engine it uses, and which characters it considers during extraction.

    PSM

    Tesseract offers various page segmentation modes (PSM)(opens in a new tab) that determine how text is segmented within an image. For example:

    text = pytesseract.image_to_string(image, config='--psm 6')

    Common PSM modes include:

    • 3 — Fully automatic page segmentation.
    • 6 — Assumes a single uniform block of text.
    • 11 — Sparse text with no predefined order.

    OEM

    Tesseract supports multiple OCR engine modes (OEM), which define the underlying text recognition approach:

    text = pytesseract.image_to_string(image, config='--oem 1')

    Common OEM modes include:

    • 0 — Uses the legacy OCR engine only.
    • 1 — Uses the long short-term memory (LSTM)-based OCR engine.
    • 3 — Uses a combination of the legacy and LSTM engines.

    Allowed and disallowed characters

    To improve accuracy, Tesseract allows restricting recognition to specific characters:

    custom_config = r'--psm 6 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    text = pytesseract.image_to_string(image, config=custom_config)

    Extracting text from PDF

    Tesseract can extract text from PDFs by converting them to images. Ensure you have Poppler(opens in a new tab) installed first. For alternative Python approaches to PDF text extraction, see our dedicated guides.

    Installing Poppler

    First, install Poppler:

    Then, use this code:

    import pytesseract
    from pdf2image import convert_from_path
    # Convert PDF to images.
    images = convert_from_path('example.pdf')
    # Extract text from the first page.
    text = pytesseract.image_to_string(images[0])
    print(text)

    You’ll need to install pdf2image using:

    Terminal window
    pip install pdf2image

    For extracting text from PDFs without OCR (when text is already selectable), see how to extract text from a PDF using PyMuPDF.

    Tesseract vs. commercial OCR solutions

    Choosing between Tesseract and a commercial OCR solution depends on your use case, volume, and accuracy requirements.

    FeatureTesseract (open source)Nutrient OCR API (commercial)
    CostFree (Apache 2.0)50 free credits/month, then paid
    InstallationLocal engine requiredCloud API — no installation
    PreprocessingManual (grayscale, threshold, deskew)Automatic — built-in preprocessing
    Output formatPlain text, hOCR, TSVSearchable PDF with embedded text layer
    Languages100+ (install language packs)80+ languages built in
    Batch processingBuild your own pipelineSingle API call for multiple pages
    PDF supportRequires pdf2image conversionNative PDF input and output
    Layout preservationLimitedRetains tables, columns, and formatting
    AccuracyGood with proper preprocessingConsistent without manual tuning
    Best forPrototyping, local processing, customizationProduction workflows, searchable PDFs

    For production OCR that outputs searchable PDFs, see the Nutrient OCR API. You can also OCR PDFs directly using the API in JavaScript, Python, PHP, or Java.

    Performance optimization tips

    When processing large batches of images or working with high-resolution scans, performance becomes critical. These tips help you get the most out of Tesseract.

    1. Use tessdata_fast models — The tessdata_fast(opens in a new tab) models are smaller and faster than default models with minimal accuracy loss. Swap your tessdata directory to use the fast variants for production workloads.
    2. Resize images appropriately — Tesseract works best with text at 300 dots per inch (DPI). Images that are too large waste processing time; images that are too small reduce accuracy. Resize to an optimal range before OCR.
    3. Limit the recognition region — If you only need text from a specific area, crop the image before passing it to Tesseract. This reduces processing time significantly.
    4. Use the right PSM mode — Choosing the correct page segmentation mode avoids unnecessary layout analysis. For single text blocks, --psm 6 is faster than the default --psm 3.
    5. Process pages in parallel — For multipage documents, use Python’s concurrent.futures to OCR pages in parallel:
    from concurrent.futures import ThreadPoolExecutor
    import pytesseract
    from pdf2image import convert_from_path
    images = convert_from_path('document.pdf')
    def ocr_page(image):
    return pytesseract.image_to_string(image)
    with ThreadPoolExecutor(max_workers=4) as executor:
    results = list(executor.map(ocr_page, images))
    full_text = '\n'.join(results)
    1. Cache preprocessed images — If you’re iterating on OCR settings, save preprocessed images to disk so you don’t repeat expensive preprocessing steps.

    For high-volume document processing, consider automated OCR workflows or the Nutrient OCR API, which handles preprocessing and optimization automatically.

    Common errors and troubleshooting

    Most issues fall into four categories: the Tesseract engine can’t be found, output is empty or incorrect, the Python library won’t import, or processing is too slow.

    TesseractNotFoundError

    This means Python cannot locate the Tesseract executable. Fix it by setting the path explicitly:

    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' # Windows
    # pytesseract.pytesseract.tesseract_cmd = '/usr/local/bin/tesseract' # macOS/Linux

    Empty or garbled output

    If Tesseract returns empty strings or incorrect characters, check these common causes:

    • Image quality — Apply grayscale conversion, thresholding, and noise removal before OCR.
    • Wrong PSM mode — Try --psm 6 for blocks of text, --psm 7 for single lines.
    • Wrong language — Specify the correct language with lang='eng' or install additional language packs.
    • Low resolution — Upscale images to at least 300 DPI for reliable recognition.

    Import errors

    If import pytesseract fails, ensure the library is installed in the correct Python environment. See the troubleshooting guide in our pytesseract tutorial for detailed solutions.

    Slow processing

    If OCR is taking too long, reduce image resolution, use tessdata_fast models, limit the recognition region, or switch to parallel processing as described in the performance optimization section above.

    Common OCR challenges

    The most frequent sources of reduced accuracy are poor image quality, unusual fonts, and non-standard characters.

    Low-quality images

    For blurry or noisy images, apply preprocessing before OCR:

    • Denoising — cv2.fastNlMeansDenoising()
    • Binarization — cv2.threshold()

    Text in uncommon fonts

    Tesseract may struggle with decorative or distorted fonts. Try training Tesseract on custom font data, or apply additional image processing to increase contrast and clarity.

    Non-standard characters

    If Tesseract misrecognizes special characters or symbols, verify that you have the correct language data installed and try adjusting the OEM or PSM settings.

    Nutrient OCR solutions and features

    Nutrient offers OCR across multiple platforms, extracting text from scanned PDFs and images to make documents searchable and editable.

    Nutrient products supporting OCR

    Nutrient also supports OCR on Mac Catalyst, React Native, and Flutter.

    Key differentiators

    • Searchable PDFs — Converts scanned documents into searchable, selectable text with the original layout preserved.
    • Built-in preprocessing — No manual grayscale/threshold/deskew steps required.
    • Batch processing — Single API call for multipage documents. See our guide on automated PDF OCR workflows.

    OCR may require an additional license component. For more details, visit Nutrient OCR solutions or contact Sales.

    Conclusion

    Tesseract with Python is a free, customizable option for text recognition — from digitizing medical records to automating data entry. Image preprocessing and the right PSM/OEM settings make the biggest difference in accuracy. For production OCR that outputs searchable PDFs without manual preprocessing, see the Nutrient OCR API or contact Sales.

    Related Python guides

    OCR and document processing

    FAQ

    How does Tesseract OCR work with Python?

    Tesseract OCR reads image pixels and applies recognition algorithms to identify characters. The pytesseract Python wrapper calls the Tesseract engine and returns the extracted text as a string, making it easy to integrate OCR into Python scripts.

    What is pytesseract?

    pytesseract is a Python wrapper library for the Tesseract OCR engine. It provides a simple interface — pytesseract.image_to_string(image) — that lets you extract text from images directly in Python without interacting with the C++ engine. You need both Tesseract (the engine) and pytesseract (the Python wrapper) installed.

    What are the best practices for enhancing Tesseract OCR accuracy?

    Start with high-quality images and apply preprocessing: grayscale conversion, thresholding, and noise removal. Then tune the page segmentation mode (PSM) and OCR engine mode (OEM) to match your document layout. These two steps account for most accuracy gains.

    How do I OCR a PDF with pytesseract?

    pytesseract doesn’t support PDFs directly. Convert PDF pages to images first using the pdf2image library: images = convert_from_path('file.pdf'). Then run pytesseract.image_to_string() on each image. You also need Poppler installed on your system. For native PDF OCR without this extra step, use the Nutrient OCR API.

    How do I fix TesseractNotFoundError?

    This error means Python cannot find the Tesseract executable. Either add Tesseract to your system PATH, or set the path explicitly: pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' on Windows, or pytesseract.pytesseract.tesseract_cmd = '/usr/local/bin/tesseract' on macOS/Linux.

    How does Nutrient enhance OCR workflows in modern applications?

    Nutrient adds batch processing, built-in preprocessing, and multiplatform support on top of what Tesseract offers. The API produces searchable PDFs directly, which removes the need to build your own post-processing pipeline.

    Which Nutrient product is best for web-based OCR integration?

    Nutrient Web SDK handles OCR through Document Engine in server-backed mode. It extracts text from documents and images delivered via the browser and returns searchable PDF output.

    How does the Nutrient OCR API handle scanned documents?

    The Nutrient OCR API accepts PDF or image input via a REST call and returns a searchable PDF with an embedded text layer. It handles preprocessing automatically, so you don’t need to manage grayscale conversion, thresholding, or deskewing yourself.

    Can Tesseract handle handwritten text?

    Tesseract has limited support for handwriting recognition out of the box. While it can recognize clearly printed handwriting, it struggles with cursive or informal handwriting. For better results with handwritten text, consider training Tesseract on a custom dataset of handwriting samples, or use a commercial OCR solution with built-in handwriting support.

    What image formats does pytesseract support?

    pytesseract supports all image formats that Pillow (PIL) can open, including PNG, JPEG, TIFF, BMP, GIF, and WebP. For best OCR results, use lossless formats like PNG or TIFF. JPEG compression artifacts can reduce accuracy, especially with small or low-contrast text.

    Hulya Masharipov

    Hulya Masharipov

    Technical Writer

    Hulya is a frontend web developer and technical writer who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

    Explore related topics

    Free to start Start extracting structured data