Sub topic 3
Word boxes and confidence scores
This chapter assumes you can run Python, install packages with pip, and read an image as a pixel array. You should also have Tesseract installed and pytesseract available.
Reading word boxes
image_to_string returns only text. image_to_data returns one row per detected item, with its position (left, top, width, height) and a confidence score from 0 to 100.
import cv2
import pytesseract
from pytesseract import Output
image = cv2.imread("receipt.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
data = pytesseract.image_to_data(binary, output_type=Output.DICT)
for i, word in enumerate(data["text"]):
confidence = float(data["conf"][i])
if word.strip() and confidence >= 60:
print(word, confidence, (data["left"][i], data["top"][i]))Cleaning and validating output
OCR often confuses similar characters, such as "O" with "0" or "l" with "1". Check each field against the format you expect. A total should match a number pattern, and a date should parse. Flag values that fail the check for review instead of guessing a correction.
Measuring accuracy with character error rate
Character error rate (CER) is the edit distance between the OCR output and the true text, divided by the length of the true text. Edit distance counts the insertions, deletions, and substitutions needed to change one string into the other.
| Reference text | OCR output | Edits | CER |
|---|---|---|---|
| invoice 2024 | invo1ce 2O24 | 2 | 0.167 |
Deep-learning OCR and scene text
Tesseract works best on scanned pages with clean, horizontal text. Scene text, such as signs and product labels photographed at an angle, often breaks it. Deep-learning engines such as EasyOCR and PaddleOCR locate text regions with neural networks and handle rotated or curved text better, but they need more compute and a larger install.
Limitations and choosing the right tool
Tesseract is fast and free, and it suits documents. A deep-learning engine suits photos. Measure CER on a sample of your own images before you commit to either one.
Exercise
A word has the text "total" and a confidence of 45. Using the filter from this chapter (confidence at least 60), should you keep it?
Show answer
No. 45 is below 60, so the filter drops the word. Flag it for review or rescan the image.