Skip to content

Optical Character Recognition

Optical Character Recognition is a Python project that uses OCR to recognize text in images. The application features image processing, text extraction, and a CLI interface, demonstrating best practices in computer vision and automation.

  • Python 3.8 or above
  • A code editor or IDE
  • Basic understanding of OCR and computer vision
  • Required libraries: pytesseract, opencv-python, numpy

Install Python and the required libraries:

Install dependencies
pip install pytesseract opencv-python numpy
  1. Create a folder named optical-character-recognition.
  2. Open the folder in your code editor or IDE.
  3. Create a file named optical_character_recognition.py.
  4. Copy the code below into your file.
Optical Character Recognition pch.viewSource
Optical Character Recognition
import cv2
import pytesseract
import numpy as np

class OpticalCharacterRecognition:
    def __init__(self):
        pass

    def recognize_text(self, image):
        text = pytesseract.image_to_string(image)
        print(f"Recognized text: {text}")
        return text

    def demo(self):
        img = np.zeros((100, 300, 3), dtype=np.uint8)
        cv2.putText(img, 'Python OCR', (5, 70), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 3)
        self.recognize_text(img)
        show_or_save('OCR Demo', img)
        wait_or_skip(1000)
        cv2.destroyAllWindows() if "--show" in __import__("sys").argv else None

def wait_or_skip(delay=0):
    """cv2.waitKey needs a window; without one it raises. Skip it instead."""
    import sys

    if "--show" in sys.argv:
        return cv2.waitKey(delay)
    return -1


def show_or_save(title, image, _counter=[0]):
    """Display the frame, or write it to a file when no window is available.

    Headless OpenCV has no GUI at all, and even a full build cannot open a
    window over SSH or inside a container. Falling back to a file keeps the
    project runnable everywhere and leaves something to look at afterwards.
    """
    import os
    import re as _re

    if "--show" in __import__("sys").argv:
        cv2.imshow(title, image)
        return None
    _counter[0] += 1
    stem = _re.sub(r"\W+", "_", title).strip("_").lower() or "frame"
    name = f"{stem}.png" if _counter[0] == 1 else f"{stem}_{_counter[0]}.png"
    cv2.imwrite(name, image)
    print(f"saved {name}  ({os.path.getsize(name):,} bytes)")
    return name


if __name__ == "__main__":
    print("Optical Character Recognition Demo")
    ocr = OpticalCharacterRecognition()
    ocr.demo()
Run OCR
python optical_character_recognition.py

Read from the top: this is what runs when you execute the file, and which function calls which. It is generated from the code, so it cannot drift from it.

diagram Diagram mermaid
  • OCR: Recognizes text in images.
  • Image Processing: Prepares images for text extraction.
  • Error Handling: Validates inputs and manages exceptions.
  • CLI Interface: Interactive command-line usage.
  1. What it imports (lines 1–3)
optical_character_recognition.py
import cv2
import pytesseract
import numpy as np
  1. OpticalCharacterRecognition — the class (lines 5–20)
optical_character_recognition.py
class OpticalCharacterRecognition:
    def __init__(self):
        pass
 
    def recognize_text(self, image):
        text = pytesseract.image_to_string(image)
        print(f"Recognized text: {text}")
        return text
 
    def demo(self):
        img = np.zeros((100, 300, 3), dtype=np.uint8)
        cv2.putText(img, 'Python OCR', (5, 70), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 3)
        self.recognize_text(img)
        cv2.imshow('OCR Demo', img)
        cv2.waitKey(1000)
        cv2.destroyAllWindows()

The file defines 1 top-level symbol in all; the whole thing is above under Write the Code.

  • OCR: Text recognition and image processing
  • Modular Design: Separate functions for each task
  • Error Handling: Manages invalid inputs and exceptions
  • Production-Ready: Scalable and maintainable code

Enhance the project by:

  • Integrating with real image datasets
  • Supporting advanced OCR algorithms
  • Creating a GUI for OCR
  • Adding real-time recognition
  • Unit testing for reliability

This project teaches:

  • Computer Vision: OCR and image processing
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code
  • Document Digitization
  • Accessibility Tools
  • AI Platforms

Optical Character Recognition demonstrates how to build a scalable and accurate OCR tool using Python. With modular design and extensibility, this project can be adapted for real-world applications in digitization, accessibility, and more. For more advanced projects, visit Python Central Hub.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading