Sub topic 2
How an OCR Pipeline Works
This chapter explains the stages an OCR engine runs between a raw image and a string of text. It assumes you can write basic Python, that you know an image is an array of pixels with a width, a height, and color channels, and that you can run commands in a terminal. The previous chapter covered what OCR produces. This one covers how it gets there, so that later chapters on preprocessing, page segmentation, and confidence scores make sense.
The pipeline at a glance
An OCR engine does not look at a page and read it the way a person does. It turns the problem into a chain of smaller steps. Each step takes the output of the one before it and narrows the problem.
- Preparation. The engine cleans the image and converts it into a form that is easy to analyze, usually a grayscale or black-and-white array.
- Detection. The engine finds where text is: blocks, lines, words, and sometimes single characters.
- Recognition. The engine decides which characters each located region contains.
- Output. The engine assembles the characters into words and lines and returns them as plain text, or as text with positions and confidence scores.
Errors flow forward through this chain. If detection misses a line, recognition never sees it. If preparation destroys thin strokes, recognition cannot recover them. This is why most practical OCR work is spent on the early stages and not on the recognizer.
Stage 1: Preparation
Preparation turns the input into something the later stages can handle. Typical operations are:
- Grayscale conversion. Color carries little information about letter shapes, so the engine reduces three channels to one.
- Binarization. The engine decides for each pixel whether it is ink or background, producing a black-and-white image. Tesseract does this internally even if you do not, but it often does better when you supply a cleaner binary image yourself.
- Noise removal. Specks, scanner dust, and compression artifacts can look like punctuation.
- Deskewing. If the page was scanned at a slight angle, text lines are tilted. Most engines assume lines are close to horizontal, so a tilt of a few degrees can already lower accuracy.
Engines vary in how much of this they do for you. Tesseract performs its own binarization, and newer versions use an internal method that handles uneven lighting reasonably well. It still does not fix heavy blur, strong shadows, or large rotations. Chapter 5 covers these operations in practice. Here the point is that preparation is part of the pipeline, whether you write it or the engine does.
Stage 2: Detection
Detection answers the question "where is the text?" It does not read anything. Its output is a set of regions.
Classic engines such as Tesseract use a layout analysis approach built from several steps:
- Find connected components, which are groups of touching ink pixels. A letter like "o" is one component. A letter like "i" is two.
- Group components that sit close together on a horizontal baseline into lines.
- Group lines into blocks such as paragraphs, columns, or table cells.
- Split lines into words using the gaps between components.
This works well on clean documents with clear structure. It struggles when ink touches non-text content such as a table border, a photo edge, or a stamp, because those pixels join the same connected components as letters.
Deep-learning detectors take a different route. They are neural networks trained to predict text regions directly from the image, often as rotated rectangles or polygons. They cope better with curved text, mixed orientations, and cluttered backgrounds, such as signs and product labels. Chapter 11 returns to these engines.
Reading order
Detection also has to decide in which order the regions should be read. On a single-column page the answer is top to bottom. On a two-column article, a naive top-to-bottom, left-to-right sweep would read across both columns and produce nonsense. Layout analysis therefore tries to identify columns before it orders lines. When it guesses wrong, each word is recognized correctly but the text comes out scrambled. Chapter 6 shows how page segmentation modes let you tell the engine what layout to expect.
Stage 3: Recognition
Recognition takes each detected line or word image and decides what characters it contains. There are two broad designs.
Character-by-character classification. Older engines split a word into individual glyph images, then classify each one by comparing its features to stored shapes. This breaks down when characters touch, as in tightly set or low-resolution text ("rn" often looks like "m"), because the split is itself a guess.
Sequence recognition. Modern engines, including Tesseract 4 and later, read a whole line image as a sequence. A neural network, typically using LSTM (long short-term memory) layers, slides across the line and at each horizontal position predicts which character is likely there. The model then combines those predictions into the most probable string. Because the network sees context, it can handle touching characters and uses neighbouring letters to resolve ambiguous shapes.
Sequence recognizers also depend on a language model or character set. If the engine has been trained for English, it will lean toward English letter patterns, which helps with a smudged "e" but hurts with serial numbers or foreign names that do not look like English. This is one reason language selection matters (Chapter 7).
Where confidence comes from
For each recognized symbol, the network produces a probability across the candidate characters. The engine reports a score derived from that, usually on a 0 to 100 scale for Tesseract. A confidence of 95 on a word means the model found one candidate clearly more likely than the others. A confidence of 40 means the candidates were close or the shapes matched poorly. Confidence is not a measured probability of being correct. It is a model's own estimate, and it can be confidently wrong, especially on clean-looking but unfamiliar characters. Chapter 8 shows how to read these scores.
Stage 4: Output
The final stage assembles recognized characters into a result. The same recognition run can be reported at different levels of detail:
| Output form | Contains | Typical use |
|---|---|---|
| Plain text | Characters and line breaks | Search indexing, quick reading |
| Word data | Each word with box coordinates and confidence | Filtering weak words, highlighting, redaction |
| Layout formats such as hOCR or ALTO XML | Page, block, line, and word hierarchy with positions | Building searchable documents |
| Searchable PDF | The original image with an invisible text layer | Archiving scans so they can be searched and copied |
Plain text is the simplest and throws away the most information. If you later need to know where a word was, or whether the engine trusted it, you must request the richer form from the start. You cannot reconstruct positions from a text string.
Following one image through the pipeline
Consider a photographed receipt. The following table shows what each stage does and how it can fail.
| Stage | What happens | Typical failure on a receipt |
|---|---|---|
| Preparation | Convert to grayscale, binarize | Shadow across one side turns half the page black |
| Detection | Find line and word boxes | A dashed separator line is treated as text |
| Recognition | Read each line | Thin thermal print fades, so "8" reads as "3" |
| Output | Assemble text with boxes | Prices end up on different lines from item names |
The last row is worth noting. A receipt has two columns, item name on the left and price on the right, with a wide gap. Line grouping may split each row into two pieces and read all the names before all the prices. The characters are right, yet the result is wrong for your purpose.
Seeing the stages in code
You can observe each stage by asking Tesseract for structured output. The program below runs the whole pipeline on one image. It then groups the result by the hierarchy that detection built: blocks, paragraphs, lines, and words. It requires the Tesseract program, plus the pytesseract and opencv-python packages.
import cv2
import pytesseract
from pytesseract import Output
image = cv2.imread("receipt.jpg")
if image is None:
raise FileNotFoundError("receipt.jpg not found")
# Preparation: grayscale, then Otsu binarization.
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Detection and recognition happen inside this call.
data = pytesseract.image_to_data(binary, output_type=Output.DICT)
# Output: group words by the line that detection assigned them to.
lines = {}
for i, word in enumerate(data["text"]):
if not word.strip():
continue
key = (data["block_num"][i], data["par_num"][i], data["line_num"][i])
lines.setdefault(key, []).append((word, float(data["conf"][i])))
for (block, par, line), words in sorted(lines.items()):
text = " ".join(w for w, _ in words)
avg = sum(c for _, c in words) / len(words)
print(f"block {block} par {par} line {line}: {text!r} (mean confidence {avg:.0f})")Each key in lines is a position in the hierarchy that the detection stage produced. If two halves of a receipt row end up under different line numbers or different block numbers, you have found a layout problem and not a recognition problem. Printing this view is a quick way to decide where to look first when results are wrong.
Diagnosing which stage failed
When OCR output is wrong, the useful question is which stage caused it. The symptom usually points to the answer.
- Entire regions missing. Detection failed, or preparation erased the text (for example, binarization turned light gray text white).
- Text present but scrambled in order. Layout analysis and reading order. Try a different page segmentation mode.
- Right layout, wrong letters. Recognition. Common causes are low resolution, blur, an unusual font, or the wrong language data.
- Many junk symbols from non-text areas. Detection treated borders, textures, or images as text. Crop to the text area or clean the image.
- Correct text but unusable structure. Output stage. Request word-level or layout output and rebuild the structure yourself.
Classic and deep-learning pipelines compared
The four stages exist in every OCR system, but the implementations differ in how the stages connect.
| Aspect | Classic layout analysis plus recognizer | Deep-learning detector plus recognizer |
|---|---|---|
| Detection method | Connected components and rules | Trained network predicting regions |
| Best input | Clean scanned documents | Photos, signs, curved or rotated text |
| Failure on clutter | Treats non-text as text | Usually better, but can miss rare styles |
| Configuration | Modes and parameters you set | Mostly fixed by the trained model |
| Cost | Runs on a CPU quickly | Often needs more memory, benefits from a GPU |
Some modern systems merge detection and recognition into a single network, but the logical stages remain, and you can still diagnose problems with the same questions.
Key points to carry forward
- OCR runs as a chain: preparation, detection, recognition, output. Errors in an early stage cannot be fixed later.
- Detection finds regions and decides reading order. Recognition reads characters. They fail in different ways.
- Confidence is the model's estimate and not a guarantee.
- Plain text discards positions and scores. Ask for richer output when you will need them.
- Naming the failing stage tells you which fix to try, which the next chapters cover in turn.
Exercise
A scan of a two-column magazine page gives you text where every sentence is spelled correctly, but each line mixes words from the left and right columns. Which pipeline stage is the most likely cause, and what would you change first?
Show answer
The cause is the detection stage, specifically layout analysis and reading order. Recognition is fine because the words are spelled correctly. The engine treated the page as a single wide column and grouped words across the gap between columns. Change the page segmentation mode to one that expects multiple columns or separate blocks of text (for example, Tesseract's automatic mode with orientation detection, or crop each column and process it separately), then check the line and block numbers in image_to_data output to confirm the columns are separate blocks.
Exercise
You call pytesseract.image_to_string on an invoice and later need to draw a box around every amount that has a confidence below 70. Why can't you do this with the string you already have, and which function should you have called?
Show answer
A plain string contains only characters and line breaks. It carries no coordinates and no confidence scores, and those cannot be recovered from the text. You should have called pytesseract.image_to_data with output_type=Output.DICT, which returns each word with its left, top, width, height, and conf values, so you can filter by confidence and draw the boxes.