Sub topic 9
Cleaning and Validating OCR Output
Assume you know basic Python, can install packages with pip, and understand that an image is an array of pixels. This chapter focuses on what happens after an OCR engine returns text. The goal is to make that text useful without hiding recognition errors.
Why OCR output needs post-processing
OCR output often contains extra spaces, broken line endings, and character substitutions. For example, an engine might return TotaI: $12.50 when the image says Total: $12.50. The uppercase I is visually similar to a lowercase l.
Post-processing is the work of cleaning this result and checking whether it follows the rules you expect. It should not blindly “correct” every unusual character. A correction can make incorrect text look trustworthy.
A useful pipeline separates these stages:
Normalize without destroying evidence
Normalization makes predictable changes, such as converting Windows line endings to newlines or collapsing repeated spaces. Keep the original OCR result so you can inspect it later.
Common normalization operations include:
- Remove spaces at the start and end of each line.
- Convert repeated spaces to one space.
- Convert different newline styles to
\n. - Join lines only when the document format says that they belong together.
- Avoid changing letter case unless a field explicitly requires it.
A normalization rule should be specific to the document type. Joining every line can merge separate fields or table rows.
import re
def normalize_ocr_text(text: str) -> str:
"""Make safe, layout-preserving cleanup changes."""
text = text.replace("\r\n", "\n").replace("\r", "\n")
cleaned_lines = []
for line in text.split("\n"):
line = re.sub(r"[ \t]+", " ", line).strip()
cleaned_lines.append(line)
return "\n".join(cleaned_lines).strip()
def extract_invoice_fields(text: str) -> dict[str, str | None]:
"""Extract fields with patterns designed for this invoice format."""
invoice_match = re.search(
r"\bInvoice\s*(?:No\.?|Number)?\s*[:#]?\s*([A-Z0-9-]+)",
text,
flags=re.IGNORECASE,
)
total_match = re.search(
r"\bTotal\s*[:\-]?\s*\$?\s*([0-9,]+\.\d{2})",
text,
flags=re.IGNORECASE,
)
return {
"invoice_number": invoice_match.group(1) if invoice_match else None,
"total": total_match.group(1) if total_match else None,
}
def validate_invoice(fields: dict[str, str | None]) -> list[str]:
errors = []
invoice_number = fields.get("invoice_number")
if not invoice_number:
errors.append("missing invoice number")
elif not re.fullmatch(r"[A-Z0-9-]{3,20}", invoice_number, flags=re.IGNORECASE):
errors.append("invoice number has an unexpected format")
total = fields.get("total")
if not total:
errors.append("missing total")
else:
try:
amount = float(total.replace(",", ""))
if amount < 0:
errors.append("total cannot be negative")
except ValueError:
errors.append("total is not a number")
return errors
raw_text = """
Invoice No.: AB-1042
Total: $1,250.00
"""
normalized = normalize_ocr_text(raw_text)
fields = extract_invoice_fields(normalized)
errors = validate_invoice(fields)
print(fields)
print("valid" if not errors else f"review required: {errors}")The extraction patterns in this example are deliberately narrow. A pattern that accepts every possible string may produce a value for the wrong line. Adapt the pattern to the forms you actually process.
Validate against document rules
Validation checks whether extracted values make sense. It is different from OCR confidence. Confidence estimates how likely a recognized word is correct. Validation checks whether the value fits your application’s rules.
| Validation | Example | What it catches |
|---|---|---|
| Format | Invoice number matches `AB-1042` | Missing or extra characters |
| Range | Tax rate is between 0 and 100 | Misread decimal points |
| Relationship | Subtotal plus tax equals total | Incorrect numeric fields |
| Required field | Date is present | Missing recognition |
| Cross-check | ID exists in a known list | Plausible but false values |
Use multiple signals when deciding whether to accept a result. A high-confidence word can still be wrong, and a low-confidence word can be correct.
Handling uncertain results
Send a result for review when:
- A required field is missing.
- A value fails its format or range check.
- Related fields do not agree.
- Word confidence is below your chosen threshold.
- The image contains handwriting, unusual fonts, or overlapping text.
Do not use a fixed confidence threshold as the only decision rule. Choose thresholds by testing representative documents and measuring the cost of false acceptance versus manual review.
Exercise
Why should validation be performed after OCR extraction instead of relying only on the OCR engine's confidence score?
Show answer
Confidence describes the engine's recognition certainty, while validation checks whether the extracted value follows the document and application rules. Both signals are needed.