Python Central HubSign in

Python Projects / Advanced

Optical Character Recognition

A Python application for recognizing text in images using OCR, featuring image processing, text extraction, and a CLI interface.

Abstract

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.

Prerequisites

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

Before you Start

Install Python and the required libraries:

Shell
pip install pytesseract opencv-python numpy

Getting Started

Create a Project

  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.

Write the Code

Optical Character RecognitionSource
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()

Example Usage

Shell
python optical_character_recognition.py

How it fits together

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

Explanation

Key Features

  • 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.

Code Breakdown

  1. What it imports (lines 1–3)
Python
import cv2
import pytesseract
import numpy as np
  1. OpticalCharacterRecognition — the class (lines 5–20)
Python
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.

Features

  • 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

Next Steps

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

Educational Value

This project teaches:

  • Computer Vision: OCR and image processing
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code

Real-World Applications

  • Document Digitization
  • Accessibility Tools
  • AI Platforms

Checkpoint exercise

This checkpoint practises binarising a tiny glyph and matching it to the closest character template.

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Conclusion

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.

Was this page helpful?

Let us know how we did