Sub topic 2
Why Image Quality Decides Accuracy
This chapter assumes you know basic Python, can install packages with pip, understand that an image is a grid of pixels with width, height, and color channels, and can run commands in a terminal. You need the Tesseract program installed, plus the pytesseract, opencv-python, and pillow packages.
Why image quality matters
OCR reads characters from pixels. The engine can only use the pixels it receives. Blur, low resolution, uneven lighting, noise, and skew all blur the edges between characters and the background, so the engine guesses wrong more often.
Tesseract works best when scanned text is about 300 dots per inch and each character is roughly 20 to 40 pixels tall. Smaller text loses the detail that separates similar letters, such as "o" and "e".
Preprocessing images before recognition
Preprocessing is a set of steps that separate text from the background before recognition. Two common steps are grayscale conversion and Otsu thresholding. Otsu thresholding chooses a cutoff value automatically and turns each pixel black or white.
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)
print(text)Run the script on the original and the preprocessed image. Keep a step only when it improves the output.
Choosing a page segmentation mode
Page segmentation mode (PSM) tells Tesseract how text is laid out on the page. Pass it through the config argument. For one uniform block of text, use mode 6:
text = pytesseract.image_to_string(binary, config="--psm 6")Mode 3 is the default and suits full pages with mixed layouts. Mode 7 treats the image as a single line.
Selecting languages and trained data
Tesseract needs a trained data file for each language, such as eng.traineddata. Choose languages with the lang argument, and join several with a plus sign:
text = pytesseract.image_to_string(binary, lang="eng+fra", config="--psm 6")Install each language's data file before you use it. Each added language can reduce accuracy, so include only the languages that appear in the image.
Exercise
Exercise
A scan contains one line of French text with accents. Which psm and lang values should you pass, and what must you install first?
Show answer
Use config="--psm 7" for a single line and lang="fra" for French. Install the fra.traineddata file before running the code.