Preparing an Image for OCR
Image pre-processing is the most important step for accurate OCR. A well-prepared image can dramatically improve accuracy — often from 60% to 99%.
10 min•By Priygop Team•Updated 2026
OCR Pre-processing Pipeline
OCR Pre-processing Pipeline
import cv2
import numpy as np
import pytesseract
def preprocess_for_ocr(image_path):
"""
Complete OCR pre-processing pipeline.
Each step improves accuracy for different types of images.
"""
image = cv2.imread(image_path)
# Step 1: Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Step 2: Remove noise
denoised = cv2.fastNlMeansDenoising(gray, h=10)
# Step 3: Increase contrast (CLAHE)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
enhanced = clahe.apply(denoised)
# Step 4: Binarise (threshold)
_, binary = cv2.threshold(enhanced, 0, 255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Step 5: Remove noise from binary image
kernel = np.ones((1, 1), np.uint8)
cleaned = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
cleaned = cv2.morphologyEx(cleaned, cv2.MORPH_CLOSE, kernel)
# Step 6: Add padding (Tesseract works better with margins)
padded = cv2.copyMakeBorder(cleaned, 10, 10, 10, 10,
cv2.BORDER_CONSTANT, value=255)
return padded
# Compare OCR on raw vs. preprocessed image
image = cv2.imread("document.jpg")
preprocessed = preprocess_for_ocr("document.jpg")
raw_text = pytesseract.image_to_string(image)
processed_text = pytesseract.image_to_string(preprocessed)
print(f"Raw characters: {len(raw_text)}")
print(f"Processed characters: {len(processed_text)}")
print("\nProcessed result:")
print(processed_text[:300])Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment