Sub topic 3
Extracting text with Tesseract and Python
This chapter shows how to run Tesseract from Python and read its output. It assumes you can use pip and a terminal, and that you know an image is an array of pixels with a width, a height, and color channels. The earlier chapters described the OCR pipeline: detection, recognition, and output. Here you run that pipeline with a real engine.
What Tesseract and pytesseract are
Tesseract is an open-source OCR engine, a standalone program written in C++. It reads an image, finds lines and words, recognizes the characters, and returns text. Recent versions (4 and later) use a neural network based on LSTM (long short-term memory) layers to recognize each text line.
pytesseract is a thin Python wrapper. It does not contain OCR code. When you call it, it writes your image to a temporary file, starts the tesseract program as a subprocess, and reads the result back. This has two practical consequences:
- You must install the Tesseract program separately from the Python package. Installing only pytesseract gives you a
TesseractNotFoundErrorwhen you first call it. - Every call starts a new process. Calling it in a tight loop over thousands of small crops is slow.
Installing
Install the engine first, then the Python packages.
| System | Command |
|---|---|
| Ubuntu or Debian | `sudo apt install tesseract-ocr` |
| macOS (Homebrew) | `brew install tesseract` |
| Windows | Use an installer such as the UB Mannheim build, then add its folder to `PATH` |
Then install the Python side:
pip install pytesseract pillow opencv-pythonCheck that the engine is found:
tesseract --version
tesseract --list-langsThe second command lists the installed trained data files. A fresh install normally shows eng and osd. If Python cannot find the program on Windows, set the path in code:
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"The simplest call
The first example loads an image with Pillow and asks for plain text.
from PIL import Image
import pytesseract
image = Image.open("scan.png")
text = pytesseract.image_to_string(image, lang="eng")
print(text)image_to_string returns one Python string. Lines are separated by newlines, and Tesseract usually adds a trailing newline and sometimes a form-feed character (\f) at the end of a page. Call .strip() if you compare the result with expected text.
lang="eng" names the trained data file to use. Chapter 7 covers language selection in more detail. For now, note that eng is the default, so the argument here only makes the choice explicit.
How the call flows
The diagram shows what happens between your code and the engine.
Image types pytesseract accepts
pytesseract accepts a Pillow image, a NumPy array, or a file path. This matters because OpenCV and Pillow store color channels in different orders.
- Pillow images use RGB order.
- OpenCV's
cv2.imreadreturns BGR order.
For recognition on a color image, the swapped channels usually do not change the text result much, because Tesseract converts to grayscale internally. They do matter if you save or display the image, so convert with cv2.cvtColor(image, cv2.COLOR_BGR2RGB) when mixing the libraries.
A common error is passing None. cv2.imread does not raise an exception for a missing file. It returns None, and the failure appears later as a confusing error inside pytesseract. Check it right away:
import cv2
image = cv2.imread("receipt.jpg")
if image is None:
raise FileNotFoundError("receipt.jpg could not be read")Adding preprocessing
A raw photo of a receipt rarely gives good text. The next example converts to grayscale and applies Otsu thresholding. Otsu's method chooses a threshold automatically by finding the value that best separates dark and light pixel groups. The result is a pure black-and-white image. Chapter 5 explains why this helps and when it hurts.
import cv2
import pytesseract
image = cv2.imread("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")
print(text)Three details are worth reading closely:
cv2.thresholdreturns two values: the threshold it chose and the image. The code keeps only the image and discards the number with_.- The threshold argument is
0because Otsu computes its own value and ignores it. config="--psm 6"passes a command-line option straight to Tesseract.
The config string
The config argument is a string of command-line options for the tesseract program. You can combine several, separated by spaces.
| Option | Meaning |
|---|---|
| `--psm N` | Page segmentation mode, a number from 0 to 13 |
| `--oem N` | Engine mode: 0 legacy, 1 LSTM, 2 both, 3 default |
| `-c name=value` | Set an internal variable |
| `--dpi N` | Tell Tesseract the image resolution |
Page segmentation mode (PSM) tells Tesseract what layout to expect. Mode 6 means "assume a single uniform block of text". That fits a cropped receipt or a paragraph. It fits poorly on a page with columns or a table, where Tesseract could treat separate columns as one block and mix lines together. Chapter 6 covers the other modes.
A useful variable is the character whitelist, which restricts output to the characters you list:
import pytesseract
digits = pytesseract.image_to_string(
"serial.png",
config="--psm 7 -c tessedit_char_whitelist=0123456789",
)
print(digits.strip())Mode 7 treats the image as a single line of text. A whitelist works well for fields with a known alphabet, such as serial numbers. Be aware that in Tesseract 4 and later with the LSTM engine, whitelist support has been inconsistent across versions. Test it on your installed version, and validate the output afterward instead of trusting it.
Getting more than text
image_to_string throws away position and certainty. For most real tasks you also want to know where each word is and how sure the engine is. pytesseract offers several functions:
| Function | Returns |
|---|---|
| `image_to_string` | Plain text |
| `image_to_data` | Word-level table with boxes and confidence |
| `image_to_boxes` | Character-level boxes |
| `image_to_osd` | Orientation and script detection |
| `image_to_pdf_or_hocr` | Searchable PDF or hOCR output |
The most useful is image_to_data. Chapter 8 treats it in depth, but here is a complete example so you can see its shape.
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))With Output.DICT, you get a dictionary of parallel lists. Index i in each list describes the same item. The keys include text, conf, left, top, width, and height, plus level, block_num, par_num, line_num, and word_num, which locate each word in the page structure.
Notice how the code handles two traps:
- Tesseract returns rows for pages, blocks, paragraphs, and lines as well as words. Those rows have empty
text, soword.strip()removes them. - The confidence is
-1for non-word rows. In some pytesseract versions the value is a string, so the code converts it withfloat. The testconfidence >= 60then also drops the-1entries.
A confidence of 60 is a starting point, not a rule. Confidence is the engine's own estimate and is not a calibrated probability. Pick your cutoff by comparing against known text.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| `TesseractNotFoundError` | Engine not installed or not on `PATH` | Install it, or set `tesseract_cmd` |
| `Failed loading language 'xxx'` | Missing trained data | Install the language pack, or check `TESSDATA_PREFIX` |
| Empty string | Text too small, very low contrast, or wrong PSM | Enlarge the image, preprocess, try another PSM |
| Garbled output on a clean image | Wrong PSM for the layout | Try `--psm 4`, `6`, or `11` |
| Letters swapped with digits (`O` and `0`, `l` and `1`) | Ambiguous shapes, no context | Use a whitelist or validate afterward |
| `cv2.error` on a valid-looking path | `imread` returned `None` | Check the path and file format |
| Very slow on large batches | One subprocess per call | Run calls in parallel with a process pool |
The last row deserves a note. Because each call is its own process, parallelism works well. A concurrent.futures.ProcessPoolExecutor or ThreadPoolExecutor can run several recognitions at once, since the heavy work happens outside Python. Tesseract itself may use multiple threads through OpenMP, which can slow things down when you also run many calls at once. Setting the environment variable OMP_THREAD_LIMIT=1 before launching often gives better throughput for batch jobs.
A reusable function
The pieces above combine into one small function that you can reuse in later chapters.
import cv2
import pytesseract
def read_text(path, psm=6, lang="eng"):
image = cv2.imread(path)
if image is None:
raise FileNotFoundError(f"Could not read image: {path}")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
config = f"--psm {int(psm)}"
return pytesseract.image_to_string(binary, lang=lang, config=config).strip()
if __name__ == "__main__":
print(read_text("receipt.jpg"))The int(psm) call guards the config string: only a number can enter it.
Edge cases to expect
- Inverted text. Light text on a dark background often reads poorly. Invert the binary image with
cv2.bitwise_notand compare. - Tiny text. Tesseract works best when capital letters are roughly 20 to 30 pixels tall. A small image should be enlarged first.
- Rotated pages. A page rotated by 90 degrees may produce nonsense.
image_to_osdreports the detected rotation, and chapter 5 covers deskewing for small tilts. - Mixed content. Photos, logos, and tables inside a page add junk lines. Cropping to the text region helps more than any setting.
- Handwriting. Tesseract is trained on printed text. Handwriting gives poor results whatever the settings.
Exercise
A script calls pytesseract.imagetostring on an image loaded with cv2.imread("invoice.png") and fails with a confusing error from inside the library, although the program runs without error up to that line. What is the most likely cause, and how do you guard against it? Then name one reason why a call to pytesseract in a loop over 5,000 images could be slow, and one way to speed it up.
Show answer
cv2.imread returns None instead of raising an exception when the file is missing or unreadable, so the None value is passed on to pytesseract. Guard against it with a check such as if image is None: raise FileNotFoundError(...) right after loading. Each pytesseract call starts a separate tesseract subprocess, which adds start-up cost. Speed it up by running calls in parallel with a process or thread pool, optionally setting OMPTHREADLIMIT=1 so Tesseract's own threads do not compete with your workers.
Exercise
In the imagetodata example, why does the loop test both word.strip() and confidence >= 60?
Show answer
imagetodata returns rows for pages, blocks, paragraphs, and lines as well as words. Those rows have empty text and a confidence of -1. The word.strip() test removes the empty-text rows, and the confidence test removes both the -1 rows and real words the engine is unsure about.