Sub topic 6
Choosing a Page Segmentation Mode
This chapter assumes you can run Tesseract from Python with pytesseract, as in the earlier chapter on running an engine. It also assumes you know how to preprocess an image to grayscale and a binary version. Here you will learn what a page segmentation mode (PSM) controls, how to pick one, and how to check that your choice helped.
What a page segmentation mode does
Before Tesseract recognizes any characters, it decides which regions of the image contain text and in what order to read them. This is layout analysis. A page segmentation mode tells the engine what layout to expect, so it can skip guessing.
The default mode, 3, assumes a full page that may contain several columns, headings, and possibly images. That assumption is wrong for many real inputs:
- A cropped photo of a single line, such as a serial number.
- A receipt, which is one narrow column.
- A screenshot with labels scattered around.
When the assumption is wrong, Tesseract may split one line into fragments, merge two columns into one run of text, or return an empty string because it found no text block at all.
A PSM does not change how individual characters are recognized. It changes which regions are handed to the recognizer, and how they are cut into lines and words.
The modes
You select a mode with the --psm option in the config string. The table lists the modes in Tesseract 4 and 5.
| PSM | Meaning | Typical use |
|---|---|---|
| 0 | Orientation and script detection only, no OCR | Finding out whether a page is rotated |
| 1 | Automatic segmentation with orientation and script detection | Mixed pages of unknown rotation |
| 2 | Automatic segmentation, no OSD or OCR | Not implemented |
| 3 | Fully automatic segmentation, no OSD (default) | Clean full pages with columns |
| 4 | One column of text of variable sizes | Receipts, forms, single-column articles |
| 5 | One uniform block of vertically aligned text | Vertical text |
| 6 | One uniform block of text | A paragraph or a tidy table region |
| 7 | One text line | Cropped lines, license-plate style strips |
| 8 | One word | Cropped single words |
| 9 | One word in a circle | Stamps, seals |
| 10 | One character | Single glyphs, digits in boxes |
| 11 | Sparse text, find as much as possible in any order | Screenshots, diagrams, labels |
| 12 | Sparse text with OSD | Sparse text with unknown rotation |
| 13 | Raw line, bypassing Tesseract's line-specific hacks | Lines the normal line mode mishandles |
"OSD" means orientation and script detection. It estimates the page rotation (0, 90, 180, or 270 degrees) and the writing system.
In practice you will use about five of these: 3, 4, 6, 7, and 11. The others are for narrow cases.
Matching the mode to the layout
Choose the mode by looking at the image, from the most constrained description that is true to the least.
- If the image is one character, use 10. If it is one word, use 8. If it is one line, use 7. These modes skip layout analysis, so there is little to go wrong, but they fail badly if the crop actually contains more than you declared. A two-line crop in mode 7 usually loses or garbles the second line.
- If the image is a block of text with consistent font size and spacing, use 6.
- If the image is a single column whose line heights vary, use 4. A receipt is the standard case: a large store name, small item lines, and a bold total.
- If the image is a full page with multiple columns, use 3.
- If the text is scattered with no reading order, such as a UI screenshot, a chart, or a product photo with labels, use 11.
The diagram turns this into a decision path.
Setting the mode in code
The mode goes into the config string. This is the same call used in the preprocessing chapter, with the mode as the only variable.
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 4")
print(text)You can combine options in one string, separated by spaces, for example --psm 7 --oem 1. The --oem option selects the engine: 1 is the LSTM neural network engine, which is the one you want unless you have a reason to use the legacy engine.
Comparing modes on your own image
The table tells you where to start. Your images decide the final answer. A small experiment that runs several modes and reports a confidence summary is cheap and often settles the question.
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)
for psm in (3, 4, 6, 11):
data = pytesseract.image_to_data(
binary, config=f"--psm {psm}", output_type=Output.DICT
)
words = [
(word, float(conf))
for word, conf in zip(data["text"], data["conf"])
if word.strip() and float(conf) >= 0
]
if words:
mean_conf = sum(conf for _, conf in words) / len(words)
else:
mean_conf = 0.0
print(f"psm={psm:2d} words={len(words):3d} mean_conf={mean_conf:5.1f}")Entries with a confidence of -1 are layout elements such as blocks and lines, not words, so the filter drops them. Empty strings are dropped as well.
Read the output with care:
- A mode that finds many more words is not necessarily better. Mode 11 often returns more words because it accepts fragments, including noise.
- A higher mean confidence can come from a mode that found fewer, easier words and ignored the hard ones.
- The reliable check is a ground-truth transcription and the character error rate from the evaluation chapter. Use confidence to shortlist modes, then use error rate to decide.
Detecting rotation with OSD
Modes 0, 1, and 12 use orientation and script detection. Mode 0 does no recognition. It reports how the page is rotated, and pytesseract exposes it through image_to_osd.
import re
import cv2
import pytesseract
image = cv2.imread("scan.png")
osd = pytesseract.image_to_osd(image)
print(osd)
angle = int(re.search(r"Rotate: (\d+)", osd).group(1))
print("Rotate by", angle, "degrees")The "Rotate" value is the clockwise rotation you must apply to the image to make the text upright. OSD needs the osd.traineddata file, which is missing from some minimal installs. It also needs enough text to work with. On a nearly empty image, or one with only a few characters, image_to_osd raises a TesseractError. Wrap the call in try and except pytesseract.TesseractError if you process unattended batches.
OSD detects page orientation in 90-degree steps. It does not measure small skew. For a page tilted by a few degrees, use the deskewing step from the preprocessing chapter.
Common failure patterns
These symptoms point to a layout mismatch, not a recognition problem.
- Empty output on a small crop. Mode 3 may not find a text block in a tight crop with little margin. Try 7 or 8, or add a border of white pixels around the crop with
cv2.copyMakeBorder. - Lines from two columns interleaved. Mode 6 and mode 4 do not split columns. Either use 3, or crop each column and run it separately.
- Missing text in a screenshot. Modes that expect a reading order drop isolated labels. Use 11.
- A line split into several lines, or two lines read as one. The mode and the image disagree about line height. Rescale the image so characters are around 30 pixels tall, then retry.
- Garbage on a single digit. Mode 10 on a crop that includes the box border can read the border as a character. Crop tighter.
- Small speckles read as punctuation in mode 11. Sparse mode accepts almost anything. Apply a confidence filter and use denoising.
Combining a mode with a character whitelist
For narrow fields, such as a numeric amount or a part number, pair a single-line mode with a whitelist of permitted characters.
import cv2
import pytesseract
field = cv2.imread("amount_field.png", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(field, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
config = "--psm 7 -c tessedit_char_whitelist=0123456789.,"
text = pytesseract.image_to_string(binary, config=config).strip()
print(text)A whitelist makes confusions such as O for 0 impossible, because the letter is not an allowed output. It cannot repair a bad crop, though. If the engine sees a smudge, it will pick the closest allowed character, and that character may be wrong with high apparent confidence. Whitelists are reliable with the LSTM engine in Tesseract 4.1 and later. Older builds ignore them.
Choosing in a pipeline
For a system that handles one kind of document, fix the mode, after measuring. For a system that handles mixed inputs, there are three options.
- Route by document type. A classifier or a simple rule, such as image aspect ratio, selects the mode. This is predictable and easy to debug.
- Segment first. Detect regions yourself, for example with OpenCV contours or a text detector, crop each region, and run a narrow mode such as 7 on each. This gives the best accuracy on structured layouts, at the cost of more code.
- Try several and pick by score. Run two or three modes and keep the result with the best mean confidence, then check it with a validation rule such as a regular expression. This is slow, because each extra mode is another full OCR pass, and mean confidence is a noisy signal, as discussed above.
Summary of decisions
- Describe the layout, then pick the most specific mode that is true: 10, 8, 7, 6, 4, 3, 11.
- Use the default 3 only for page-like images with columns.
- Use 4 for receipts and single-column documents with mixed text sizes.
- Use 11 when there is no reading order.
- Use
image_to_osdor mode 0 to detect 90-degree rotation, and deskew separately for small tilts. - Compare modes with word counts and mean confidence to shortlist, and with character error rate to decide.
Exercise
You crop a 40-pixel-tall strip from a shipping label that contains one line, "SKU 48213", and Tesseract returns an empty string with the default settings. Which mode would you try first, what two other changes could help, and why might the same mode give wrong output if the crop accidentally included part of the next line?
Show answer
Try --psm 7, which treats the image as a single text line and skips the layout analysis that failed to find a text block in the tight crop. Two helpful changes are adding a white border around the crop with cv2.copyMakeBorder and upscaling the strip so characters are about 30 pixels tall. If part of the next line is included, mode 7 still assumes there is only one line, so it will merge or garble the extra pixels into the result instead of reporting them as a separate line. Crop tightly, or use mode 6 or 4 if more than one line is possible.
Exercise
A screenshot of a dashboard has a title, four number tiles with small labels, and a legend. Mode 6 returns a few lines of text and misses most of the labels. Which mode should you switch to, and how would you check that the switch improved the result without relying only on word count?
Show answer
Switch to --psm 11 (sparse text), because the text has no single reading order or uniform block. Word count alone is misleading because sparse mode also accepts noise as words. Instead, write down the true text of a sample of screenshots, run both modes, and compare the character error rate for each. Also filter words below a confidence threshold, such as 60, and compare mean confidence on the remaining words.