Automation8 min read

Developing OCR: Tesseract, Cloud APIs and Vision LLMs

How to build OCR in practice: Tesseract settings and preprocessing, cloud document AI services, open models, vision LLMs with JSON output, and CER/WER.

By AI Agents DirectoryLast checked
Rows of server hardware with blue status lights

Building OCR today means choosing between four kinds of tool: a classic engine such as Tesseract, a managed cloud document service, an open-source deep-learning toolkit, or a vision-capable LLM that reads the page and fills in a schema. They fail in different ways, so the useful skill is knowing what each one is for and how to measure it on your own documents. This guide sticks to what each project’s documentation says, with links to the sources.

Classic OCR with Tesseract

Tesseract is an Apache-2.0 licensed engine that ships as a library (libtesseract) and a tesseract command-line program. Since version 4 it includes an LSTM neural network engine that works on whole lines, and it keeps the older pattern-matching engine from Tesseract 3. The README says it reads over 100 languages out of the box and can write plain text, hOCR, PDF, TSV, ALTO and PAGE output. There is no GUI. Version 5 is the current stable line; 5.0.0 came out on November 30, 2021.

Two command-line switches matter most:

  • --oem picks the engine. The command-line docs give --oem 1 for the LSTM engine and --oem 0 for the legacy one (legacy models only come with the traineddata files from the tessdata repo).
  • --psm tells Tesseract what layout to expect. By default it assumes a full page.
--psmWhat Tesseract assumes
3Fully automatic page segmentation, no OSD (the default)
4One column of text in varying sizes
6One uniform block of text
7A single line
8A single word
11Sparse text, found in no set order
13A raw single line, skipping Tesseract-specific tweaks

If you are reading a small crop, such as one field cut out of a form, the default mode is often the wrong one. The docs suggest switching modes for small regions, and also note that a thin white border can help when the crop is very tight.

Preprocessing that the Tesseract docs recommend

The “Improving the quality of the output” page is the best checklist to start from. It opens with a warning: unless the font or language is unusual, retraining is unlikely to help. Fix the image first.

  • Check what Tesseract saw. Set tessedit_write_images to true and inspect the resulting tessinput.tif.
  • Resolution. Tesseract does best at 300 DPI or higher, so upscale small images.
  • Dark text on a light background. Version 4 and later expect this; invert dark-mode screenshots.
  • Binarisation. Tesseract applies Otsu thresholding internally, which struggles when the page background is unevenly lit. Version 5.0.0 added Adaptive Otsu and Sauvola as alternatives.
  • Noise, bold and thin strokes. Denoise, and use dilation or erosion to thicken or thin characters (erosion helps with ink bleed in old documents).
  • Deskew. A tilted page hurts line segmentation badly; rotate so text lines are horizontal.
  • Borders. Crop dark scanner edges, which can be read as stray characters, but leave around 10 px of white margin.
  • Alpha channels. Since 4.00 Tesseract blends transparency onto white, which can go wrong (subtitles are the doc’s example), so flatten images yourself when in doubt.

For receipts, price lists and codes, the same page suggests turning off the built-in dictionaries (load_system_dawg and load_freq_dawg set to false) and restricting characters with tessedit_char_whitelist, for example to digits. It is also frank that tables are a weak spot without custom layout analysis.

A working example with pytesseract

pytesseract (Apache-2.0) is a Python wrapper that calls the Tesseract binary, so install the engine first (tesseract-ocr on Debian/Ubuntu, tesseract from Homebrew on macOS), then pip install pytesseract. Engine flags go through the config argument, as in the README:

from PIL import Image
import pytesseract

img = Image.open("receipt.png")

# LSTM engine, treat the image as one uniform block of text
text = pytesseract.image_to_string(img, lang="eng", config="--oem 1 --psm 6")
print(text)

# Word boxes, confidences, line and page numbers (TSV)
print(pytesseract.image_to_data(img, config="--oem 1 --psm 6"))

image_to_data is the call to use when you need positions or want to flag low-confidence words for review. The wrapper also offers image_to_pdf_or_hocr for searchable PDFs and a timeout argument to stop long jobs.

Cloud document AI services

The managed services go further than text: they return fields, tables and key-value pairs. Here is what each vendor’s overview page says it does.

ServiceWhat the official docs describe
Google Document AIProcessors you create per project: Enterprise Document OCR (optionally with image-quality analysis), Form Parser for tables and key-value pairs, Layout Parser for chunking, custom extractors, classifiers and splitters. Results come back as Document objects.
Amazon TextractPrinted and handwritten text detection; forms and tables via the Analyze Document API; Queries; AnalyzeExpense for invoices and receipts; AnalyzeID for U.S. IDs; an Analyze Lending workflow. Synchronous calls handle single pages, asynchronous ones handle multipage files.
Azure Document Intelligenceprebuilt-read for text, prebuilt-layout for text plus layout, prebuilt models such as receipts and invoices, plus custom template, neural, composed and classification models. Fields come back typed (date, currency, address and so on).

All three let you train or adapt models on your own labelled documents. Choose one by matching your document types to its prebuilt models, then test on real samples before committing. If receipts are your use case, see how this fits a pipeline in our post on AI expense receipt processing.

Open-source deep-learning toolkits

When data can’t leave your servers, or you want to fine-tune, two maintained Apache-2.0 projects are worth trying:

  • PaddleOCR turns images and PDFs into JSON or Markdown. It includes the PP-OCR text recognition models, PP-StructureV3 for layout-aware conversion with cell and text coordinates, and the PaddleOCR-VL vision-language models for document parsing. Recent releases list Transformers as an optional inference backend and a browser SDK, PaddleOCR.js.
  • docTR is a PyTorch library, started by Mindee and now maintained by t2k GmbH. It runs detection (finding words) then recognition (reading characters), lets you pick an architecture for each stage, reads PDFs and images, and returns a nested Page/Block/Line/Word tree that exports to JSON. Options cover rotated pages and optional layout detection.

Both projects publish their own benchmark claims in their READMEs. Treat them as vendor numbers and benchmark on your own pages.

Vision LLMs with structured output

A newer pattern skips line-level OCR: send the page image to a multimodal model and ask for JSON that matches a schema. With the Claude API, for example, an image goes in a message as a base64, URL or Files API source, and structured outputs constrain the reply to a JSON schema. In Python you can pass a Pydantic model to client.messages.parse() and read the validated object from parsed_output. Libraries such as Instructor offer a similar schema-first approach across providers.

Read the limits before relying on it. Anthropic’s vision docs say Claude “might hallucinate or make mistakes” on low-quality or rotated images and on images smaller than 200 pixels, and that coordinate outputs are approximate. Oversized images are downscaled, which can make small text harder to read, so crop or resize deliberately. A schema guarantees valid JSON, not correct values: check totals add up, dates parse and IDs match known formats, and send failures to a person. Our post on AI agents for insurance claims covers where that human review step sits in a claims workflow.

Measuring OCR quality: CER and WER

You can’t choose between engines without a test set. Collect a few hundred real documents, transcribe them by hand, and score every candidate against those transcripts.

The two standard metrics, as defined in Hugging Face’s evaluate metric cards for CER and WER:

CER = (S + D + I) / N        N = characters in the reference (S + D + C)
WER = (S + D + I) / N        N = words in the reference

S = substitutions, D = deletions, I = insertions, C = correct units

Both come from aligning the output with the reference (edit distance), so lower is better and 0 means a perfect match. Neither is capped at 1: many insertions can push it higher. The CER card notes that CER suits multilingual data where word boundaries make WER a poor fit. Neither metric says why errors happen, so look at the actual mistakes too.

For extraction pipelines, also score at field level: did the invoice total, date and supplier name come out right? That is the number that decides whether a document can skip human review.

Choosing an approach

  • Clean, printed pages and full control: Tesseract plus careful preprocessing.
  • Forms, receipts, IDs at scale with little ML work: a cloud document AI service.
  • On-premises, layout-heavy or multilingual documents: PaddleOCR or docTR.
  • Messy layouts where you need named fields: a vision LLM with a schema, plus validation and review.

Many production systems mix them, for example a cheap OCR pass for search plus an LLM or cloud extractor for the fields that matter. For more tooling, browse the data and research category.

#OCR#Tesseract#Document AI#Computer vision#Structured output
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.