Skip to main content

Lesson 11 of 12

Module 7 Practice 2

Advanced OCR practice tasks.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Removing Noise

Removing Noise
import cv2
import numpy as np

def prepare_invoice_for_ocr(image_path):
    """
    Special pre-processing pipeline optimised for receipts and invoices.
    Invoices often have fine print, tables, and mixed content.
    """
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Upscale if image is small (Tesseract needs sufficient resolution)
    h, w = gray.shape
    if w < 1000:
        scale = 1000 / w
        gray = cv2.resize(gray, None, fx=scale, fy=scale,
                         interpolation=cv2.INTER_CUBIC)
        print(f"Upscaled from {w}px to {int(w*scale)}px width")

    # Sharpen to make thin characters more distinct
    kernel = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])
    sharpened = cv2.filter2D(gray, -1, kernel)

    # Adaptive threshold — better for invoices with varying background
    binary = cv2.adaptiveThreshold(
        sharpened, 255,
        cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
        cv2.THRESH_BINARY,
        blockSize=15, C=10
    )

    # Clean
    kernel = np.ones((1,1), np.uint8)
    cleaned = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)

    cv2.imwrite("invoice_prepared.jpg", cleaned)
    return cleaned
Diagram
Loading diagram…

Machine Learning follows a structured pipeline from data to deployment

Finished this lesson?

0 of 12 in Module 7
Sign in to save progress

Topics in This Module

0/12 done