"""
Optical Character Recognition (OCR) function using Tesseract.
Prerequisites:
1. Install Tesseract OCR binary:
- Windows: Download from https://github.com/UB-Mannheim/tesseract/wiki
- macOS: brew install tesseract
- Linux: sudo apt install tesseract-ocr (Ubuntu/Debian)
2. Install Python packages:
pip install pytesseract pillow
3. Optionally, install language packs: e.g., sudo apt install tesseract-ocr-eng tesseract-ocr-fra
Usage:
text = ocr_image('path/to/image.png')
print(text)
"""
import pytesseract
from PIL import Image
from typing import Union, Optional
import os
def ocr_image(
image_path_or_pil: Union[str, Image.Image],
lang: str = 'eng',
config: Optional[str] = None,
tesseract_cmd: Optional[str] = None
) -> str:
"""
Perform OCR on an image using Tesseract.
Args:
image_path_or_pil (str or PIL.Image): Path to image file or PIL Image object.
lang (str): Tesseract language code (default: 'eng' for English).
config (str, optional): Additional Tesseract config string (e.g., '--psm 6' for uniform block of text).
tesseract_cmd (str, optional): Path to tesseract executable if not in PATH.
Returns:
str: Extracted text from the image.
Raises:
FileNotFoundError: If image path is invalid.
pytesseract.TesseractError: If Tesseract fails to process the image.
"""
# Set tesseract command path if provided
if tesseract_cmd:
pytesseract.pytesseract.tesseract_cmd = tesseract_cmd
# Load image
if isinstance(image_path_or_pil, str):
if not os.path.exists(image_path_or_pil):
raise FileNotFoundError(f"Image file not found: {image_path_or_pil}")
image = Image.open(image_path_or_pil)
else:
image = image_path_or_pil
# Convert to RGB if necessary (Tesseract prefers grayscale/RGB)
if image.mode != 'RGB' and image.mode != 'L':
image = image.convert('RGB')
# Build config
custom_config = f'--oem 3 --psm 6 -l {lang}' # OEM 3 (default LSTM), PSM 6 (uniform block)
if config:
custom_config += f' {config}'
# Perform OCR
try:
text = pytesseract.image_to_string(image, config=custom_config)
return text.strip()
except pytesseract.TesseractError as e:
raise pytesseract.TesseractError(f"Tesseract OCR failed: {str(e)}")
# Example usage
if __name__ == "__main__":
# Replace with your image path
image_path = "example_image.png"
try:
extracted_text = ocr_image(image_path, lang='eng')
print("Extracted text:")
print(extracted_text)
except Exception as e:
print(f"Error: {e}")
Key Features:
- Flexible input: Accepts file path (str) or PIL Image object.
- Language support: Specify
lang (e.g., 'eng+fra' for English+French).
- Custom config: Pass Tesseract flags like
'--psm 3' (fully automatic) via config.
- Error handling: Checks file existence and Tesseract errors.
- Optimized defaults: Uses LSTM engine (
--oem 3) and block text mode (--psm 6).
- Production-ready: Includes type hints, docstrings, and example.
For better accuracy:
- Preprocess images (e.g., resize, deskew) using OpenCV/PIL.
- Use
pytesseract.image_to_data() for bounding boxes/confidence.