Back to Blog
Technicalocrtesseractwebassembly

How Client-Side OCR Reads Text From Images

How Tesseract reads text from an image entirely in your browser, from the worker model and binarization to the LSTM recognizer, and how to prepare images for the most accurate results.

LoopalooPublished May 15, 20269 min read

Optical character recognition sounds like it should need a server. You have an image of text, you want the text back, and that feels like a job for a heavy model running on a GPU somewhere. In practice the whole pipeline runs comfortably inside a browser tab, and that is how the Loopaloo Image Text Extractor works: the image you drop never leaves your machine.

The engine behind most browser OCR is Tesseract, compiled to WebAssembly and wrapped by the tesseract.js library. Tesseract began as a research project at Hewlett-Packard, was open-sourced in 2005, and its modern recognition core is a neural network rather than the older pattern-matching approach. Running it in the browser means the WASM binary, the engine and the per-language model files download once and then execute locally against the pixels of your image.

This post walks through what happens between "here is a PNG" and "here is the text": how the engine is set up, what each stage of recognition does, and what those stages mean for getting a clean result.

The worker model

Everything starts with a Tesseract worker. Workers matter because OCR is CPU-heavy, and you do not want it blocking the main thread that is painting your progress bar. With tesseract.js, creating one looks like this:

import { createWorker, OEM } from 'tesseract.js';

const worker = await createWorker('eng+fra', OEM.LSTM_ONLY, {
  logger: (message) => {
    // message.status names the phase; message.progress runs from 0 to 1
    console.log(message.status, Math.round(message.progress * 100));
  },
});

That one call makes three decisions. The language string tells the worker which model files to fetch, and joining codes with + loads more than one. The second argument picks the OCR Engine Mode. The logger is how the worker reports progress, phase by phase: loading the core, initializing the engine, loading the language data and, finally, recognizing text with a percentage.

The engine mode deserves a closer look. Tesseract historically shipped two engines: a "legacy" engine based on character-shape pattern matching, and an LSTM engine, which is a recurrent neural network. OEM.LSTM_ONLY uses the neural recognizer exclusively. That changes what the model files contain (trained network weights rather than glyph templates) and generally gives better results on real-world fonts.

The recognition pipeline, stage by stage

When you call worker.recognize(image), Tesseract runs a sequence of stages. Knowing them explains why some images read cleanly and others come back as garbage.

Binarization

OCR does not reason about color. The first step is to reduce the image to pure black and white, a process called binarization. Tesseract uses Otsu's method by default: it looks at the histogram of pixel intensities and picks the threshold that best separates the two clusters (dark ink, light background).

Otsu's method is more forgiving than most people expect. Grey text on a slightly lighter grey page still produces two distinct clusters in the histogram, and as long as the lighting is even, the threshold lands cleanly between them. What a single global threshold cannot handle is lighting that changes across the page. A photo of a receipt with a shadow across half of it has one histogram for the lit half and another for the shadowed half, and any one cutoff either drops the faint strokes on one side or turns the other side into a solid block. Even lighting matters more than raw contrast.

Page layout analysis and segmentation

Once the image is binary, Tesseract works out where the text is. It finds connected components (blobs of adjacent black pixels), groups them into lines, groups lines into regions, and splits lines into words by looking at the gaps. This is layout analysis.

How hard it works at this is controlled by the Page Segmentation Mode (PSM), which you set as a parameter on the worker:

import { PSM } from 'tesseract.js';

await worker.setParameters({
  tessedit_pageseg_mode: PSM.SINGLE_LINE,
});

Tesseract defines more than a dozen modes. These five cover most real-world images:

PSM valueNameWhat it tells Tesseract
3AutoDo full automatic page layout analysis (the default)
6Single BlockAssume one uniform block of text, skip region detection
7Single LineTreat the whole image as one text line
8Single WordTreat the whole image as one word
11Sparse TextFind as much text as possible, in no particular order

The mode changes the result. Feed a single-line receipt total to Auto and the layout analyzer can misjudge the structure, hunting for columns that are not there. Telling it "this is one line" (PSM 7) removes the guesswork. Sparse Text (11) suits the opposite case: a screenshot with scattered labels and no flowing paragraphs at all.

Character classification

This is the LSTM's job. For each text line, Tesseract feeds a normalized strip of the image into the recurrent network, which scans left to right and emits a sequence of character probabilities. Because it is an LSTM rather than a per-glyph classifier, it has context. It sees a span of the line at once, so it can tell apart characters that look identical in isolation. The classic example is the letter "l", the digit "1" and the pipe "|", which often differ only by the letters around them.

The network outputs a probability distribution over characters at each step, and a decoding pass collapses that into the most likely string. This is also where per-word confidence comes from. Current versions of tesseract.js return only the plain text unless you ask for more, so to get words you request the block hierarchy and flatten it:

const { data } = await worker.recognize(image, {}, { text: true, blocks: true });

const words = (data.blocks ?? [])
  .flatMap((block) => block.paragraphs)
  .flatMap((paragraph) => paragraph.lines)
  .flatMap((line) => line.words)
  .map(({ text, confidence, bbox }) => ({ text, confidence, bbox }));

Each word comes back with its recognized text, a confidence percentage, and a bbox (the pixel coordinates x0, y0, x1, y1 of where that word sat in the image). Confidence is the model telling you how sure it is, and it is most useful at the word level. A page-wide average can look healthy while hiding the handful of words that are wrong; the boxes show you exactly where to look. The Loopaloo Image Text Extractor draws every word's box over your picture and outlines in red any word that came back under 70 percent confidence, so you know which readings to check by eye.

The language model

The LSTM does not work alone. Each language's traineddata file also carries a word list and patterns for punctuation and numbers. When the raw network output is ambiguous, this language data nudges decoding toward real words and plausible sequences, which is why choosing the right language changes the result.

Pick English for a French document and two things go wrong. The character set is off, because the English model was not trained to emit accented glyphs (é, à, ç) with any confidence. And the dictionary is wrong, so the decoder cannot lean on it to fix borderline characters. For a mixed-language document, the + syntax loads both models, so eng+fra covers each. The Loopaloo tool offers eighteen languages and lets you add a second one for this case.

Why it can run entirely in the browser

No stage of that pipeline needs a server. worker.recognize() accepts a File, a Blob, an image element or a canvas, reads the pixels into memory and hands them to the WASM engine running in the page. The image is processed and discarded, and nothing is uploaded.

The price of that privacy is the first download. The first time you run a recognition, the browser fetches the WASM core and the traineddata for your chosen language. That is why progress is reported in separate phases for loading the core, initializing the engine and loading the language model before recognition begins. Language files are not tiny (often several megabytes each), so the first scan feels slower than the rest. The browser caches them, and after that, recognition is pure local computation.

Starting the engine has a cost too, so a worker is worth keeping. A page that reads several images in a row can create one worker, reuse it for each image, and shut it down when it is finished:

const worker = await createWorker('eng', OEM.LSTM_ONLY);

for (const image of images) {
  const { data } = await worker.recognize(image);
  console.log(data.text);
}

await worker.terminate(); // releases the memory the WASM engine allocated

Terminating matters on a long-lived tab, because the WebAssembly memory behind a worker is not released until the worker is torn down.

What you get back, and how to shape it

The raw result is richer than a single text blob: the full text, the block, paragraph and line structure, and per-word confidence with bounding boxes. Much of what makes OCR output pleasant to use is then plain string processing that has nothing to do with recognition. A small tidy-up function might look like this:

function tidy(text, options) {
  let out = text;
  if (options.trimLines) {
    out = out.split('\n').map((line) => line.trim()).join('\n');
  }
  if (options.collapseBlankLines) {
    out = out.replace(/\n{3,}/g, '\n\n');
  }
  if (options.joinHyphenated) {
    out = out.replace(/(\p{L})-\n(\p{L})/gu, '$1$2');
  }
  if (options.joinLines) {
    out = out.replace(/\s+/g, ' ').trim();
  }
  return out;
}

Trimming cleans up the ragged spacing that segmentation tends to leave behind. Joining everything into one paragraph is what you want when you OCR a column of text and intend to reflow it. Rejoining words split by a hyphen at the end of a line repairs justified text, at the risk of merging a compound that really was hyphenated. Because all of this runs on the recognized string, it is instant: changing the case or the line handling never needs another pass through the engine. Exports work the same way. A JSON export can carry the confidence, the language and the word boxes alongside the text, which is handy if you are feeding the output into another tool.

Practical takeaways for getting good results

Everything above boils down to a few rules that follow from the pipeline:

  • Give it enough pixels. Text size matters more than anything else. The LSTM normalizes line height, but it cannot recover detail that was never captured. Tesseract's own documentation puts a typical x-height (the height of a lowercase x) at about 20 pixels for 10-point text scanned at 300 dpi, and warns that below about 10 pixels there is very little chance of accurate results. Enlarging small type before recognition often helps more than any other fix.
  • Keep the lighting even. Binarization is the first gate. Otsu's method copes with modest contrast but not with a shadow across half the page.
  • Match the language. The dictionary and character set in the traineddata file actively correct ambiguous characters. Use eng+fra style combinations for mixed text.
  • Match the page mode to the layout. Single Line for a receipt total, Sparse Text for a scattered screenshot, Auto for a full document. The wrong PSM makes the segmenter solve a problem you do not have.
  • Read the confidence word by word. A cluster of low scores on a clean-looking image usually points to text that is too small or a language mismatch, both of which you can fix and rerun.

Try it

The Loopaloo Image Text Extractor puts all of this in one place. Drop in an image, pick a language (or two) and a page layout mode, and recognition runs locally through Tesseract. By default the tool prepares the picture first: it measures the type, enlarges it if it is too small to read well (a slider sets the target x-height), flips light-on-dark pages, and converts to grey with the levels stretched, and it tells you what it did at each step. You can switch preparation off or add a strict two-level Otsu conversion. The result comes with word boxes drawn over your original, uncertain words in red, quick tidy-up options, and export to plain text, JSON, Markdown or HTML. Your image never leaves your device.

Related Tools

Related Articles