Sub topic 1
Reading Text in Images with OCR
Prerequisites
This chapter assumes that you:
- Can install Python packages with pip.
- Know that a digital image is a grid of pixels with width, height, and color channels.
- Can run commands in a terminal.
What OCR does and where it is used
Optical character recognition (OCR) is the process of converting text in an image into machine-readable characters. The output is a plain string that a program can search, store, or validate.
OCR appears in many places:
- Scanning paper documents into searchable PDFs
- Reading receipts and invoices for expense tools
- Extracting license plates, shipping labels, and serial numbers
- Making photographed signs or menus accessible to screen readers
How an OCR pipeline works
An OCR pipeline usually has three stages:
- Detection finds where text sits in the image.
- Recognition turns each text region into characters.
- Output returns the text, often with positions and confidence scores.
caption: The OCR pipeline runs from the input image through preprocessing and detection to recognition and output. alt: A top-down flowchart with five boxes in sequence: input image, preprocessing, text detection, text recognition, and output text with confidence.
Extracting text with Tesseract and Python
Tesseract is an open-source OCR engine. The pytesseract package calls it from Python. You must install the Tesseract program separately, then run pip install pytesseract pillow.
from PIL import Image
import pytesseract
image = Image.open("scan.png")
text = pytesseract.image_to_string(image, lang="eng")
print(text)image_to_string runs detection and recognition in one call and returns the text as a string.
Exercise
Why does the code in this section open the image with Pillow before passing it to pytesseract?
Show answer
Pytesseract accepts a Pillow image object, and Pillow reads the image file into the pixel format that pytesseract expects.