Sub topic 2
How an OCR Pipeline Works
Assume you know basic Python, can install packages with pip, understand images as pixel arrays, and can run commands in a terminal. This chapter focuses on the working model of optical character recognition (OCR), not on every Tesseract option.
OCR converts visible characters in an image into machine-readable text. A useful OCR pipeline has three main stages:
- Text detection finds where text appears.
- Text recognition identifies the characters inside each text region.
- Output generation returns text and, often, positions and confidence scores.
These stages are related but solve different problems. Detection answers “where is the text?” Recognition answers “what does this text say?”
The pipeline from pixels to text
An input image contains pixels, not letters. The OCR engine must first locate likely text regions. A region might be a paragraph, a line on a receipt, or a single word in a street photograph.
After detection, the engine analyzes each region. It separates characters or character shapes, compares them with patterns learned from training data, and produces a sequence of symbols. Modern engines usually use neural networks for this recognition step. Traditional engines may use a mixture of image processing and statistical models.
Finally, the engine combines the recognized regions in reading order. A simple document may produce one string. A more complex result can include each word’s coordinates, confidence, line number, and page number.
The stages are not always separate in the software. Some deep-learning OCR systems detect and recognize text together. The separation remains useful because it helps diagnose errors.
- Missing text regions usually indicate a detection or image-quality problem.
- Incorrect characters inside a found region usually indicate a recognition problem.
- Correct words in the wrong order usually indicate a layout or output problem.
A small end-to-end example
The following example asks Tesseract for word-level output. It shows the pipeline’s final product rather than implementing detection and recognition manually.
from pathlib import Path
import cv2
import pytesseract
from pytesseract import Output
image_path = Path("scan.png")
image = cv2.imread(str(image_path))
if image is None:
raise FileNotFoundError(f"Could not read {image_path}")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
data = pytesseract.image_to_data(
gray,
lang="eng",
config="--psm 6",
output_type=Output.DICT,
)
for index, text in enumerate(data["text"]):
text = text.strip()
if not text:
continue
left = data["left"][index]
top = data["top"][index]
width = data["width"][index]
height = data["height"][index]
confidence = float(data["conf"][index])
print({
"text": text,
"box": (left, top, width, height),
"confidence": confidence,
})The grayscale conversion is preprocessing. Tesseract then analyzes the page layout, finds text regions, recognizes words, and returns structured output. The box values use the image’s coordinate system. The origin is normally the upper-left corner, left increases to the right, and top increases downward.
The --psm 6 setting tells Tesseract to expect one uniform block of text. A different layout may need a different page segmentation mode. Choosing the wrong mode can make an otherwise clear image produce missing or scrambled text.
Why errors occur at different stages
OCR errors often have a visible pattern.
| Symptom | Likely stage | First thing to check |
|---|---|---|
| A whole line is absent | Detection or segmentation | Contrast, cropping, and layout mode |
| `0` is read as `O` | Recognition | Resolution, font, and language data |
| Words appear in the wrong order | Layout or output | Columns, reading order, and boxes |
| Many words have low confidence | Image or recognition | Blur, skew, noise, and thresholding |
A pipeline should preserve intermediate results when accuracy matters. Save the preprocessed image, detected regions, and raw OCR response. Without these artifacts, it is difficult to tell whether a later cleanup step hid an earlier failure.
Choosing the right level of output
Plain text is convenient for searching and copying. Structured output is better when the application must locate or validate text. For example, an invoice system can use word boxes to associate a number with the nearest label, then use confidence and format checks to decide whether human review is needed.
A practical pipeline therefore keeps both:
- the recognized text for users and downstream search;
- metadata such as boxes, confidence, page, line, and block identifiers.
This design also makes later preprocessing, layout handling, and evaluation easier.
Exercise
An OCR result contains the correct words, but the two columns are interleaved in the wrong order. Which stage is most likely responsible, and what evidence would you inspect?
Show answer
The layout or output stage is most likely responsible. Inspect the word bounding boxes, line and block identifiers, and the page segmentation setting to determine the intended reading order.