Sub topic 4
Why Image Quality Decides Accuracy
This chapter assumes you can run Tesseract through pytesseract, as shown in the previous chapter. It also assumes you can read an image into a NumPy array with OpenCV. You don't need to know the fixes yet. The next chapter covers preprocessing. Here you learn to recognize what is wrong with an image and to measure it.
The engine can only read what the pixels show
An OCR engine does not see a page the way you do. It sees a grid of numbers. A human fills in a smudged letter from context and experience. A classic engine like Tesseract mostly works from the shapes it can separate from the background. If a letter is only six pixels tall, or its edges merge with the paper texture, the shape the engine receives may not match the letter that was printed.
Four properties of the input cause most failures:
- Resolution: how many pixels each character gets.
- Contrast: how clearly text separates from the background.
- Noise: random pixel variation, including compression artifacts and paper grain.
- Skew and distortion: text lines that are tilted, curved, or in perspective.
Fixing the input is usually cheaper than tuning the engine. A better scan often beats any configuration flag.
Resolution: pixels per character
Resolution matters because of character size in pixels, not the image's total pixel count. A 4000 by 3000 photo of a whole desk can give each letter fewer pixels than a 1000 by 1400 scan of a single page.
For scans, resolution is quoted in DPI (dots per inch). You can convert a printed font size into pixels yourself. One point is 1/72 inch, so the height of the font's em square in pixels is point_size / 72 * dpi. Capital letters are about 70% of that height.
| Font size | DPI | Em height (px) | Capital height (px, approx.) |
|---|---|---|---|
| 10 pt | 72 | 10 | 7 |
| 10 pt | 150 | 21 | 15 |
| 10 pt | 300 | 42 | 29 |
| 10 pt | 600 | 83 | 58 |
| 6 pt (fine print) | 300 | 25 | 17 |
A commonly cited guideline for Tesseract is 300 DPI for ordinary body text, which gives capitals around 30 px tall. Accuracy usually drops as capitals approach 20 px or less. Treat these numbers as a starting point and test on your own material, because fonts, engines, and versions differ.
Higher is not always better. Very large characters, say 100 px tall, can also hurt, and they slow recognition. Between roughly 25 and 50 px capital height is a safe range for most documents.
Upscaling does not add information
If a screenshot has 8 px characters, resizing it to 3 times its size gives the engine more pixels per character, and this often helps. Tesseract's models were trained on text of typical sizes, so size matching matters. But the resize only interpolates between existing values. Detail that was never captured stays missing. Upscaling is a repair for a size mismatch, not for a blurry source.
For downscaling, use area-based interpolation (cv2.INTER_AREA), which averages pixels. Nearest-neighbor downscaling drops pixels and breaks thin strokes.
Contrast and lighting
Contrast is the difference in brightness between ink and paper. Black text on white paper gives the engine two clean populations of pixels. Problems start when the two overlap:
- Faded ink or a light pencil gives gray text on gray paper.
- Colored backgrounds, stamps, and watermarks put the background close to the ink's brightness.
- Uneven lighting, such as a shadow across a phone photo, makes the background brighter on one side than the text on the other.
Uneven lighting is the hardest case, because no single brightness cutoff separates ink from paper everywhere. The previous chapter's Otsu thresholding picks one global cutoff, so it fails on shadowed photos. Adaptive thresholding, covered in the next chapter, picks a cutoff per neighborhood.
Dark-mode text (light text on a dark background) is also a problem. Tesseract's older recognizers assume dark text on a light background. Inverted images often produce poor or empty output.
Noise and compression artifacts
Noise is variation in pixel values that is not part of the text. Common sources:
- Sensor noise in low-light photos, which appears as grain.
- Paper texture, speckle, and dust on scans or photocopies.
- JPEG compression, which leaves blocky halos around sharp edges. Heavy compression of small text is especially damaging.
- Motion blur or defocus, which smears strokes so that letters such as
e,c, andomerge.
Noise causes two kinds of error. Speckles near letters become stray punctuation such as ., ,, and '. Smearing and broken strokes cause substitutions between similar shapes: l, 1, and I, or rn read as m.
Prefer lossless formats (PNG, TIFF) when you control the capture. If you must use JPEG, high quality settings matter more for text than for photographs.
Skew and perspective
Skew is a rotation of the whole page. Tesseract's layout analysis finds text lines by grouping connected shapes horizontally. Small tilts of one or two degrees are usually tolerated. Larger tilts cause lines to be split or merged, and the reading order then goes wrong. The words may be recognized correctly but come out in a scrambled order.
Phone photos add perspective distortion. The page is a trapezoid instead of a rectangle, so text is smaller at the far end. A rotation cannot fix this, because it needs a perspective transform. Curved pages near a book spine add warping that is harder still.
How the factors lead to errors
The diagram shows how each input problem breaks a different pipeline stage.
Measuring quality before you run OCR
You can estimate three of the four factors with a few lines of code. The script below reports image size, a contrast measure, a sharpness measure, and an approximate skew angle. The numbers are heuristics, so use them to flag images for review, not as exact verdicts.
import cv2
import numpy as np
def quality_report(path):
image = cv2.imread(path)
if image is None:
raise FileNotFoundError(path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
height, width = gray.shape
# Contrast: spread between dark and light pixels (5th to 95th percentile).
low, high = np.percentile(gray, [5, 95])
contrast_range = float(high - low)
# Sharpness: variance of the Laplacian. Blurry images score low.
sharpness = float(cv2.Laplacian(gray, cv2.CV_64F).var())
# Skew: fit a rotated rectangle around all dark pixels.
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
points = cv2.findNonZero(binary)
skew = 0.0
if points is not None:
angle = cv2.minAreaRect(points)[-1]
# OpenCV versions report different angle ranges; fold into [-45, 45].
if angle > 45:
angle -= 90
elif angle < -45:
angle += 90
skew = abs(float(angle))
return {
"size": (width, height),
"contrast_range": contrast_range,
"sharpness": sharpness,
"skew_degrees": skew,
}
report = quality_report("scan.png")
for name, value in report.items():
print(name, value)Read the output with these rules of thumb:
- A
contrast_rangebelow about 80 (on a 0 to 255 scale) suggests faded text or a gray background. - A very low
sharpnesscompared to other images from the same source suggests blur. The absolute value depends on content, so compare images of similar pages. - A
skew_degreesabove 2 or 3 is worth correcting. The estimate assumes the text forms one roughly rectangular block. Photos with a visible desk or border around the page will give misleading angles.
Seeing the effect: confidence versus scale
You can test the resolution claim on your own page. This script shrinks a page image in steps and prints how many words Tesseract finds and their mean confidence. Confidence is a score from 0 to 100 that Tesseract attaches to each word. The structured-output chapter explains it fully. Here it serves as a rough proxy for how comfortable the engine is.
import cv2
import pytesseract
from pytesseract import Output
def mean_confidence(image):
data = pytesseract.image_to_data(image, output_type=Output.DICT)
scores = [
float(conf)
for conf, text in zip(data["conf"], data["text"])
if text.strip() and float(conf) >= 0
]
if not scores:
return 0.0, 0
return sum(scores) / len(scores), len(scores)
gray = cv2.imread("page.png", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise SystemExit("Could not read page.png")
for scale in (1.0, 0.75, 0.5, 0.35, 0.25):
small = cv2.resize(gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
mean, count = mean_confidence(small)
print(f"scale {scale:.2f}: {count} words, mean confidence {mean:.1f}")On a 300 DPI page you should see the word count and confidence hold steady down to about half size, then fall quickly as characters shrink toward 10 px. The exact break point depends on the font and the engine version. Run the experiment on your own documents to find where the cliff is.
Common errors and what they usually mean
| Symptom | Likely cause | First thing to check |
|---|---|---|
| Empty output | Inverted image, tiny text, or very low contrast | View the image. Is text light on dark? |
| `0` and `O`, `1` and `l` confusions | Low resolution or blur | Capital height in pixels |
| Stray `.`, `,`, `'` characters | Speckle noise or JPEG artifacts | Zoom in to 400% and look for grain |
| Right words, wrong order | Skew or multi-column layout | Estimate the skew angle |
| Left half read, right half garbage | Uneven lighting or perspective | Compare the brightness of both sides |
| Good on screenshots, bad on photos | Screenshots are crisp and aligned, photos are not | Compare the quality report for both |
Decision criteria
Before adding processing code, decide whether to improve capture instead:
- If you control the scanner or camera, set 300 DPI, use lossless output, and avoid shadows. This removes most problems at no code cost.
- If you receive files from users, run the quality report and reject or flag images that fall below your thresholds. Asking for a better upload is cheaper than silent errors.
- If images are fixed and poor, apply the preprocessing steps in the next chapter, and measure the improvement with character error rate rather than by eye.
- If images are photos of signs or products with complex backgrounds, no amount of cleanup may be enough. That is a case for the deep-learning engines covered later.
Exercise
A 10 pt document is scanned at 150 DPI, and Tesseract returns many wrong characters. Estimate the capital letter height in pixels, say whether it falls in the safe range described in this chapter, and give two ways to fix the problem.
Show answer
The em height is 10 / 72 * 150, about 21 px, and capitals are about 70% of that, so roughly 15 px. This is below the 25 to 50 px safe range, so errors are expected. Fixes: rescan at 300 DPI (capitals become about 29 px), or upscale the existing image by about 2 times with interpolation before recognition. Rescanning is better because upscaling cannot recover detail that was never captured.
Exercise
Your quality report for a phone photo shows a contrast range of 140 and a skew of 0.5 degrees, yet the left half of the page is read well and the right half is garbled. Which input factor is the most likely cause, and why did the report miss it?
Show answer
Uneven lighting (a shadow) or perspective is the likely cause. The contrast range is computed over the whole image, so a bright half and a shadowed half can together produce a wide range even though each half has poor local separation. The skew estimate also ignores perspective. To catch this, compute contrast separately for the left and right halves, or for a grid of tiles.