◆ AI All-in-One

Level 3 In-Depth AI · Vision, Audio and Multimodal

OCR and Document AI

Turning pictures of text into usable text and data. Classic OCR finds text boxes and reads them; document AI goes further, understanding layout, tables and forms well enough to answer questions about a page or fill a database from it. Modern systems increasingly skip OCR entirely and read pages end to end.

Level
●●●●● Intermediate
Reading
12 min
To learn it well
1 hour to read, an hour to practise
↗ Plan a path here

Read first

Object DetectionThe Transformer

This leads to

—
The full path from zero — 33 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Tensors and Shapes
  13. Supervised Learning
  14. Images as Data
  15. Linear Regression
  16. The Perceptron
  17. Logistic Regression
  18. Neural Networks
  19. Convolutional Neural Networks
  20. Recurrent Neural Networks
  21. Backpropagation
  22. Activation Functions
  23. Vanishing and Exploding Gradients
  24. Normalization Layers: BatchNorm and LayerNorm
  25. Image Classification
  26. LSTMs and GRUs
  27. Residual Connections
  28. Object Detection
  29. Sequence-to-Sequence Models
  30. Attention
  31. Self-Attention and Multi-Head Attention
  32. Positional Encodings
  33. The Transformer
  34. OCR and Document AI

Read them roughly in this order. See it on the concept map →

Why it matters

An enormous amount of the world's information is locked in images of text: scanned contracts, invoices and receipts, insurance claims, medical records, handwritten forms, historical archives, photographed whiteboards, street signs, product labels and screenshots. Optical character recognition (OCR) turns those pixels into characters a computer can search, copy and process. Document AI goes further: it understands the structure of a page (headings, paragraphs, tables, form fields and reading order) so it can extract "invoice number", "total" and "due date" into a database, or answer questions such as "what is the deductible on this policy?"

This is one of the most widely deployed forms of AI in business. Banks, insurers, governments, logistics firms and accountants process millions of documents a day with it. It also feeds retrieval-augmented generation: before an LLM can answer questions about your PDFs, the text has to be extracted, with tables and reading order intact. Bad extraction is one of the most common reasons document chatbots fail.

The intuition

Think of how you read an unfamiliar form. First you glance over the page and see where the text is: blocks, lines, boxes. Then you read each piece. Finally you use the layout to make sense of it: the number to the right of "Total:" is the total, a column of numbers under "Price" are prices, and the title is the big text at the top.

A classic OCR pipeline does the same three steps:

  1. Text detection: find the regions of the image that contain text, as boxes around words or lines. This is Object Detection where the only class is "text".
  2. Text recognition: crop each box and read its characters, turning a small image into a string.
  3. Layout and extraction: put the pieces in reading order, recognise structures (tables, key–value pairs, sections) and pull out the fields you need.
INVOICE No. 2041 Coffee beans 12.50 Milk 3.20 Total: 15.70 INVOICE No. 2041 Coffee beans 12.50 Milk 3.20 Total: 15.70 1. Document imagescan, photo or PDF page2. Text detectionfind every word or line box Coffee recogniser “Coffee” 3. Text recognitioncrop each box, read its characters (CNN or ViT encoder + CTC or decoder) {  "number": "2041",  "items": [    ["Coffee beans", 12.50],    ["Milk", 3.20]  ],  "total": 15.70} 4. Layout + extractionreading order, fields, tables End-to-end models (Donut, multimodal LLMs) can go straight from step 1 to step 4, with no separate OCR.
Fig. 1 The classic OCR and document AI pipeline. Text detection finds word boxes, recognition reads each box, and layout analysis puts the words in order and extracts structured fields. End-to-end models can go from the image straight to the structured output.

Key idea OCR = detect where the text is, recognise what it says, then use the layout to turn words into structure. Modern document AI often folds all three into one model, a layout-aware Transformer or a multimodal LLM that reads the page image directly.

How it works

Two kinds of text

  • Document text: scans and PDFs of printed pages. The text is dark on light, horizontal and in a few fonts. Clean printed English can be recognised with error rates well under 1% of characters. Difficulty comes from poor scans, unusual layouts, tables, stamps and handwriting.
  • Scene text: text in photos, such as shop signs, licence plates and labels on products. It can be curved, rotated, in perspective, partly hidden and in any style. It is much harder, and has its own benchmarks.

Handwriting recognition (HTR) is harder again, because every writer is different.

Step 1: text detection

Modern text detectors are segmentation-style CNNs. Rather than predicting boxes from anchors as in Object Detection, many predict for every pixel "is this text?" (plus, depending on the method, the distance to the box edges or the link between characters), then group pixels into word or line regions. This handles long, thin and rotated text better than ordinary boxes. EAST (2017), CRAFT (2019) and DBNet (2020) are well-known examples. Their output is a set of possibly rotated quadrilaterals.

Step 2: text recognition

Recognition takes one cropped word or line image and outputs a string. The problem is that you don't know where one character ends and the next begins, and the number of characters varies.

The classic solution is CRNN with CTC (2015). A CNN turns the line image into a sequence of feature vectors, one per narrow vertical slice from left to right. A bidirectional LSTM adds context. At each slice, the model outputs probabilities over characters plus a special "blank". The Connectionist Temporal Classification (CTC) loss sums over all the ways of aligning that per-slice output with the true string, so no character-level positions are needed for training. At prediction time you take the best symbol per slice, merge repeats and remove blanks: --CC-oo-f-ff-e-e-- becomes "Coffee". The same CTC idea is central to Speech Recognition, where it is explained in more detail.

The newer approach treats recognition as translation from image to text. TrOCR (2021) uses a pretrained vision Transformer as the encoder and a Transformer text decoder that generates the characters one at a time, as an encoder–decoder does. It is more accurate, especially on handwriting, and slower.

Step 3: layout, reading order and extraction

Recognised words come with positions, but not in order. Reading order recovery groups boxes into lines (boxes whose vertical extents overlap), sorts each line from left to right, and orders lines from top to bottom. That is enough for simple pages. Multi-column articles, sidebars and tables need layout analysis: detect and label page regions (title, paragraph, list, table, figure, caption, header, footer) with an object detector trained on page images. PubLayNet, with about 360,000 labelled pages from scientific articles, is a standard training set. Tables need a further step, table structure recognition, to find rows, columns and merged cells.

title text figure caption table text Layout analysisdetect and label page regions Layout-aware Transformers (LayoutLM family)each token's input embedding is a sum of three parts word“Total:” + 2-D positionbox (x₁, y₁, x₂, y₂) = (40, 212, 98, 230) + imagevisual features of that region Transformer encoder so the model knows “15.70” sits on the same line as “Total:”,not just that the two words appear somewhere in the text
Fig. 2 Left: layout analysis labels the regions of a page. Right: layout-aware Transformers such as LayoutLM add each word's 2-D position (and image features) to its embedding, so the model can use where text sits as well as what it says.

Key information extraction pulls specific fields from forms, receipts and invoices. Rules and templates work for one fixed layout but break when a supplier changes theirs. LayoutLM (2019) made extraction learnable across layouts. It is a BERT-style Transformer whose input for each OCR'd word is the sum of its word embedding, a 2-D position embedding of its bounding box (x1,y1,x2,y2)(x_1, y_1, x_2, y_2), and in later versions (LayoutLMv2, v3) image features. The model is pretrained on millions of scanned pages, then fine-tuned to tag each word with a field label, so that "15.70" gets labelled total. Because it sees positions, it learns that a number on the same line as "Total:" is probably the total.

OCR-free document understanding

The newest systems skip the separate OCR step. Donut (2021) is an encoder–decoder Transformer that takes the page image and directly generates structured output, such as a JSON string of fields. Nougat (2023) converts academic PDFs into Markdown, including equations. Pix2Struct (2022) learned to read screenshots by predicting their HTML. These are OCR-free models: no OCR errors cascade into later steps, and the model can use visual cues such as bold text and lines.

Multimodal LLMs are the furthest extension of this idea. Given a page image and an instruction ("extract the line items as JSON", "what is the policy's deductible?"), they do detection, recognition, layout and reasoning in one pass. Document visual question answering benchmarks such as DocVQA (2020, about 50,000 questions on about 12,000 document images) track this ability. As of late 2026, frontier multimodal models handle clean documents very well, and small open vision-language models built specially for OCR (such as olmOCR, DeepSeek-OCR and PaddleOCR-VL, first released in 2025) turn page images into Markdown cheaply. Long multi-page documents, dense tables, small print, handwriting and exact numbers still call for verification, and dedicated OCR remains cheaper and faster at very high volumes.

Measuring OCR

The standard metric is the character error rate (CER): the minimum number of single-character insertions, deletions and substitutions needed to turn the OCR output into the true text (the edit distance, or Levenshtein distance), divided by the length of the true text:

CER=S+D+IN\text{CER} = \frac{S + D + I}{N}

SS, DD and II are the numbers of substitutions, deletions and insertions, and NN is the number of characters in the reference. The word error rate (WER) is the same calculation over words, and Speech Recognition uses it too.

Worked example. The truth is Total: 15.70 (12 characters, counting the space). The OCR read Tota1: 15.7O: the letter "l" became the digit "1", and the digit "0" became the letter "O", two substitutions. CER = 2/12 ≈ 0.167. Those two confusions (l/1/I and 0/O) are the classic OCR errors. They are also exactly the ones that break an amount or an ID number, which is why extracted numbers should be checked, for example by verifying that line items add up to the total.

For extraction tasks, field-level accuracy or F1 ("was the total extracted exactly right?") matters more than CER.

In code

Two pieces of the pipeline that need no model: reconstructing reading order from unordered word boxes, and computing CER with edit distance.

# Word boxes as a text detector + recogniser might return them: (text, x1, y1, x2, y2), unordered
words = [("Total:", 40, 212, 98, 230), ("INVOICE", 40, 20, 160, 48), ("12.50", 300, 150, 350, 168),
         ("Coffee", 40, 150, 100, 168), ("beans", 106, 151, 160, 169), ("No.", 200, 24, 232, 44),
         ("2041", 238, 24, 280, 44), ("Milk", 40, 180, 80, 198), ("3.20", 304, 181, 350, 199),
         ("15.70", 296, 212, 350, 230)]

def reading_order(words, overlap=0.5):
    """Group boxes into lines by vertical overlap, then read each line left to right."""
    lines = []
    for w in sorted(words, key=lambda w: (w[2] + w[4]) / 2):         # by vertical centre
        for line in lines:
            ref = line[0]
            inter = min(w[4], ref[4]) - max(w[2], ref[2])
            if inter > overlap * min(w[4] - w[2], ref[4] - ref[2]):  # same line
                line.append(w)
                break
        else:
            lines.append([w])
    return "\n".join(" ".join(w[0] for w in sorted(line, key=lambda w: w[1])) for line in lines)

print(reading_order(words))
# INVOICE No. 2041
# Coffee beans 12.50
# Milk 3.20
# Total: 15.70

def edit_distance(a, b):
    """Minimum insertions, deletions and substitutions to turn a into b (Levenshtein)."""
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]

truth = "Total: 15.70"
ocr = "Tota1: 15.7O"                      # two classic OCR confusions: l->1, 0->O
cer = edit_distance(ocr, truth) / len(truth)
print(f"CER = {edit_distance(ocr, truth)} / {len(truth)} = {cer:.3f}")   # CER = 2 / 12 = 0.167

Classic OCR with Tesseract, through the pytesseract wrapper (install the Tesseract program itself first, and scan.png is any scanned page):

import pytesseract
from PIL import Image

img = Image.open("scan.png")
print(pytesseract.image_to_string(img, lang="eng"))            # plain text
data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)
print(list(zip(data["text"], data["left"], data["top"], data["conf"]))[:10])   # words, boxes, confidence

A Transformer recogniser for a single handwritten line, with TrOCR from Hugging Face (line.png is a cropped line of handwriting, and the model downloads on first use):

from PIL import Image
from transformers import TrOCRProcessor, VisionEncoderDecoderModel

processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
pixel_values = processor(images=Image.open("line.png").convert("RGB"), return_tensors="pt").pixel_values
ids = model.generate(pixel_values, max_new_tokens=64)
print(processor.batch_decode(ids, skip_special_tokens=True)[0])

For whole-document extraction with a multimodal LLM, send the page image with an instruction such as "Return the invoice number, line items and total as JSON", using the API pattern in Multimodal LLMs and Structured Output and JSON to enforce the format.

Common pitfalls

  • OCR-ing a PDF that already has text. Most PDFs created digitally contain the exact text. Extract it directly (with pypdf, pdfplumber or PyMuPDF), which is faster and error-free. Only scanned pages need OCR.
  • Low resolution. Text needs enough pixels per character. Around 300 dpi is the usual recommendation for scans, and small print in a downscaled image is unreadable for any model.
  • Skew, shadows and perspective. Photographed pages need deskewing, cropping and contrast correction. Phone scanning apps do this automatically.
  • Losing table structure. Plain OCR flattens tables into a jumble of numbers. Use table-aware tools or models when tables matter.
  • Silent number errors. One wrong digit in an amount, date or account number is a serious error that CER barely registers. Add validation: totals that add up, check digits, date formats, and human review of low-confidence fields.
  • Wrong language or script settings. Tesseract and others need the right language packs, and right-to-left scripts and vertical text need explicit support.
  • Multimodal LLMs "correcting" text. A language model may silently fix a typo, normalise a date or fill in a smudged digit with a plausible guess. That is good for readability and dangerous for records. Ask for verbatim transcription, and compare against classic OCR where exactness matters.

Watch out Documents are full of personal and confidential data, such as names, addresses, ID numbers, health and financial details. Check where pages are processed (local versus a cloud API), how long they are stored, and what your data-protection obligations are before sending them anywhere. See Privacy, Data and Copyright and Using AI Safely at Work.

Where it leads

A bit of history

Reading machines are older than computers. Gustav Tauschek patented an optical reading device in Austria in 1929. In the 1950s and 1960s, OCR read specially designed fonts on bank documents and mail, such as the OCR-A typeface, and the US Postal Service began automated address reading. Ray Kurzweil's Reading Machine (1976) read printed books aloud to blind users using omni-font OCR. LeCun's CNNs read handwritten digits on cheques and postcodes from the late 1980s.

Tesseract was developed at Hewlett-Packard from 1985, open-sourced in 2005 and developed with Google's sponsorship afterwards. It switched to an LSTM recogniser in version 4 (2018). Deep learning reshaped every stage in the 2010s: CRNN with CTC (2015), learned text detectors (2017–2020) and layout-aware LayoutLM (2019). From 2021, OCR-free Transformers (Donut, TrOCR, Pix2Struct, Nougat) and then multimodal LLMs began to read documents end to end, so "document AI" now often means asking a model questions about a page.

Try it

  1. Compute the CER of Invoice No. 2O41 against Invoice No. 2041. Then compute the word error rate. Which metric better reflects how bad the error is for a database lookup?
  2. In reading_order, the "Total:" line works because its boxes overlap vertically. Move "15.70" down by 12 pixels (y1=224, y2=242) and run again. What happens? Then lower overlap to 0.2.
  3. Try it: photograph a receipt and run it through Tesseract and through a multimodal assistant. Compare the totals, dates and item names character by character.

Hint for 1: one substitution in 16 characters gives a CER of about 0.06. But one of the three words is wrong, a WER of 0.33, and the lookup fails completely.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. The truth is Total: 15.70 (12 characters) and the OCR output is Tota1: 15.7O. What is the character error rate?

  2. Your manager asks you to extract the text from 5,000 PDFs that were exported from Word. What should you do first?

  3. An invoice ID 2041 was read as 2O41. CER is only about 0.06 on the line. Why might this still be a serious failure?

  4. Why does LayoutLM add a 2-D position embedding of each word's bounding box to its word embedding?

  5. You use a multimodal LLM to transcribe old handwritten records for an archive. What risk should you guard against?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Tool

Tesseract OCR documentation

Tesseract contributors · Beginner · Free

Documentation for Tesseract, the long-standing open-source OCR engine (LSTM-based since version 4), with guides to installation, languages and improving output quality.

Tool

PaddleOCR

PaddlePaddle (Baidu) · Intermediate · Free

A widely used open-source OCR toolkit with text detection, recognition for many languages, and document layout and table parsing.

Paper

OCR-free Document Understanding Transformer

Kim et al. (NAVER CLOVA) · 2021 · Advanced · Free

Donut maps a document image directly to structured output (such as JSON fields) with an encoder–decoder Transformer, skipping the separate OCR step.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/ocr-and-documents.md