Sub topic 10
Measuring Accuracy with Character Error Rate
Earlier chapters showed how to run Tesseract and how preprocessing changes its output. This chapter covers how to tell whether a change helped. Character error rate (CER) turns "this looks better" into a number you can compare across images, settings and engines.
Prerequisites
This chapter assumes you can:
- Run Tesseract through pytesseract and apply grayscale and Otsu thresholding with OpenCV, as in the earlier chapters.
- Read basic Python, including loops, lists and functions.
- Use
pathlibor a similar tool to read text files from a folder.
Why you need a metric
OCR output is almost never perfectly right or perfectly wrong. A page can have 2,000 correct characters and 15 wrong ones. If you judge by eye, you will miss small regressions. A threshold that fixes one receipt may break ten others.
A metric needs three things:
- A reference, also called ground truth: the text a human confirmed is in the image.
- A hypothesis: the text the OCR engine returned.
- A distance between the two that counts how much editing it would take to turn one into the other.
CER is that distance, divided by the reference length so that long and short documents are comparable.
The definition
CER is built on the Levenshtein edit distance. This is the minimum number of single-character edits needed to turn one string into another. There are three kinds of edit:
| Edit | Meaning | Example |
|---|---|---|
| Substitution | One character is replaced by another | `1` read instead of `i` |
| Insertion | The engine added a character that is not in the reference | a stray `.` from a speck of dust |
| Deletion | The engine dropped a character that is in the reference | a thin `l` that vanished |
The formula is:
CER = (substitutions + insertions + deletions) / number of characters in the referenceThe numerator is the edit distance, since the minimum edit count is the total of those three kinds. The denominator is always the reference length, not the hypothesis length.
A worked example
The reference invoice 2024 has 12 characters. The OCR output invo1ce 2O24 differs in two places. The letter i became the digit 1, and the digit 0 became the capital letter O. That is two substitutions, so CER is 2 / 12, or about 0.167. This is the code from the plan:
def edit_distance(a, b):
previous = list(range(len(b) + 1))
for i, char_a in enumerate(a, start=1):
current = [i]
for j, char_b in enumerate(b, start=1):
cost = 0 if char_a == char_b else 1
current.append(min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost))
previous = current
return previous[-1]
def character_error_rate(reference, hypothesis):
return edit_distance(reference, hypothesis) / max(len(reference), 1)
print(character_error_rate("invoice 2024", "invo1ce 2O24"))It prints 0.16666666666666666. Many people report CER as a percentage, so you would say 16.7%.
How the edit distance works
The function uses dynamic programming. Conceptually there is a table where cell (i, j) holds the edit distance between the first i characters of a and the first j characters of b. The code keeps only one previous row at a time, so memory use is proportional to the length of b.
For each cell the code takes the cheapest of three options:
previous[j] + 1: deletechar_a.current[j - 1] + 1: insertchar_b.previous[j - 1] + cost: match the two characters (cost 0) or substitute one for the other (cost 1).
The last value of the final row is the distance for the full strings. The time cost is proportional to len(a) * len(b). That is fine for lines and pages. For book-length text, use a library such as rapidfuzz, which implements the same distance in compiled code.
Normalize before you compare
Raw OCR output often differs from a clean reference in ways you may not care about. Examples are trailing newlines, doubled spaces, or fi (one ligature character) versus fi. If you leave these in, CER measures formatting noise.
Decide on a normalization and apply it to both strings, every time:
import re
import unicodedata
def normalize(text):
text = unicodedata.normalize("NFKC", text)
return re.sub(r"\s+", " ", text).strip()
print(repr(normalize(" final total\n")))This prints 'final total'. NFKC folds ligatures and other look-alike forms into plain characters. Whitespace runs collapse to one space.
Be deliberate about what you do not normalize. Lowercasing hides case confusions like O versus o, which can matter for part numbers. Stripping punctuation hides errors in decimal points, and those turn 3.50 into 350. Match the normalization to what your application cares about, and keep it fixed so scores stay comparable over time.
Building a ground-truth set
CER is only as good as the references. A practical approach:
- Collect 20 to 50 images that represent real input: the same camera, scanner, lighting and document types you expect in production.
- Run OCR on them once. Correct the output by hand instead of typing from scratch. This is faster, but check each line against the image, because it is easy to accept an engine mistake.
- Save each reference next to its image:
receipt_01.jpgandreceipt_01.txt. - Keep these files fixed. Add new files over time, but do not edit old references to make the score look better.
Include difficult images on purpose. A set of only clean scans will give a CER near zero and will not tell you whether a change helps on bad inputs.
Scoring a whole set
You can average per-image CER, but short images then count as much as long ones. A better summary is corpus CER: the total edit distance across all images divided by the total reference length. The script below compares a grayscale baseline with Otsu thresholding. It assumes the edit_distance and normalize functions are defined in the same file.
from pathlib import Path
import cv2
import pytesseract
def to_gray(image):
return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
def to_otsu(image):
_, binary = cv2.threshold(to_gray(image), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return binary
def score(folder, prepare, config="--psm 6"):
total_distance = 0
total_length = 0
for image_path in sorted(Path(folder).glob("*.jpg")):
reference = normalize(image_path.with_suffix(".txt").read_text(encoding="utf-8"))
image = cv2.imread(str(image_path))
hypothesis = normalize(pytesseract.image_to_string(prepare(image), config=config))
distance = edit_distance(reference, hypothesis)
total_distance += distance
total_length += len(reference)
print(f"{image_path.name}: {distance / max(len(reference), 1):.3f}")
return total_distance / max(total_length, 1)
print("grayscale:", score("testset", to_gray))
print("otsu:", score("testset", to_otsu))Per-file lines show where the problems are. The final two numbers tell you which pipeline to keep. If Otsu wins overall but loses badly on two images, look at those two. Global thresholding often fails on unevenly lit photos, which is a hint to try adaptive thresholding.
What CER does not tell you
Word error rate
CER is forgiving of near misses. Word error rate (WER) uses the same edit distance on lists of words instead of characters. The function from this chapter works on lists too:
def word_error_rate(reference, hypothesis):
ref_words = reference.split()
return edit_distance(ref_words, hypothesis.split()) / max(len(ref_words), 1)
print(word_error_rate("invoice 2024", "invo1ce 2O24"))This prints 1.0. Both words contain an error, so both count as wrong, even though CER was only 0.167. Use CER when partial correctness matters (for example, search that tolerates fuzzy matching). Use WER when whole words must be right.
Field-level correctness
If you extract an invoice number, a single wrong digit makes the result useless, whatever the CER says. For structured extraction, also measure exact match per field: the share of fields where the normalized output equals the reference.
Reading order and layout
CER compares one long string. If a two-column page is read across both columns, the characters can all be correct but in the wrong order. The edit distance will be large. A high CER can therefore mean a wrong page segmentation mode rather than bad recognition. Check the output by eye before tuning preprocessing.
Edge cases
- Empty reference. Dividing by zero is avoided with
max(len(reference), 1). If the reference is empty and the engine output is not, the score equals the number of extra characters. Treat empty-reference images (pages that should yield nothing) as a separate check, such as "output is empty". - CER above 1. The score is not capped. A reference of
aband a hypothesis ofxxxxxxneeds 2 substitutions and 4 insertions, so CER is 6 / 2 = 3.0. Do not clip it silently, because it signals that the engine produced much more text than expected, often from noise or a border read as characters. - Case and accents.
ÉversusEcounts as one substitution. If your language uses combining accents, normalize to one Unicode form first, or the same visible character can differ in code points. - Small test sets. With a handful of images, one hard image can move the corpus CER by several points. Report the per-image spread too.
- Overfitting. If you tune thresholds against the same 30 images that you score on, the result is optimistic. Keep some images aside and score them only at the end.
Common errors
| Symptom | Likely cause |
|---|---|
| CER is slightly above 0 on a perfect read | Trailing newline or double spaces left in the text |
| CER jumps after a harmless change | Different normalization between runs |
| CER is very high but the text looks right | Wrong reading order, or Unicode forms differ |
| CER improves but fields still fail | Errors are concentrated in digits or key characters |
| Score differs from a library's score | The library normalizes or weights costs differently |
Summary
Compute CER as the edit distance between the normalized reference and the normalized OCR output, divided by the reference length. Fix the normalization, keep a stable ground-truth set that includes hard images, and report corpus CER with per-image detail. Add WER or exact field match when your application needs whole words or whole fields to be right.
Exercise
A reference line is total 45.60 (11 characters including the space). The OCR output is tota1 4560. What is the CER, and what edit operations produce it? Would stripping punctuation before comparing change the result?
Show answer
The output has two differences from the reference: l became 1 (one substitution) and the period was dropped (one deletion). Edit distance is 2, so CER is 2 / 11, about 0.182. If you strip punctuation from both strings first, the reference becomes total 4560 and only the substitution remains, so CER is 1 / 10 = 0.1. This is why normalization must be fixed in advance: here it would hide a decimal-point error that changes 45.60 into 4560.
Exercise
You compare two preprocessing pipelines on 30 images. Pipeline A has a mean per-image CER of 0.08 and pipeline B has 0.07. Corpus CER (total distance / total reference length) is 0.05 for A and 0.06 for B. Why might the two summaries disagree, and which should you trust for a document-level cost estimate?
Show answer
The mean per-image CER gives every image equal weight, while corpus CER weights each image by its length. B may do better on many short images and worse on a few long ones. For a cost estimate based on how many characters a person would have to fix, corpus CER is the better measure because it counts total errors against total text. Also check the per-image scores for the long documents before deciding.
Exercise
The character_error_rate function is called with reference ab and hypothesis xxxxxx. What does it return, and what does the value tell you?
Show answer
It returns 3.0, because the edit distance is 6 (2 substitutions and 4 insertions) and the reference length is 2. A CER above 1 means the engine produced far more text than the reference contains, which usually points to noise, borders or background texture being read as characters. It suggests fixing detection, cropping or preprocessing before tuning recognition.