Sub topic 10
Measuring OCR Accuracy with Character Error Rate
Prerequisites and the basic idea
This chapter assumes that you can run Python programs, install packages with pip, and represent OCR output as a string. It also assumes that you understand that OCR errors come from comparing an image's true text with the text predicted by an OCR engine.
Character error rate, or CER, measures how many character-level edits are needed to change OCR output into the correct text. It is useful when individual characters matter, such as invoice numbers, serial codes, dates, and short labels.
CER uses three edit operations:
| Operation | Meaning | Example |
|---|---|---|
| Substitution | One character is changed to another | `0` becomes `O` |
| Insertion | An extra character appears | `cat` becomes `cart` |
| Deletion | A character is missing | `cart` becomes `cat` |
The edit count is called the Levenshtein distance. CER divides that count by the number of characters in the reference text:
CER = edit distance / reference character count
A CER of 0 means the strings match exactly. A CER of 0.10 means the edit distance is 10% of the reference length. Lower is better.
Aligning reference and OCR text
Suppose the correct text is invoice 2024 and OCR produces invo1ce 2O24. Two substitutions are needed:
cbecame10becameO
The reference contains 12 characters, including the space. Therefore, the CER is 2 / 12, or about 0.167.
The following implementation calculates edit distance with dynamic programming. It stores the best distance for every pair of prefixes.
def edit_distance(reference, hypothesis):
previous = list(range(len(hypothesis) + 1))
for i, ref_char in enumerate(reference, start=1):
current = [i]
for j, hyp_char in enumerate(hypothesis, start=1):
substitution_cost = 0 if ref_char == hyp_char else 1
current.append(
min(
previous[j] + 1, # deletion
current[j - 1] + 1, # insertion
previous[j - 1] + substitution_cost,
)
)
previous = current
return previous[-1]
def character_error_rate(reference, hypothesis):
if not reference:
return 0.0 if not hypothesis else 1.0
return edit_distance(reference, hypothesis) / len(reference)
reference = "invoice 2024"
ocr_text = "invo1ce 2O24"
distance = edit_distance(reference, ocr_text)
cer = character_error_rate(reference, ocr_text)
print(f"Edit distance: {distance}")
print(f"CER: {cer:.3f}")The output is:
Edit distance: 2
CER: 0.167Normalize before measuring
The comparison rules must match the task. OCR may differ from the reference only because of formatting:
- line endings may differ
- multiple spaces may replace one space
- uppercase and lowercase may vary
- Unicode characters may have different representations
You can normalize both strings before calculating CER. For example, this version compares lowercase text and collapses runs of whitespace:
import re
import unicodedata
def normalize(text):
text = unicodedata.normalize("NFKC", text)
text = text.lower()
return re.sub(r"\s+", " ", text).strip()
reference = normalize("Total:\n$ 24.00")
hypothesis = normalize("total: $ 24.00")
print(character_error_rate(reference, hypothesis))Do not normalize away meaningful differences. If capitalization, spaces, or punctuation carry meaning in your application, preserve them. A serial number such as AB-10 should not be treated as equivalent to ab10 unless your validation rules explicitly allow that change.
Interpreting results
Measure a representative test set rather than one convenient image. Keep the reference text separate from the OCR output, and report the total edit distance and total reference characters:
corpus CER = total edits / total reference characters
This gives long samples appropriate weight and is usually more stable than averaging each image's CER. Also report results by document type, image quality, language, and field. A receipt with a clear total may perform differently from a receipt with a skewed item list.
Common failure cases
CER can mislead when:
- the reference has an incorrect transcription
- text order is wrong because columns were read incorrectly
- OCR inserts line breaks that your comparison treats as characters
- the text contains symbols or languages unsupported by the evaluation setup
- an empty reference or empty OCR result is handled inconsistently
For structured documents, combine CER with field-level checks. Parse dates, totals, or identifiers and compare those values directly. Confidence scores and bounding boxes can also help you send uncertain regions for review.
When another metric helps
Word error rate, or WER, counts word-level insertions, deletions, and substitutions. WER is often easier to interpret for paragraphs. CER is more sensitive to small spelling changes and is better for short codes or languages where word boundaries are unclear. Use both when your system reads ordinary prose and important identifiers.
Exercise
The reference is ABC123 and OCR returns ABC12. What is the CER, and which edit occurred?
Show answer
The CER is 1/6, or about 0.167. One deletion occurred because the final 3 is missing.