Sub topic 11
Deep-learning OCR and scene text
Classic engines like Tesseract work well on clean, printed pages. They struggle with photos of street signs, product labels, and curved or stylized text. This chapter explains why, how deep-learning OCR engines differ internally, and how to run one from Python. It also covers how to decide whether to switch.
This chapter assumes you have read the earlier chapters on the OCR pipeline, confidence scores, and character error rate. You should be comfortable with Python, OpenCV, and NumPy arrays.
Document text versus scene text
The text-in-image problem splits into two cases.
- Document text is printed text on a flat, evenly lit page, such as a scan, a PDF render, or a screenshot. Lines are straight, fonts are regular, and the background is plain.
- Scene text is text that appears in a photograph of the real world: shop signs, license plates, product packaging, road markings, and posters. It can be rotated, curved, partly hidden, blurred, reflected, or set in decorative fonts. The background may be a brick wall, foliage, or another busy texture.
Tesseract was designed around the first case. It expects to find lines of text through page layout analysis, and its preprocessing assumes you can separate dark ink from a light background. A single global threshold, such as Otsu's method, turns a photo of a sign into noise because the lighting changes across the frame.
Scene text needs a detector that can find text anywhere in a cluttered image, and a recognizer that tolerates distortion.
How deep-learning OCR differs
Deep-learning OCR keeps the two-stage structure from the pipeline chapter (detection, then recognition). Each stage is now a neural network trained on large sets of labeled images, many of them synthetic.
Detection networks
A text detector looks at the whole image and outputs regions that contain text. There are two common designs.
- Regression-based detectors predict boxes or rotated boxes directly, like object detectors. EAST is an example.
- Segmentation-based detectors predict, for every pixel, whether it belongs to text. They then group connected pixels into regions. CRAFT and DBNet work this way. They handle curved and irregular text better because the output is a pixel mask, not a rectangle.
The detector replaces Tesseract's layout analysis. You do not choose a page segmentation mode. The network decides where text is.
Recognition networks
Each detected region is cropped, resized to a fixed height, and passed to a recognizer. A widely used architecture is the CRNN:
- A convolutional network turns the crop into a sequence of feature columns, left to right.
- A recurrent layer (LSTM) or a transformer reads that sequence and models context between neighboring columns.
- A CTC (connectionist temporal classification) output layer predicts one character, or a blank, for each column. It then collapses repeats and blanks into the final string.
CTC is why these models need no character segmentation. The network never has to decide where one letter ends and the next begins. Newer recognizers use attention-based decoders or full transformers, which are more accurate on difficult text but slower.
What you give up
Deep-learning engines also have costs. They need more memory and compute, and a GPU makes them much faster. Model files are large, often tens to hundreds of megabytes, and are downloaded on first use. The output is also harder to debug. When Tesseract fails, you can often see why in the thresholded image. When a neural network fails, you usually cannot.
Running EasyOCR
EasyOCR is a Python package that bundles a CRAFT detector and a CRNN-style recognizer behind a small API. Install it with pip install easyocr. It depends on PyTorch, so the install is large. The first run downloads the model weights.
import cv2
import easyocr
import numpy as np
reader = easyocr.Reader(["en"], gpu=False)
image = cv2.imread("street.jpg")
if image is None:
raise FileNotFoundError("street.jpg not found")
results = reader.readtext(image)
for box, text, confidence in results:
if confidence < 0.5:
continue
points = np.array([(int(x), int(y)) for x, y in box], dtype=np.int32)
cv2.polylines(image, [points], isClosed=True, color=(0, 255, 0), thickness=2)
print(f"{text!r} confidence={confidence:.2f}")
cv2.imwrite("street_annotated.jpg", image)Points to note about this code:
easyocr.Readerloads the models, which is slow. Create it once and reuse it, not once per image.readtextreturns a list of(box, text, confidence)tuples. Theboxis four(x, y)corner points in order around the region. Unlike Tesseract'sleft, top, width, height, it can describe a rotated quadrilateral.- Confidence is between 0 and 1. Tesseract reports 0 to 100. Do not reuse the threshold of 60 from the earlier chapter. Use 0.5 as a starting point and adjust it against your own data.
- Passing the raw color image works. You normally do not binarize first, because the networks were trained on natural images. Thresholding can remove information the network would have used.
Comparing engines on the same image
The only reliable way to choose an engine is to run candidates on your own images with known correct text. This script runs both engines on one image and prints what each returns, so you can compute character error rate against a reference.
import cv2
import easyocr
import pytesseract
image = cv2.imread("label.jpg")
if image is None:
raise FileNotFoundError("label.jpg not found")
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
tesseract_text = pytesseract.image_to_string(rgb, config="--psm 11").strip()
reader = easyocr.Reader(["en"], gpu=False)
easy_lines = reader.readtext(image, detail=0)
easy_text = " ".join(easy_lines)
print("Tesseract:", tesseract_text)
print("EasyOCR: ", easy_text)Details that matter here:
--psm 11is "sparse text". It finds as much text as possible in no particular order, which suits labels and signs better than the single-block mode.detail=0makes EasyOCR return only the strings, with no boxes or confidences.- Tesseract returns text in its own reading order and EasyOCR in another. If you compare with character error rate, compare word sets or sort both outputs consistently, or the order difference will inflate the error.
Reading the results
Deep-learning engines have their own characteristic mistakes.
| Symptom | Likely cause | What to try |
|---|---|---|
| Text missed entirely | Detector threshold too strict, or text too small | Upscale the image, or lower the engine's text threshold |
| One word split into several boxes | Detector separates characters with wide gaps | Raise the engine's width-merge setting, or merge boxes yourself |
| Plausible but wrong words | Recognizer's language prior favors common words | Check the confidence, and validate against a known format |
| Vertical or rotated text read as garbage | Recognizer assumes horizontal crops | Rotate the image and run again, then keep the higher confidence |
| Slow processing | Running on CPU, or large input images | Use a GPU, or downscale to the size the model needs |
The "plausible but wrong" case deserves attention. A neural recognizer is trained to produce likely text, so it can return a clean, valid-looking word that is not what the image says. Tesseract's errors tend to look like errors, such as 1 for l. A neural engine's errors can look correct. For this reason, post-processing checks matter more here, such as pattern checks on dates, totals, and identifiers.
Other engines and when each fits
Several options exist, and the field changes quickly, so verify current versions before committing.
- Tesseract has no GPU requirement and a small footprint. It handles clean documents well, and many languages are available. It performs poorly on scene text.
- EasyOCR is easy to install and works on photos. It is a good first deep-learning option. Speed on CPU is modest.
- PaddleOCR offers detection, recognition, and layout models, with strong accuracy and fast variants. Its API has changed between major versions, so follow the documentation for the version you install.
- Cloud OCR services from large providers return text, boxes, and sometimes table or form structure. They need no local models, but they send your images to a third party and charge per page.
- Vision-language models can read text and answer questions about an image. They are flexible but slow, costly, and can invent text that is not present. Verify their output for anything important.
Choosing an approach
Use these criteria in order.
- What kind of images are they? Clean scans and PDF renders favor Tesseract with good preprocessing. Photos, signs, and packaging favor a deep-learning engine.
- What accuracy do you need? Measure character error rate on a sample of at least 50 to 100 of your own images, with the correct text written by hand. Do not rely on published benchmark numbers.
- Where can it run? An embedded device or a server with no GPU may rule out heavy models. Privacy rules may rule out cloud services.
- What are the volume and latency limits? Millions of pages a day make per-page pricing and CPU speed matter. Interactive use needs results in well under a second.
- What must the output contain? If you need tables, forms, or reading order, check that the engine provides them. Raw text alone is rarely enough.
A common production pattern is to run Tesseract first and fall back to a deep-learning engine only when the confidence is low. This keeps costs down and uses the heavier tool where it is needed. Whatever you choose, keep the validation step from the post-processing chapter, because no engine is correct all the time.
Failure modes that remain
Deep-learning OCR does not fix everything.
- Very low resolution. If characters are under roughly 10 to 12 pixels tall, detail is gone and no network can recover it.
- Handwriting. General models do poorly on handwriting. Models trained specifically for handwriting exist, but accuracy varies widely between writers.
- Unseen scripts or fonts. A recognizer trained on Latin text will not read a script it has never seen. Check the supported language list.
- Domain shift. A model trained on street photos may fail on dot-matrix printing or engraved metal. Fine-tuning on a few hundred labeled examples can help, but it is a project in itself.
- Reading order. Detectors return regions, not paragraphs. Rebuilding lines, columns, and tables is left to you.
Exercise
A teammate runs Otsu thresholding on photos of shop signs before passing them to EasyOCR, and accuracy drops compared with passing the raw color photo. Give two reasons this can happen, and describe how you would settle the question.
Show answer
Otsu uses one global threshold, and lighting varies across a photo, so parts of the sign turn solid black or white and the text is lost. Binarization also discards color and edge detail that the neural network learned from during training on natural images. To settle it, collect 50 to 100 sign photos with hand-written correct text, run EasyOCR on the raw and the thresholded versions, compute character error rate for each, and keep the version with the lower average error.
Exercise
EasyOCR returns a confidence of 0.62 for the word "TOTAL" and the same confidence for "T0TAL" (with a zero) on another receipt. Why is the confidence alone not enough to trust the second result, and what check would catch it?
Show answer
A neural recognizer can give a similar confidence to a wrong reading, and its output may look plausible. Confidence is the model's own estimate and is not calibrated against truth. A validation step helps, for example matching the text against a list of expected field names, or checking that a numeric field contains only digits. Either check would flag "T0TAL" because it is not an expected word.