Sub topic 5
Preprocessing Images Before OCR Recognition
This chapter assumes basic Python, pip, terminal use, and familiarity with images as pixel arrays. You should also know that an image usually stores color channels, such as red, green, and blue.
OCR engines work best when characters are clear, separated, and aligned. Preprocessing changes the image before recognition so the engine can distinguish text from its background. It cannot recover text that was never captured, but it can reduce distractions such as shadows, compression noise, and uneven lighting.
Where preprocessing fits
An OCR pipeline usually has three stages:
- Detection finds regions that may contain text.
- Recognition converts each text region into characters and words.
- Output returns plain text, coordinates, confidence scores, or all three.
Preprocessing happens before detection or recognition, depending on the engine and workflow.
Image problems that affect OCR
Resolution, contrast, noise, and skew strongly affect recognition. The following table connects a symptom to a useful response.
| Image problem | Typical symptom | Useful preprocessing |
|---|---|---|
| Low contrast | Text and background have similar brightness | Contrast adjustment or adaptive thresholding |
| Uneven lighting | One side of the page is darker | Adaptive thresholding or background correction |
| Speckle noise | Isolated dots appear near characters | Median or morphological filtering |
| Skew | Text lines are tilted | Deskewing with a rotation |
| Small characters | Letters contain too few pixels | Upscaling before recognition |
Do not apply every operation automatically. An aggressive filter can erase punctuation, thin strokes, or accents. Compare the processed image with the original.
Grayscale conversion
Color often adds information that OCR does not need. Grayscale replaces each pixel with a brightness value. This reduces a three-channel color image to one channel and makes later operations simpler.
For OpenCV images, use cv2.COLOR_BGR2GRAY because OpenCV reads color images in blue-green-red order.
Thresholding with Otsu’s method
Thresholding converts an image into two classes, commonly black text and a white background. Otsu’s method chooses a threshold from the image’s brightness histogram instead of requiring you to select a number manually.
import cv2
import pytesseract
image = cv2.imread("receipt.jpg")
if image is None:
raise FileNotFoundError("Could not read receipt.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(
gray,
0,
255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU,
)
text = pytesseract.image_to_string(binary, config="--psm 6")
print(text)The first return value from cv2.threshold is the threshold selected by Otsu’s method. The second is the resulting binary image. Passing 0 tells OpenCV to calculate the threshold.
For shadows or gradients, global Otsu thresholding may fail because one threshold cannot fit the entire page. Adaptive thresholding calculates a threshold for local neighborhoods:
binary = cv2.adaptiveThreshold(
gray,
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
31,
11,
)The block size must be an odd number. The final value is subtracted from the local weighted mean. Larger block sizes respond to broader lighting changes.
Denoising and deskewing
Denoising removes small variations that are unlikely to be characters. A median filter is often useful for isolated salt-and-pepper noise:
denoised = cv2.medianBlur(gray, 3)The number 3 is the kernel size. Larger kernels remove more noise but can blur narrow strokes.
Deskewing rotates a page so text lines become horizontal. A small angle can make a large difference because character segmentation depends on consistent baselines. A practical workflow is to detect the dominant text-line angle, rotate the image, and then apply thresholding. Deskewing is more involved than grayscale conversion, so use it when inspection shows a real tilt.
A repeatable preprocessing workflow
Use this order when diagnosing a poor scan:
- Inspect the original at its actual resolution.
- Convert to grayscale.
- Try OCR on the grayscale image.
- Add denoising only if visible noise causes errors.
- Compare Otsu and adaptive thresholding.
- Deskew when text lines are visibly tilted.
- Keep the version that produces better measured accuracy.
Exercise
Exercise
A scanned page has a dark shadow along one edge and faint text elsewhere. Why might Otsu thresholding fail, and what should you try next?
Show answer
Otsu uses one global threshold, so the shadow and faint text may require different values. Try adaptive thresholding, then compare its OCR output with the grayscale version.