Sub topic 5
Preprocessing images before recognition
This chapter assumes you can run Tesseract from Python with pytesseract, that you know OpenCV images are NumPy arrays in BGR order, and that you have read the earlier chapter on image quality (resolution, contrast, noise, skew). Here you will apply fixes for those problems and learn how to tell whether a fix helped.
What preprocessing is for
Preprocessing transforms an image before it reaches the recognizer. The goal is to make the text look like what the engine was trained on: dark, evenly lit characters on a plain light background, upright, and large enough to resolve.
Each step targets one defect:
| Defect | Step |
|---|---|
| Color channels carry no text information | Grayscale conversion |
| Characters under about 20 px tall | Upscaling |
| Speckle, sensor noise, JPEG artifacts | Denoising |
| Gray background, faint ink | Thresholding |
| Uneven lighting, shadows | Adaptive thresholding |
| Page rotated a few degrees | Deskewing |
| Text touching the image edge | Border padding |
Grayscale conversion
Tesseract needs intensity, not color. Converting to grayscale collapses three channels into one and makes later steps simpler.
import cv2
image = cv2.imread("receipt.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
print(image.shape, gray.shape)cv2.imread returns BGR, so use COLOR_BGR2GRAY. Using COLOR_RGB2GRAY on a BGR array weights the channels wrongly. The result is subtly off, not broken, which makes the mistake easy to miss.
Grayscale averages channels with fixed weights. If your text is red on a dark blue background, the two colors can map to nearly the same gray. In that case, inspect the individual channels with cv2.split and pick the one with the best contrast.
Resizing
Tesseract works best when the height of a typical lowercase letter is around 20 to 30 pixels, which is roughly a 300 DPI scan of ordinary body text. Screenshots and phone photos of distant documents are often well below that.
import cv2
gray = cv2.imread("small_text.png", cv2.IMREAD_GRAYSCALE)
upscaled = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
print(gray.shape, upscaled.shape)Use INTER_CUBIC or INTER_LANCZOS4 to enlarge, and INTER_AREA to shrink. Upscaling adds no information, but it gives the recognizer more pixels per stroke, so thin strokes survive later steps. Enlarging beyond about 3x rarely helps and slows recognition.
Denoising
Noise breaks strokes and adds specks the engine may read as punctuation. Two filters cover most cases:
cv2.medianBlur(gray, 3)replaces each pixel with the median of its neighborhood. It removes salt-and-pepper speckle and keeps edges sharp. The kernel size must be odd.cv2.fastNlMeansDenoising(gray, None, h=10)handles broader noise such as JPEG blocking and camera grain. It is slower, and a largehsmears thin strokes.
import cv2
gray = cv2.imread("noisy.png", cv2.IMREAD_GRAYSCALE)
median = cv2.medianBlur(gray, 3)
nlm = cv2.fastNlMeansDenoising(gray, None, h=10)A Gaussian blur also reduces noise, but it softens character edges, so prefer the median filter before thresholding.
Thresholding
Thresholding turns a grayscale image into pure black and white by comparing each pixel with a cutoff. It removes background texture and fixes faint ink, provided the cutoff is chosen well.
Global thresholds and Otsu's method
A global threshold uses one cutoff for the whole image. Otsu's method picks that cutoff automatically by finding the value that best separates the histogram into two groups, dark text and light background.
import cv2
gray = cv2.imread("scan.png", cv2.IMREAD_GRAYSCALE)
cutoff, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print("Otsu cutoff:", cutoff)When you pass THRESH_OTSU, the threshold argument (0 here) is ignored and the computed cutoff is returned as the first value. Otsu works well when lighting is even and the histogram has two clear peaks.
Adaptive thresholding
Under a shadow or a lighting gradient, one cutoff fails: part of the page turns solid black or solid white. Adaptive thresholding computes a separate cutoff for each pixel from its local neighborhood.
import cv2
gray = cv2.imread("shadowed_page.jpg", cv2.IMREAD_GRAYSCALE)
adaptive = cv2.adaptiveThreshold(
gray, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
blockSize=31,
C=15,
)blockSize is the neighborhood width in pixels and must be odd. Make it larger than a character stroke and a character's height, or strokes will hollow out. C is subtracted from the local mean. A larger C suppresses more background noise but erodes faint text.
| Method | Good for | Fails when |
|---|---|---|
| Otsu | Even lighting, clean scans | Shadows, gradients, mixed backgrounds |
| Adaptive Gaussian | Uneven lighting, photos of pages | Large filled areas, which turn into noise |
Deskewing
Text rotated by even 2 to 3 degrees can hurt line detection. Tesseract tolerates small skews, but larger ones cause lines to merge or split.
A reliable method is the projection profile. When lines are perfectly horizontal, the row-wise sum of text pixels alternates sharply between dense text rows and empty gaps. That sharpness is highest at the correct angle. Because the code scores candidates by rotating with the same function it later uses to correct the image, there is no sign-convention problem to get wrong.
import cv2
import numpy as np
def rotate(image, angle, border_value):
h, w = image.shape[:2]
matrix = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)
return cv2.warpAffine(
image, matrix, (w, h),
flags=cv2.INTER_CUBIC,
borderMode=cv2.BORDER_CONSTANT,
borderValue=border_value,
)
def skew_score(ink, angle):
rotated = rotate(ink, angle, 0)
profile = rotated.sum(axis=1, dtype=np.float64)
return float(np.sum(np.diff(profile) ** 2))
def estimate_skew(gray, limit=10.0):
scale = 800 / max(gray.shape)
small = cv2.resize(gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
_, ink = cv2.threshold(small, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
coarse = np.arange(-limit, limit + 0.01, 0.5)
best = max(coarse, key=lambda a: skew_score(ink, a))
fine = np.arange(best - 0.5, best + 0.51, 0.1)
return max(fine, key=lambda a: skew_score(ink, a))
def deskew(gray):
angle = estimate_skew(gray)
return rotate(gray, angle, 255), angle
if __name__ == "__main__":
gray = cv2.imread("tilted.png", cv2.IMREAD_GRAYSCALE)
straight, angle = deskew(gray)
print(f"Corrected by {angle:.1f} degrees")
cv2.imwrite("straight.png", straight)The estimate runs on an 800-pixel version of the page for speed, and the final rotation uses the full-size image. The limit of 10 degrees covers typical scanner and phone tilt. Pages tilted further, or photographed at an angle, need a perspective correction instead, because rotation cannot fix keystone distortion.
The profile method assumes lines of text. On an image with a single word, a logo, or a table with strong vertical rules, the score can peak at the wrong angle. Check the output visually.
Border padding
Characters that touch the image edge are often dropped or misread, because the engine finds no background around them. Adding a margin of white is cheap insurance, especially for tight crops.
import cv2
binary = cv2.imread("crop.png", cv2.IMREAD_GRAYSCALE)
padded = cv2.copyMakeBorder(
binary, 20, 20, 20, 20, cv2.BORDER_CONSTANT, value=255
)The value 255 is white. If you inverted the image so text is white on black, pad with 0 instead. Tesseract expects dark text on a light background.
Putting the steps together
The function below applies the full chain and measures its effect. Mean word confidence is a quick proxy when you have no ground truth. It is not a measure of correctness, since an engine can be confidently wrong, so confirm with character error rate when you have reference text.
import cv2
import pytesseract
from pytesseract import Output
def mean_confidence(image, config="--psm 6"):
data = pytesseract.image_to_data(image, config=config, output_type=Output.DICT)
scores = [
float(c) for c, t in zip(data["conf"], data["text"])
if t.strip() and float(c) >= 0
]
return sum(scores) / len(scores) if scores else 0.0
def preprocess(gray, scale=2, use_adaptive=False):
gray = cv2.resize(gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
gray = cv2.medianBlur(gray, 3)
if use_adaptive:
binary = cv2.adaptiveThreshold(
gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 15
)
else:
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return cv2.copyMakeBorder(binary, 20, 20, 20, 20, cv2.BORDER_CONSTANT, value=255)
gray = cv2.imread("receipt.jpg", cv2.IMREAD_GRAYSCALE)
variants = {
"grayscale only": gray,
"otsu pipeline": preprocess(gray),
"adaptive pipeline": preprocess(gray, use_adaptive=True),
}
for name, img in variants.items():
print(f"{name:20s} mean confidence {mean_confidence(img):5.1f}")To add deskewing, call deskew(gray) from the previous section before preprocess. Deskew first on the grayscale image, so the thresholding sees clean edges and the rotation does not interpolate binary pixels into gray ones.
Order matters
Steps interact, so the sequence affects the result:
- Upscale before thresholding, so the threshold sees smoother edges and thin strokes keep their width.
- Denoise before thresholding. A speck that survives thresholding becomes a solid black dot.
- Deskew before final binarization when possible, so rotation interpolates gray values.
- Pad last, so the margin stays pure white.
When preprocessing hurts
More steps do not mean better output. Common failures:
- Binarizing an already clean, high-contrast image removes antialiasing that the recognizer uses.
- Aggressive denoising erases dots, accents, and thin serifs, turning
iintoloréintoe. - An adaptive threshold with a small
blockSizeturns large letters into outlines. - Upscaling a blurry image gives a larger blurry image.
- Fixed parameters tuned on one batch fail on another with different lighting or resolution.
The working method is to start with grayscale alone, add one step at a time, and keep a step only if it improves a measurement on a representative sample of your images, not a single favorite one.
Exercise
A phone photo of a page has a dark shadow across its left third. Otsu thresholding turns that third solid black, and Tesseract returns nothing for it. Which change would you try first, and what two parameters would you tune?
Show answer
Replace the global Otsu threshold with adaptive thresholding (cv2.adaptiveThreshold with the Gaussian method), because it computes a cutoff from each pixel's local neighborhood and so ignores the lighting gradient. Tune blockSize, an odd number larger than a character's height, and C, the value subtracted from the local mean. Compare mean confidence or character error rate against the grayscale-only baseline to confirm the change helped.
Exercise
Why does the deskew code in this chapter rotate the full-size image with the angle found on a downscaled copy, and why is the downscaled image thresholded with THRESHBINARYINV?
Show answer
Estimating the angle on an image about 800 pixels across makes the many candidate rotations fast, and the angle is the same at any scale, so it can be applied to the full-size image without loss. THRESHBINARYINV makes text pixels 255 and the background 0, so the row sums count text pixels. Without the inversion, the sums would count background and the profile would still vary, but the score would no longer measure how aligned the ink is.