Skip to chapter content
navan✳THE BUILD LABPYTHON / GUIDE
0/26 read
CHAPTER 22 / 26 · TIME AND MEDIA

Reading text from images.

Use OCR as a fallible text extractor, then validate the result.

BY NAVAN SAMI5 MIN READTHEORY FIRST
01 / THE BASICS

Start here.

Optical character recognition, or OCR, guesses text from an image. This is different from reading a normal text file: the input is pixels, not characters. The recognizer looks at shapes and estimates letters and words. Blur, shadows, rotation, and unfamiliar fonts can change its guess. A photograph of a receipt may look readable to a person while the program confuses 0 with O or merges two columns.

Pillow opens the image and provides pixel data. pytesseract is a Python wrapper that sends the image to the separately installed Tesseract engine. image_to_string returns a string of guessed text. strip removes whitespace at the edges but cannot fix a mistaken digit or name. The result is therefore a candidate for further interpretation, not a confirmed transcript.

The next layer depends on the purpose. A search feature can show the extracted words and let a person inspect the source image. A financial workflow must parse amounts and compare them with other evidence before acting. A PDF may already have an embedded text layer, which is usually preferable to OCR. Read the chapter as a chain from source image to guessed text to validated field, with uncertainty carried through each step.

02 / THE IDEA

Build the model.

Optical character recognition, or OCR, estimates which characters appear in an image. It is useful for scans, screenshots, and photographs that do not contain selectable text. Unlike reading a text file, OCR does not recover an exact original string. Blur, skew, handwriting, shadows, small fonts, and unusual layouts can all change the result.

Before running OCR, ask whether the source already has text. A PDF may contain an embedded text layer that a parser can extract more accurately. When only pixels exist, crop to the relevant region, use a readable resolution, and improve contrast carefully. Keep the original image so you can compare any cleaned version with the source.

03 / UNDER THE SURFACE

How it works.

An OCR engine typically has a recognition model and language settings. A Python wrapper such as pytesseract calls an installed Tesseract executable; installing only the wrapper does not install the engine. The recogniser may return text with unexpected spaces or line breaks, so normalise only what your task requires. Aggressive cleanup can erase real information.

Treat extracted text as untrusted input. If the goal is to read invoice totals, locate likely fields, parse numbers, and check arithmetic or other constraints. If the goal is search, retain page or image coordinates so a person can verify a match. High-impact fields such as amounts, dates, and identifiers need a human review or stronger validation before a program acts on them.

A useful workflow measures quality on representative samples. Record the original, extracted text, expected field values, and error cases. Improve the input or recognition settings only when the results show a pattern. One flawless demo image does not prove the pipeline works across real photographs or scans.

04 / A WORKED EXAMPLE

Read it line by line.

example.py
from PIL import Image
import pytesseract
image = Image.open('receipt.png')
text = pytesseract.image_to_string(image)
print(text.strip())

Pillow opens the image. pytesseract sends it to the installed Tesseract engine and returns a guessed string. strip removes surrounding whitespace, not recognition errors. This needs Pillow, pytesseract, and the separate Tesseract program configured on the machine; the output depends on the actual image.

05 / ANOTHER EXAMPLE

See the rule again.

example-2.py
from decimal import Decimal, InvalidOperation
raw = '12.50'
try:
    amount = Decimal(raw)
except InvalidOperation:
    raise ValueError('review the scanned amount')
if amount < 0:
    raise ValueError('amount cannot be negative')
print(amount)

The output is 12.50. Decimal avoids binary floating-point surprises for money. This only checks that the text is a nonnegative decimal; a person or another independent signal should still verify a critical amount against the image.

06 / REMEMBER THIS

A mistake to avoid.

Do not assume an OCR number is correct because it contains digits. A recogniser can confuse 0 with O or 1 with I. Parse and cross-check the field before using it in a payment or report.

Finished this chapter?
Built with curiosity. By Navan Sami. ↗Python · Understand the idea, then write the code.