Sub topic 8
Word boxes and confidence scores
This chapter assumes you can run Tesseract from Python through pytesseract, as shown earlier in the tutorial. It also assumes you know how to load an image with OpenCV and can read a NumPy pixel array. Here you will get more than a string from the engine. You will get where each word sits in the image and how sure the engine is about it.
Why plain text is not enough
image_to_string returns one string. That is fine for a quick look, but many tasks need more:
- Finding the amount next to the word "Total" on a receipt needs word positions.
- Rejecting a bad scan automatically needs a measure of how sure the engine was.
- Debugging a poor result is much easier when you can draw what the engine found on top of the image.
- Redacting or highlighting a phrase needs the pixel coordinates of that phrase.
Tesseract computes all of this while it recognizes text. The image_to_data function exposes it.
The structure Tesseract reports
Tesseract organizes a page as a tree. A page contains blocks, a block contains paragraphs, a paragraph contains lines, and a line contains words. image_to_data returns one row for every node in that tree, not only for words.
Each row carries these fields:
| Field | Meaning |
|---|---|
| `level` | Depth in the tree: 1 page, 2 block, 3 paragraph, 4 line, 5 word |
| `page_num`, `block_num`, `par_num`, `line_num`, `word_num` | Counters that identify the node's place in the tree |
| `left`, `top` | Pixel coordinates of the box's upper-left corner |
| `width`, `height` | Size of the box in pixels |
| `conf` | Confidence from 0 to 100, or -1 when the row is not a word |
| `text` | The recognized text, empty for rows above word level |
The origin is the top-left corner of the image. left grows to the right and top grows downward, the same convention as NumPy array indexing and OpenCV drawing.
Reading word data
With output_type=Output.DICT, the result is a dictionary of parallel lists. Index i in each list describes the same row. The next script keeps only real words with a confidence of at least 60.
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:
x, y = data["left"][i], data["top"][i]
w, h = data["width"][i], data["height"][i]
print(word, confidence, (x, y, w, h))Two details in this script matter:
- The
word.strip()test removes the page, block, paragraph, and line rows, whose text is empty. It also removes whitespace-only entries that Tesseract sometimes emits. float(...)makes the code work across pytesseract versions. Older releases returnedconfas an integer or a string. Newer ones return a float such as91.37.
Other output types exist. Output.STRING returns the raw TSV text, and Output.BYTES returns bytes. Output.DICT is the most convenient for code. If you prefer tables, pandas.DataFrame(data) turns the dictionary into one row per node.
What the confidence score means
conf is the engine's own estimate of how likely it is that a word was recognized correctly. It is derived from internal character-level scores, and it has limits you should know:
- It is not a calibrated probability. A score of 90 does not mean the word is right nine times out of ten. Treat it as a ranking: higher is more trustworthy than lower.
- It is the engine's opinion of itself. A clean, confidently wrong word can score high. A common case is a letter O read where a zero was printed, in a font where the two look alike.
- Scores depend on the engine version, the language data, and the preprocessing. A threshold tuned on one setup may not transfer to another.
- A value of -1 means the row is not a word. It does not mean "very low confidence".
- A word can score 0 when Tesseract recognized something but had no support for it. Treat 0 as a signal to inspect.
Tesseract also returns low scores for non-text image regions. A photo, a logo, or a table border can produce short junk "words" like | or —. Combining a confidence filter with a minimum word length or box size removes most of them.
Choosing a threshold
A threshold of 60, as in the example, is a starting point. The right value depends on the cost of each kind of mistake:
- A low threshold, such as 30, keeps more words and more noise. Use it when missing text is worse than keeping garbage, for example when a human reviews everything.
- A high threshold, such as 80, keeps fewer words and fewer errors. Use it when wrong data is costly, for example when text feeds a database.
- A middle path is a review queue. Accept words above a high threshold, discard words below a low one, and send the band between them to a person or a second check.
To pick values, label a small sample by hand. Run OCR, then compare the confidence of correct words with the confidence of wrong ones. Choose the cut where the two groups separate best. You will measure accuracy formally in the chapter on character error rate.
Drawing boxes to see what the engine saw
When results look wrong, draw the boxes. This shows whether the engine found the text at all, found it in the wrong place, or found it and misread it.
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 not word.strip() or confidence < 0:
continue
x, y = data["left"][i], data["top"][i]
w, h = data["width"][i], data["height"][i]
color = (0, 160, 0) if confidence >= 60 else (0, 0, 255)
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
cv2.putText(image, word, (x, max(y - 4, 12)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
cv2.imwrite("receipt_boxes.png", image)OpenCV stores colors in blue, green, red order. (0, 160, 0) is green and (0, 0, 255) is red. Confident words get green boxes and doubtful ones get red.
The boxes are drawn on the original color image, but the OCR ran on the binarized copy. This works only because thresholding does not change the image size. If your preprocessing resizes, crops, or rotates the image, the coordinates refer to the processed image. Draw on that image, or divide the coordinates by the scale factor to map them back.
Rebuilding lines and scoring them
The tree numbers let you regroup words into lines. A line is identified by the combination of page, block, paragraph, and line numbers. line_num alone repeats in every paragraph, so it is not enough as a key.
from collections import defaultdict
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)
lines = defaultdict(list)
for i, word in enumerate(data["text"]):
confidence = float(data["conf"][i])
if word.strip() and confidence >= 0:
key = (data["page_num"][i], data["block_num"][i],
data["par_num"][i], data["line_num"][i])
lines[key].append((data["left"][i], word, confidence))
for key in sorted(lines):
words = sorted(lines[key])
text = " ".join(word for _, word, _ in words)
mean_conf = sum(c for _, _, c in words) / len(words)
print(f"{mean_conf:5.1f} {text}")Printing a mean confidence per line is a cheap quality report. A line at 35 among lines at 90 stands out immediately. Sorting by left keeps words in reading order for left-to-right scripts. A single bad word can drag a short line's mean down, so for important fields consider the minimum confidence instead of the mean.
Using boxes for layout tasks
Positions let you answer questions that plain text cannot.
- Find a label and read its value. Locate the word "Total", then collect words whose vertical center falls within the same line band and whose
leftis greater than the label's right edge,left + width. - Crop a region. Slice the array with
image[y:y + h, x:x + w]and run OCR again on the crop with a more specific page segmentation mode. - Redact text. Fill the box with
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 0), -1). A thickness of -1 fills the rectangle. - Detect columns. Cluster words by their
leftvalues.
Boxes are tight around the glyphs, so expand them by a few pixels before cropping if you plan to re-run recognition on the crop. Characters touching the edge of a crop are often misread.
Common errors
- Every
confis -1. The engine found no words. Check that the image loaded (cv2.imreadreturnsNonefor a bad path) and that the text is dark on a light background. - Comparing
confto a number raises an error. Older versions return strings. Convert withfloat(). - Boxes are in the wrong place. The image was resized or rotated after OCR, or you drew on a different image than the one you recognized.
- Words missing from the output. A threshold that is too high is filtering them. Print everything with
conf >= 0first, then raise the cut. - Numbers and punctuation score low. Tesseract's language model is trained on words, so short tokens like
3.14or#A-17often get weaker scores than dictionary words. Use a per-field threshold, and validate numeric fields by format.
Summary
image_to_data returns one row per page, block, paragraph, line, and word. Each word row has a box in pixels and a confidence from 0 to 100. Filter on conf >= 0 plus non-empty text to get words, then apply a threshold chosen from real examples. Draw boxes to debug, and group by the four tree numbers to rebuild lines.
Exercise
You run imagetodata on a scanned invoice and want a list of words that need human review. Which rows should you examine, and what two conditions define a word that needs review? Also, why is grouping lines by line_num alone a bug?
Show answer
Examine only word rows: those with non-empty stripped text and conf of at least 0 (level 5). Rows for pages, blocks, paragraphs, and lines have empty text and conf of -1. A word needs review if its confidence falls below your chosen threshold (for example 60), or if it falls in a band between a low and high cut. Optionally also flag words that fail a format check. Grouping by linenum alone is a bug because linenum restarts at 1 in every paragraph, so lines from different paragraphs and blocks would be merged. Use the key (pagenum, blocknum, parnum, linenum).
Exercise
Your preprocessing step upscales the image by a factor of 2 before OCR. A word box comes back as left=200, top=100, width=80, height=30. What are its coordinates on the original image, and why does this matter when drawing boxes?
Show answer
Divide every value by 2: left=100, top=50, width=40, height=15. The box coordinates are in the pixel space of the image given to Tesseract, which is the upscaled one. If you draw them on the original image without scaling back, the boxes appear shifted and twice as large.