Sub topic 8
Word Boxes and Confidence Scores
This chapter assumes basic Python, pip, and familiarity with image pixels. You also need Tesseract installed on your system, plus the Python packages pytesseract and OpenCV:
pip install pytesseract opencv-pythonOCR output does not have to be one plain string. Tesseract can return information about each recognized word, including its location and confidence score. This structured output lets you highlight text, read selected regions, or reject uncertain results.
What a word box contains
A bounding box is a rectangle around a detected word. Its position uses four pixel values:
left: horizontal position of the box's left edgetop: vertical position of the box's top edgewidth: box widthheight: box height
The image origin is at the top-left corner. The x coordinate increases to the right, and the y coordinate increases downward.
Tesseract also returns a confidence score. The score usually ranges from 0 to 100, where a larger value means that the engine is more confident in its recognition. Confidence is not a guarantee that the word is correct. A plausible but incorrect word can still receive a high score.
image_to_data returns more than words. It also describes page, block, paragraph, line, and word levels. Only word rows normally contain useful text and word coordinates. Other rows may have an empty string and a confidence of -1.
| Field | Meaning | Typical use |
|---|---|---|
| `text` | Recognized text | Display or process the word |
| `conf` | Confidence score | Filter or flag uncertain words |
| `left`, `top` | Top-left position | Draw or locate the word |
| `width`, `height` | Box dimensions | Draw a rectangle |
Extracting boxes with Python
The following program loads an image, asks Tesseract for word-level data, and prints words whose confidence is at least 60.
import cv2
import pytesseract
from pytesseract import Output
image = cv2.imread("receipt.jpg")
if image is None:
raise FileNotFoundError("Could not read 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,
config="--psm 6",
output_type=Output.DICT,
)
minimum_confidence = 60
for i, word in enumerate(data["text"]):
word = word.strip()
confidence = float(data["conf"][i])
if not word or confidence < minimum_confidence:
continue
x = data["left"][i]
y = data["top"][i]
width = data["width"][i]
height = data["height"][i]
print(
f"{word!r} confidence={confidence:.1f} "
f"box=({x}, {y}, {width}, {height})"
)The index i is important. Each list in the returned dictionary describes the same row, so data["text"][i], data["conf"][i], and data["left"][i] belong to one result.
Drawing boxes for inspection
Visual inspection is often more useful than a printed list. Draw rectangles on a copy of the original image. Use the same row values that produced the text.
annotated = image.copy()
for i, word in enumerate(data["text"]):
word = word.strip()
confidence = float(data["conf"][i])
if not word or confidence < minimum_confidence:
continue
x = data["left"][i]
y = data["top"][i]
width = data["width"][i]
height = data["height"][i]
cv2.rectangle(
annotated,
(x, y),
(x + width, y + height),
(0, 255, 0),
2,
)
cv2.imwrite("receipt_boxes.png", annotated)The saved image shows whether boxes align with actual words. Misaligned boxes can reveal skew, incorrect page segmentation, or preprocessing that removed parts of letters.
Choosing a confidence threshold
A threshold of 60 is only a starting point. A lower threshold preserves more text but increases errors. A higher threshold produces cleaner output but may discard faint or small words. Choose the threshold using labeled samples from your actual documents.
For important fields, combine confidence with validation. A date should match an expected date pattern. A total should parse as a number. An invoice identifier should match its known format. A low-confidence value that passes validation may deserve review, while a high-confidence value that fails validation should also be checked.
Exercise
Why should a row with an empty text value or confidence -1 usually be skipped when collecting word boxes?
Show answer
Such rows describe layout levels such as a page, block, paragraph, or line rather than a recognized word. They do not provide a usable word result.