Develop a Python function to perform optical character recognition (OCR) using Tesseract.
- User
Develop a Python function to perform optical character recognition (OCR) using Tesseract.
- Assistant
Developing OCR function
The user is asking me to create a Python function for OCR using Tesseract without specifying a platform. I'm thinking of providing a snippet that uses the pytesseract library, and I’ll include installation instructions, explain how to configure the Tesseract path, and discuss handling different languages. It’s important to ensure the code is up-to-date for 2024 and handles errors effectively. I’ll also provide example usage in markdown format.Crafting OCR function
I’ll provide installation commands for Tesseract on different operating systems: for Linux, it's
apt install tesseract-ocr, and for macOS,brew install tesseract. For Windows, I’ll suggest installing the system binary and runningpip install pytesseract pillow.Next, I’m crafting the function to perform OCR using pytesseract. It will accept either an image path or a PIL.Image and handle text extraction with optional language support. I’ll also include some example usage and a docstring for clarity! Below is a minimal, reusable Python function for OCR using Tesseract via the
pytesseractwrapper.1. Install dependencies
System Tesseract (required)
- Ubuntu/Debian:
sudo apt update sudo apt install tesseract-ocr - macOS (Homebrew):
brew install tesseract - Windows:
- Download the Tesseract installer from:
https://github.com/tesseract-ocr/tesseract/wiki/Downloads - Install it, and note the installation path (e.g.
C:\Program Files\Tesseract-OCR\tesseract.exe)
- Download the Tesseract installer from:
Python packages
pip install pytesseract pillow
2. Python OCR function
from typing import Union from PIL import Image import pytesseract # Uncomment and set this on Windows if pytesseract can't find Tesseract automatically: # pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" def perform_ocr( image: Union[str, Image.Image], lang: str = "eng", config: str | None = None ) -> str: """ Run OCR on an image using Tesseract. Parameters ---------- image : str or PIL.Image.Image Path to an image file (e.g., 'image.png') or a loaded PIL Image. lang : str, optional Tesseract language code(s), e.g. 'eng', 'deu', 'eng+spa'. Default is 'eng'. config : str, optional Extra Tesseract config, e.g. '--psm 6 --oem 3'. Returns ------- str Extracted text from the image. """ # Load image if a path is provided if isinstance(image, str): img = Image.open(image) elif isinstance(image, Image.Image): img = image else: raise TypeError("image must be a file path or PIL.Image.Image") # Optional simple pre-processing: convert to grayscale (often improves OCR) img = img.convert("L") # Run Tesseract OCR text = pytesseract.image_to_string(img, lang=lang, config=config or "") return text
3. Example usage
if __name__ == "__main__": # From image file path text = perform_ocr("sample_image.png", lang="eng") print(text) # With additional config (e.g., treat image as a single block of text) text2 = perform_ocr("scanned_page.jpg", lang="eng", config="--psm 6") print(text2)If you tell me your OS and typical image format (e.g., photos vs. scanned PDFs), I can adjust the function with better pre-processing steps for your case.
- Ubuntu/Debian:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.