OCR Mini Project
Build a complete OCR document reader that extracts, cleans, and saves text from any image.
15 min•By Priygop Team•Updated 2026
Document Reader Project
Document Reader Project
import cv2
import numpy as np
import pytesseract
from PIL import Image
import re
class DocumentReader:
"""A complete OCR document reader with pre-processing and output options."""
def __init__(self, lang="eng"):
self.lang = lang
def preprocess(self, image):
"""Pre-process image for best OCR accuracy."""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
denoised = cv2.fastNlMeansDenoising(gray, h=10)
_, binary = cv2.threshold(denoised, 0, 255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU)
kernel = np.ones((1, 1), np.uint8)
cleaned = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
padded = cv2.copyMakeBorder(cleaned, 15, 15, 15, 15,
cv2.BORDER_CONSTANT, value=255)
return padded
def read(self, image_path, config="--psm 6"):
"""Read text from an image file."""
image = cv2.imread(image_path)
if image is None:
return {"error": f"Could not load: {image_path}"}
preprocessed = self.preprocess(image)
raw_text = pytesseract.image_to_string(preprocessed,
lang=self.lang, config=config)
# Clean the extracted text
cleaned_text = self._clean_text(raw_text)
# Get word count and character count
words = cleaned_text.split()
chars = len(cleaned_text)
return {
"text": cleaned_text,
"word_count": len(words),
"char_count": chars,
"lines": cleaned_text.split("\n"),
}
def _clean_text(self, text):
"""Remove common OCR noise."""
# Remove multiple spaces and normalise whitespace
text = re.sub(r" +", " ", text)
text = re.sub(r"\n\n+", "\n\n", text)
return text.strip()
def save_text(self, image_path, output_path):
"""Read from image and save text to file."""
result = self.read(image_path)
if "error" in result:
print(result["error"])
return
with open(output_path, "w", encoding="utf-8") as f:
f.write(result["text"])
print(f"=== OCR Complete: {image_path} ===")
print(f"Words: {result['word_count']}")
print(f"Characters: {result['char_count']}")
print(f"Saved to: {output_path}")
print("\nFirst 200 characters:")
print(result["text"][:200])
# Use the reader
reader = DocumentReader(lang="eng")
reader.save_text("document.jpg", "extracted_text.txt")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment
Key Takeaways from Module 7
- OCR converts text in images to machine-readable digital text
- Tesseract is the most widely used open-source OCR engine; pytesseract is the Python interface
- Pre-processing is the most critical step: grayscale → denoise → threshold → clean
- pytesseract.image_to_data() returns word-level confidence scores and bounding boxes
- PSM (Page Segmentation Mode) controls how Tesseract analyses the layout — use --psm 6 for documents
- OCR struggles with handwriting, low resolution, skewed text, and stylised fonts
- Always add padding around the image before passing to Tesseract for better accuracy
Key Takeaways
- Build a complete OCR document reader that extracts, cleans, and saves text from any image.
- OCR converts text in images to machine-readable digital text
- Tesseract is the most widely used open-source OCR engine; pytesseract is the Python interface
- Pre-processing is the most critical step: grayscale → denoise → threshold → clean