Sub topic 12
Limitations and choosing the right tool
This chapter assumes you can run Tesseract through pytesseract, know the preprocessing steps from earlier chapters (grayscale, thresholding), and can read word-level confidence scores and character error rate (CER). Here you will learn where classic OCR breaks, how to detect those breaks in code, and how to decide between Tesseract, a deep-learning engine, a cloud service, and no OCR at all.
What classic OCR cannot do well
Tesseract works best on clean, printed, mostly horizontal text on a plain background. Each condition below moves an image away from that case, and accuracy drops as the conditions pile up.
Layout beyond a single block of text
Tesseract's page segmentation finds blocks, lines, and words. It has no real model of a document's meaning. These layouts cause trouble:
- Tables. Cells are read as ordinary text lines. The row and column structure is lost, and values from neighboring columns can merge into one line.
- Multi-column pages. On the wrong segmentation mode, lines are read straight across the columns and the sentences come out interleaved.
- Forms. Field labels, printed boxes, and handwritten entries mix together. Box borders are often read as characters such as
|,[, orI. - Mixed content. Photos, logos, and stamps next to text produce garbage words with low confidence.
The word boxes from image_to_data let you rebuild some structure yourself, for example by grouping words by their top value into rows. For complex documents this is a large amount of custom code, and it is often the point where a layout-aware tool becomes cheaper than hand-written heuristics.
Handwriting and unusual fonts
Tesseract's standard models were trained mainly on printed fonts. Cursive handwriting, stylized display fonts, and dot-matrix or thermal-printer text with faded dots fall outside that training. Neat block handwriting sometimes works, but you should expect a CER far higher than for printed text. Handwriting recognition is a separate problem and usually needs a model trained for it.
Scene text
Text in photographs (street signs, product labels, license plates) has perspective distortion, curved surfaces, shadows, glare, and arbitrary orientation. Binarization with a single global threshold, such as Otsu, often fails because lighting varies across the image. Deep-learning scene-text detectors handle these cases better. The next sections cover when that matters.
Resolution and size
Small text is a hard limit that preprocessing cannot fully fix. If a character is only a few pixels tall, there is not enough information to recognize it, and upscaling cannot create detail that was never captured. A commonly cited guideline for Tesseract is a scan near 300 DPI, which usually puts character height in the tens of pixels. Treat the exact number as a starting point and test it on your own images.
Look-alike characters and context
Classic engines still confuse characters that look alike. Common pairs are 0 and O, 1, l, and I, 5 and S, and rn and m. The CER example from the evaluation chapter (invo1ce 2O24 against invoice 2024) is exactly this kind of error. The engine's language model helps with ordinary words, but it does not help with serial numbers, IDs, or amounts, where any character sequence is possible.
Failure modes in a pipeline
OCR failures are usually silent. The engine returns a string either way, and nothing raises an exception when the string is wrong. Four patterns show up repeatedly:
| Failure mode | What you see | Typical cause | Mitigation |
|---|---|---|---|
| Empty output | Empty or whitespace-only string | Wrong inversion (light text on dark), tiny text, wrong segmentation mode | Try inversion, upscaling, other `--psm` values |
| Garbage output | Random symbols, many low-confidence words | Photo regions, heavy noise, non-text areas | Crop to the text region, filter by confidence |
| Plausible but wrong | Fluent text with a few wrong characters | Character confusion, blur | Validate fields, check digits, human review |
| Reordered output | Correct words in the wrong order | Multi-column layout, wrong segmentation mode | Choose `--psm` per layout, or sort word boxes yourself |
The third row is the most dangerous. A wrong digit in an invoice total looks exactly like a right one, so you need a way to catch it automatically.
Detecting trouble in code
A practical OCR system decides per image whether to trust the result. The script below reads an image, computes the mean word confidence, and routes the result to one of three outcomes: accept, review, or fallback. It builds on the Otsu preprocessing and image_to_data calls from earlier chapters.
import sys
import cv2
import pytesseract
from pytesseract import Output
def read_with_confidence(path, psm=6):
image = cv2.imread(path)
if image is None:
raise FileNotFoundError(path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
data = pytesseract.image_to_data(
binary, config=f"--psm {psm}", output_type=Output.DICT
)
words = []
confidences = []
for text, conf in zip(data["text"], data["conf"]):
confidence = float(conf)
# conf is -1 for entries that are not words (page, block, line rows)
if text.strip() and confidence >= 0:
words.append(text)
confidences.append(confidence)
mean_conf = sum(confidences) / len(confidences) if confidences else 0.0
return " ".join(words), mean_conf, len(words)
def triage(text, mean_conf, word_count):
if word_count == 0:
return "fallback" # nothing recognized: try another engine or settings
if mean_conf >= 85:
return "accept"
if mean_conf >= 60:
return "review" # send to a human or run field validation
return "fallback"
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "receipt.jpg"
text, mean_conf, word_count = read_with_confidence(path)
decision = triage(text, mean_conf, word_count)
print(f"words={word_count} mean_conf={mean_conf:.1f} decision={decision}")
print(text)The thresholds 85 and 60 are placeholders. Replace them after you measure CER on a labeled sample and see which confidence ranges actually separate good reads from bad ones.
Mean confidence only catches images that look bad to the engine. It cannot catch a confidently wrong O in 2O24. For that, validate the content itself, as described in the post-processing chapter: match dates and amounts against patterns, check checksums on IDs, and compare line items against totals.
Deep-learning OCR as an alternative
Deep-learning engines replace the hand-built stages with neural networks. A detection network finds text regions, including rotated or curved ones, and a recognition network reads each region. Examples include EasyOCR, PaddleOCR, and docTR (open source), and Amazon Textract, Google Cloud Vision, and Azure Document Intelligence (hosted services).
They tend to help in these situations:
- Scene text with perspective, glare, and uneven lighting.
- Rotated or curved text, and images with no clean binarization.
- Documents where layout matters, since some services return tables and key-value pairs, not just text.
- Handwriting, with models trained for it.
- Many scripts in one image, depending on the engine.
They also cost something:
- Compute. Neural networks run best on a GPU. On a CPU they can be slower than Tesseract.
- Setup size. Frameworks such as PyTorch or PaddlePaddle bring large dependencies and model downloads.
- Predictability. Tesseract's behavior is stable and well documented. A neural model can fail in less obvious ways, and its errors are harder to explain.
- Privacy and money. Hosted services receive your images, usually charge per page, and need network access. This can rule them out for medical, legal, or financial documents.
A deep-learning model is not automatically better on clean printed pages. On a sharp 300 DPI scan of a printed book page, Tesseract is often competitive and far lighter to run. Compare them on your data before switching.
Choosing an approach
Start by asking whether you need OCR at all. A PDF made from a word processor, or an export from a scanner with a text layer, already contains the text. Extracting it directly gives exact characters with no recognition errors. Run OCR only when the file is an image, or a PDF whose pages are scanned pictures.
The table summarizes the trade-offs.
| Option | Strengths | Weaknesses | Good fit |
|---|---|---|---|
| Direct text extraction | Exact, fast, no recognition errors | Only works when a text layer exists | Digital PDFs |
| Tesseract + preprocessing | Free, light, runs on a CPU, runs offline | Weak on layout, scene text, handwriting | Clean scans, books, printed forms |
| Open-source deep learning | Better on scene text and varied fonts, runs offline | Heavier dependencies, slower on CPU | Photos, signs, labels |
| Hosted services | Layout, tables, handwriting; no model upkeep | Per-page cost, data leaves your systems | Business documents at moderate volume |
Decide with measurements
Do not choose by reputation. Use the same procedure each time:
- Collect 50 to 100 representative images, including the bad ones you expect in production.
- Type the correct text for each by hand. This is your ground truth.
- Run each candidate engine, with its best preprocessing, over the set.
- Compute CER per image with the
character_error_ratefunction from the evaluation chapter, and look at the distribution, not only the average. A mean CER of 0.05 can hide a handful of images at 0.60. - Compare cost, speed, and operational burden next to accuracy.
The accuracy you need depends on the use. Searching a document archive tolerates a CER of several percent, because a query only needs some words to match. Extracting invoice totals tolerates almost none, so there you need field validation and a human review path regardless of the engine.
Practical design rules
- Treat OCR output as untrusted input. Validate it like data from any other unreliable source.
- Route low-confidence results to review or a second engine instead of passing them downstream.
- Fix the image before you tune the engine. Better capture (lighting, focus, 300 DPI scans) usually beats any software step.
- Keep the preprocessing and engine settings in version control next to the labeled sample, so results are reproducible.
Exercise
A pipeline reads supplier invoices with Tesseract and reports a mean word confidence of 91 on one image, yet the total came out as "1,2O0.50" instead of "1,200.50". Why did the confidence check not catch this, and what two checks would?
Show answer
Mean confidence averages over every word on the page, so one wrong character in a single token barely moves it, and the engine can be confidently wrong about look-alike characters such as 0 and O. Two checks that would catch it: a format check that the amount matches a numeric pattern (for example digits, commas, and a decimal point only), which rejects the letter O, and a consistency check that the line items add up to the stated total. Either check can send the invoice to human review.
Exercise
You must extract text from photos of shop signs taken on phones, and the photos contain customer faces, so images cannot be sent outside your company. Using the decision flow in this chapter, which approach fits, and how would you justify the choice?
Show answer
Use a self-hosted deep-learning engine such as EasyOCR, PaddleOCR, or docTR. The images are photos with scene text, so they are not clean printed text and are poor candidates for Tesseract with global thresholding. The faces mean images cannot leave your systems, which rules out hosted services. To justify the choice, label 50 to 100 representative photos, run Tesseract and the self-hosted engine on them, and compare CER distributions.