2 min read

Image Text Extractor (OCR)

This utility extracts text from images using the pytesseract library, which is a wrapper for Google's Tesseract-OCR Engine. It supports multiple languages and can output text to the console or a file.

Modules Used:

  • pytesseract: Python wrapper for Google's Tesseract-OCR.
  • Pillow: To open and manipulate image files.
  • argparse: To handle command-line arguments.

Prerequisites

  1. Install Tesseract Engine: You must install the Tesseract binary separately.

    • Windows: Download the installer from UB-Mannheim.
    • Linux: sudo apt install tesseract-ocr
    • macOS: brew install tesseract
  2. Install Python Libraries:

    pip install pytesseract Pillow

The Code

Save this as ocr_tool.py.

import pytesseract
from PIL import Image
import argparse
import os
import sys

# NOTE: If Tesseract is not in your PATH, uncomment and set the correct path below:
# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

def extract_text(image_path, output_file=None, lang='eng'):
    if not os.path.exists(image_path):
        print(f"Error: Image file '{image_path}' not found.")
        return

    try:
        print(f"Processing '{image_path}'...")

        # Open the image using Pillow
        img = Image.open(image_path)

        # Perform OCR
        # image_to_string converts the image to text
        text = pytesseract.image_to_string(img, lang=lang)

        if output_file:
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(text)
            print(f"Success! Text saved to '{output_file}'")
        else:
            print("\n--- Extracted Text ---")
            print(text.strip())
            print("----------------------")

    except pytesseract.TesseractNotFoundError:
        print("Error: Tesseract is not installed or not in your PATH.")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Image Text Extractor (OCR)")
    parser.add_argument("image", help="Path to the image file")
    parser.add_argument("-o", "--output", help="Output text file (optional)")
    parser.add_argument("-l", "--lang", default="eng", help="Language code (default: eng)")

    args = parser.parse_args()

    extract_text(args.image, args.output, args.lang)

Usage

python ocr_tool.py receipt.jpg --output receipt_text.txt

programming/python/python