Sub topic 3
Extracting Text with Tesseract and Python
This chapter assumes basic Python, familiarity with images as pixel arrays, and comfort installing packages and running terminal commands. You will use Tesseract, an open-source OCR engine, through pytesseract, a Python wrapper that sends images to the Tesseract program and returns its results.
Install the OCR tools
pytesseract is not the OCR engine itself. Install both the Python packages and the Tesseract program.
pip install pillow pytesseractInstall Tesseract with your operating system's package manager. For example:
# Debian or Ubuntu
sudo apt-get install tesseract-ocr
# macOS with Homebrew
brew install tesseractOn Windows, install Tesseract separately and add its installation directory to PATH. If Python cannot find the executable, set its location explicitly in your script:
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"Check that the command is available before debugging Python code:
tesseract --versionRun a first extraction
The simplest workflow loads an image, passes it to Tesseract, and prints the returned string.
from PIL import Image
import pytesseract
image = Image.open("scan.png")
text = pytesseract.image_to_string(image, lang="eng")
print(text)The lang="eng" argument selects Tesseract's English trained data. The image path is relative to the directory from which you run the script. Use an absolute path or construct a path with pathlib when your input files are stored elsewhere.
Tesseract returns a string, so line breaks and spacing are part of the result. They may not match the visual layout exactly. OCR works best when the text is large enough, focused, upright, and separated clearly from its background.
Improve a poor scan
A scan with shadows, gray paper, or uneven lighting may produce better results after preprocessing. Preprocessing changes the pixels before OCR. This example converts a receipt to grayscale and uses Otsu thresholding to create a black-and-white image.
import cv2
import pytesseract
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,
)
text = pytesseract.image_to_string(binary, config="--psm 6", lang="eng")
print(text)Otsu thresholding chooses a threshold from the image's pixel distribution. Pixels on one side become black and pixels on the other side become white. The method is useful when the foreground and background have reasonably different brightness values. It can make results worse when the image has strong shadows or a textured background.
--psm 6 is a Tesseract configuration option. It tells Tesseract to treat the input as one uniform block of text. Without an appropriate page segmentation mode, the engine may interpret a receipt, label, or paragraph using the wrong layout assumptions.
> callout note > Keep the original image. Compare OCR results after each preprocessing step instead of applying every filter at once. A filter that helps a faint scan can destroy punctuation or thin characters in another image.
Handle common errors
An empty result does not always mean that no text exists. Check these causes:
- The Tesseract executable is missing or is not on
PATH. - The image path is wrong, or
cv2.imreadreturnedNone. - The text is too small, blurred, rotated, or low contrast.
- The selected language data is unavailable.
- The page segmentation mode does not match the layout.
- The image contains handwriting, decorative fonts, or text in a photograph.
For a multilingual image, install the required trained data and pass language codes such as eng+fra. The order can influence which language model is preferred. Tesseract language codes depend on the installed data files, so verify the available languages with:
tesseract --list-langsWhen Tesseract cannot meet the image's needs, a deep-learning OCR engine may be a better choice. Such engines often handle curved text, varied fonts, natural scenes, and complex layouts more effectively, but they may require more memory, larger models, or a separate deployment setup.
Exercise
You have a clear photograph containing one short horizontal line of English text. Which Tesseract settings should you try first, and why?
Show answer
Use lang="eng" and try a single-line page segmentation mode such as --psm 7. The language setting selects English trained data, while the segmentation mode tells Tesseract not to search for a full page layout.