Search

Search papers and lessons

Optical Character Recognition

Level 2 · 11 min read

Optical character recognition turns an image of printed or handwritten text into the text itself, by reading the picture column by column and deciding which character each column belongs to.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Probability
  • Neural network basics
  • Algorithms
  • Linear algebra
  • ReadReady to readNot yet

TL;DR

Optical character recognition (OCR) turns a picture of text into the text itself, so a scanned page or a photo of a sign becomes something you can search, copy or read aloud. A modern system does not look for one letter at a time. It reads a line of the image from left to right, with a convolutional network turning the pixels into a sequence of features, a recurrent network reading that sequence in both directions, and a loss called CTC that lets the output be shorter than the input without anyone marking where each letter starts.

Builds on: Convolutional Neural Network, Bidirectional Recurrent Neural Network, Connectionist Temporal Classification (CTC) · Leads to: text-reading features in Vision-Language Model systems

Where it's used

Digitising books and archives. Libraries scan printed pages and need every word to be searchable. The output is a text layer under the image, so a reader can search for a name in a 19th-century novel without retyping it.

Reading cheques and forms. A bank scans a cheque and reads the amount written in the box, and a government office reads the name and address on a paper form. In both cases the text sits in a fixed region, which helps, but the handwriting varies a lot from person to person.

Signs and labels in a phone camera. Point a phone at a menu or a street sign and the app shows the words as text, sometimes translated. The text is at an angle, lit unevenly and may be partly hidden, so the system has to cope with noise that a scanner does not produce.

How it works

Here is one tiny line of text, the word "hi", followed from image to output. Suppose the image is cut into six narrow columns, one per time step, and each column gets a probability for each symbol: the letters h and i, and a special blank symbol that means "nothing new here". The blank is what allows a letter to be written more than once, and it is what lets the system skip the gaps between letters.

flowchart LR
  A[Line image] --> B[Convolutional layers turn pixels into column features]
  B --> C[Bidirectional RNN reads the columns both ways]
  C --> D[Per column: probabilities for each character and blank]
  D --> E[CTC collapses repeats and drops blanks]
  E --> F[Text output]
  1. Cut the line into columns. The line image is split into vertical slices, here six. Each slice is one time step of the sequence, so a wide line gives a long sequence and a narrow one gives a short sequence. Check: six columns means six time steps.

  2. Turn pixels into features. The convolutional layers slide small filters across the image, so each column ends up with a feature vector that describes the strokes near it. Early filters respond to edges, later ones to loops and bars. Check: each column now has one feature vector, not a grid of pixels.

  3. Read the sequence in both directions. The bidirectional RNN runs once from left to right and once from right to left, then joins the two. Each column's state therefore knows what came before and after it, which helps when the shape of a letter depends on its neighbours. Check: the state for column three uses columns one, two, four, five and six.

  4. Score every symbol at every column. A Softmax over the alphabet plus the blank gives each column a probability for each symbol. Suppose the columns give the following most likely symbols: h, h, blank, blank, i, blank. Check: each column's probabilities add up to 1.

  5. Collapse the sequence. CTC turns a path of symbols into text in two rules: merge runs of the same symbol into one, then drop the blanks. The path h, h, blank, blank, i, blank becomes h, blank, i, blank after merging, and then h, i after dropping the blanks. Check: the output is "hi", two letters from six columns.

  6. Train on the text, not the alignment. The training data is just the image and the word. CTC sums the probability of every path that collapses to the right word, so the network is never told which column holds which letter. Check: a path that merges and drops to "hi" counts toward the loss, whatever its exact timing.

The math

Let XX be the image, TT the number of columns, and yt\mathbf{y}_t the vector of probabilities at column tt, one entry per symbol including the blank. The network gives a probability to each path π=(π1,…,πT)\pi = (\pi_1, \dots, \pi_T) of symbols under the assumption that columns are independent given the image:

p(π∣X)=∏t=1Tyt,πt.p(\pi \mid X) = \prod_{t=1}^{T} y_{t,\pi_t}.

Here yt,πty_{t,\pi_t} is the probability that column tt gives to the symbol πt\pi_t on the path.

Step 5 in symbols: the collapse map

Let B\mathcal{B} be the map that merges repeated symbols and then removes blanks. A label YY is the text, and the set of paths that collapse to it is B−1(Y)\mathcal{B}^{-1}(Y). The probability of the label sums over those paths:

p(Y∣X)=∑π∈B−1(Y)p(π∣X).p(Y \mid X) = \sum_{\pi \in \mathcal{B}^{-1}(Y)} p(\pi \mid X).

This sum is what lets the network skip alignment: the timing of the letters is free, so long as the collapsed path spells the word.

Step 6 in symbols: the loss

Training minimises the negative log of the label probability, averaged over examples:

L=−log⁡p(Y∣X).\mathcal{L} = -\log p(Y \mid X).

This is a negative log-likelihood, the same family as the Cross-Entropy Loss, but taken over whole labels rather than single positions. In practice the sum over paths is computed with dynamic programming, so it does not enumerate every path.

Worked examples

Example
1. Collapsing a path by hand
  1. Take the path a, a, blank, l, blank, l.
  2. Merge runs of the same symbol. The first two a's become one a, giving a, blank, l, blank, l.
  3. Drop the blanks. That leaves a, l, l.
  4. Read the result as text: "all".
  5. Interpretation: the blank between the two l's is what keeps them as two letters. Without it, the path a, a, l, l would merge to a, l, and the word would read "al".
Example
2. Adding up the paths for one label

Use a two-column image with two symbols, a and blank. The probability of a is 0.6 and of blank is 0.4, at both columns. We want the probability of the label "a".

  1. List the paths of length two that collapse to "a": (a, a), (a, blank) and (blank, a). The path (blank, blank) collapses to nothing, so it does not count.
  2. Work out each path's probability by multiplying its columns: (a, a) gives 0.6 × 0.6 = 0.36, (a, blank) gives 0.6 × 0.4 = 0.24, and (blank, a) gives 0.4 × 0.6 = 0.24.
  3. Add them: 0.36 + 0.24 + 0.24 = 0.84.
  4. Interpretation: the label "a" has a probability of 0.84, though no single path has more than 0.36. CTC is valuable because it adds up many alignments, each of which would be too small on its own.
Example
3. Reading a real line, with the last step left to you

The network reads a line and gives the most likely symbol at each of ten columns: w, w, blank, o, o, r, blank, l, blank, d.

  1. Merge the repeats. The two w's become one w, and the two o's become one o. The sequence is now w, blank, o, r, blank, l, blank, d.
  2. Drop the blanks. That leaves w, o, r, l, d.
  3. Try it: read the sequence in step 2 as one word. Answer: "world".
  4. Interpretation: two identical symbols in a row merge into one, so a single wide stroke that covers two columns is read as one letter, as the o in "world" is. A real double letter such as "ll" survives only when a blank sits between its two copies. Learning to write that blank in the right place is a large part of what the CTC loss teaches.

Common mistakes and tradeoffs

It is tempting to think that OCR finds each letter, cuts it out, and then classifies it. In fact most modern systems read the whole line as one sequence. Letters often touch, and cutting them apart first is hard and error-prone, so a sequence model that decides the segmentation as it reads does better.

It is tempting to think the blank symbol is a space. In fact the blank separates repeats and is not part of the text. A real space between words is a character in its own right, and the network learns it like any other symbol.

It is tempting to think a per-letter classifier is enough when there is a dictionary to help. In fact a dictionary or a Language Model can help a lot, but it can also turn an unusual real word into a common wrong one, so the system should keep the image evidence in view and report uncertain words.

Tradeoffs:

ApproachGood atWeak at
Cut into characters, then classifySimple, works on clean printed textFails when letters touch or are distorted
Sequence model with CTCLine-level reading without cuttingNeeds a fixed alphabet; output is one symbol per column
Attention decoder (Attention Mechanism)Can write characters in any order and use contextSlower, and more data to train well

Use a CTC line reader for most printed and handwritten lines, especially with lots of training data. Use a simpler method for clean, fixed-font text such as a receipt printed by one machine. Do not expect the same accuracy on a new script, a new font or a new kind of paper without retraining on examples of it.

History

Machines that read printed characters appeared long before computers. In the 1930s, Emanuel Goldberg built a machine that matched characters on film against a template, an early form of OCR. Through the 1960s and 1970s, most systems matched characters against stored templates or used hand-picked features and then classified each character.

Hidden Markov models in the 1990s helped systems handle sequences of characters, and they still needed careful segmentation. The change came with neural networks trained directly on lines of text. CTC, introduced by Graves and colleagues in 2006, gave a training method that did not need aligned labels, which made line-level training practical. Convolutional networks for the features and recurrent networks for the sequence then became the standard pairing, and they reached good accuracy on printed text and on handwriting in the following decade.

Recap

  • OCR converts an image of text into text, usually one line at a time.
  • A convolutional network turns the pixels of a line into a sequence of features, one per column.
  • A bidirectional RNN reads the sequence both ways, and a softmax gives each column a probability for each symbol and the blank.
  • CTC sums over all paths that collapse to the right text, so training needs only the image and its text.

Read next: Connectionist Temporal Classification (CTC) for the loss in full, and Bidirectional Recurrent Neural Network for the reading direction, and Attention Mechanism for the alternative decoder.

Check yourself

QuestionIn one sentence, what does CTC do with the blank symbol, and what would break if it did not exist?Show answer

The blank separates repeated symbols and marks the gaps where nothing new is written. Without it, a double letter such as "ll" would merge into a single letter, because the merge rule would reduce l, l to l. The network could not write two letters in a row.

QuestionA path has three columns with probabilities 0.5, 0.5 and 0.5 for the symbols it takes. What is the probability of that path, and why is it not the probability of its label?Show answer

The probability of that path is 0.5 × 0.5 × 0.5 = 0.125. The label is the collapsed text, and several different paths can collapse to the same text. The probability of the label is the sum over all of them, which is always at least as large as any one path's probability.

QuestionWhy does the network read the line in both directions rather than only left to right?Show answer

A letter's shape can depend on what comes after it as well as what comes before, such as a letter that looks different at the end of a word. A bidirectional RNN gives each column a state that knows both its left and right context, so it can use both.

QuestionA team says its OCR is 99% accurate on the characters, but users still see many wrong words. What might explain it, and what would you check?Show answer

Character accuracy averages over all characters, so a few errors in each word can add up to many wrong words, and word accuracy is usually lower. Check the word error rate, the edit distance counted in words, on a set of real lines from the users' documents, and look at which characters fail most, such as punctuation, digits or touching letters. A dictionary could also be changing words that were right.

Sources