Sub topic 1
What OCR Does and Where It Is Used
Prerequisites
This chapter assumes you have the following:
- Basic Python, including installing packages with pip.
- Familiarity with digital images as pixel arrays: width, height, and color channels.
- Comfort running commands in a terminal.
You do not need to know anything about machine learning. Later chapters install Tesseract and write code. This chapter builds the mental model that the rest of the tutorial relies on.
What OCR Is
Optical character recognition (OCR) is the process of converting an image that contains text into machine-readable text. The input is a grid of pixels. The output is a string of characters that a program can search, copy, edit, store in a database, or pass to another system.
To a computer, a photo of a page is just numbers. The letters "A" and "B" have no meaning in a pixel array. A human reads the image without effort. A program needs a method to decide that a particular cluster of dark pixels is the letter "A".
OCR is a computer vision task. It sits between two other kinds of work:
- Image processing changes pixels, for example by sharpening or thresholding.
- Natural language processing works on text that already exists as characters.
OCR takes image data in and produces text out. After that, text tools take over.
OCR Is Not the Same as Reading a Digital Document
A PDF or Word file often stores text as characters already. You can extract that text directly, and no recognition is needed. OCR is needed when the text exists only as pixels. Typical examples are scans, photos, screenshots, and PDFs made from scanned pages.
A quick test: try selecting text in your viewer. If you can select and copy words, the file probably has a text layer. If the whole page behaves like one picture, you need OCR.
| Source | Text stored as characters? | Needs OCR? |
|---|---|---|
| Word document | Yes | No |
| PDF exported from a word processor | Yes | No |
| PDF made by scanning paper | No, only page images | Yes |
| Phone photo of a receipt | No | Yes |
| Screenshot of a web page | No | Yes |
Some scanned PDFs are "searchable". They contain page images plus a hidden text layer that an OCR step produced earlier. That text layer can contain recognition errors, so it is not guaranteed to be correct.
What an OCR Engine Returns
A basic OCR call returns a plain string. Most engines can return more than that, and the extra data matters in real systems:
- Text: the recognized characters, usually with line breaks.
- Bounding boxes: the rectangle around each word or line, given as position and size in pixels.
- Confidence scores: a number per word or character that estimates how sure the engine is.
- Layout information: grouping of words into lines, paragraphs, and blocks.
A bounding box is the smallest rectangle that encloses a piece of text. It is usually stored as left, top, width, and height. Boxes let you highlight text on the original image, crop a single field, or decide which words sit in the same column.
A confidence score is the engine's own estimate, not a measured accuracy. A word with a score of 95 can still be wrong, and a word with a score of 40 can be correct. You will use scores as a filter and a signal for review, not as proof.
Chapter 8 of this tutorial covers word boxes and confidence scores in detail. For now, keep in mind that OCR output is a set of guesses with locations attached, not a perfect transcript.
A First Look at the Code
You do not need to understand every detail yet. This example shows the smallest useful OCR program. It loads an image with Pillow, passes it to Tesseract through the pytesseract wrapper, and prints the recognized text. The Tesseract program itself must be installed on your system, because pytesseract only calls it.
from PIL import Image
import pytesseract
image = Image.open("scan.png")
text = pytesseract.image_to_string(image, lang="eng")
print(text)The call to image_to_string runs the whole recognition process and returns one string. The lang="eng" argument tells Tesseract to use its English trained data. Chapter 3 walks through installation and this call in more detail.
Where OCR Is Used
OCR appears wherever useful information is trapped in images. The use cases differ in how clean the images are and how much an error costs. Those two factors drive most design decisions.
Document Digitization
Libraries, archives, and government offices scan paper records. OCR makes the scans searchable and lets people copy passages. Source quality varies a lot. A crisp modern print is easy. A faded typewritten page or a bound book scanned near the spine is hard.
Errors here are often tolerable. A search that finds 95 percent of mentions is still very useful, even if a few words are misread.
Forms and Invoices
Businesses extract fields such as invoice numbers, dates, totals, and tax amounts from forms. This is data entry automation. The text must usually be correct, not just roughly right. A misread digit in a total changes money.
Systems in this area typically combine OCR with validation. For example, line items should add up to the stated total, and a date should match a valid calendar date. The chapter on post-processing returns to this idea.
Receipts and Expense Reports
Receipts are photographed with phones. They are narrow, often crumpled, printed in low-contrast thermal ink, and photographed at an angle. This makes them a standard hard case, and they appear throughout this tutorial as a running example.
Identity and Payment Documents
Passports, driver's licenses, and bank cards contain fixed layouts with known fields. Some also contain a machine-readable zone, which is a standardized strip of characters designed to be easy for OCR to read. Because the layout is known, systems can crop the exact field before recognizing it.
Number Plates and Industrial Reading
Automatic number plate recognition reads vehicle plates for tolling and parking. Factories read serial numbers and batch codes printed on parts. These cases involve a narrow vocabulary and tight constraints, which helps accuracy. They also involve motion blur, glare, and uneven lighting.
Accessibility
Screen readers and camera apps read printed text aloud for people with low vision. Translation apps recognize text in a photo and then translate it. In these cases the image comes from a handheld camera, so the system must cope with unpredictable conditions.
Search and Indexing
Photo libraries index the text found in pictures so you can search for a word and find a screenshot of it. Content moderation systems check images for banned text. Here the main goal is recall, meaning finding as much as possible, and some noise is acceptable.
Two Broad Kinds of Input
It helps to split image text into two groups, because the right tool depends on which one you have.
- Document text: printed or typed text on a flat page, usually dark on light, arranged in lines and paragraphs. Scans of books, letters, and forms belong here. Classic engines such as Tesseract are designed mainly for this case.
- Scene text: text that appears in a natural photo, such as a shop sign, a street name, or a product label. It can be curved, tilted, stylized, partly hidden, or set against a busy background.
This tutorial focuses on document text first. The final chapters cover scene text and deep-learning engines, which are better suited to it.
The Core Difficulty
Why is OCR hard when people read so easily? The same character can look very different. Consider these sources of variation:
- Fonts differ in shape, weight, and style.
- Printing and scanning add noise, blur, and uneven ink.
- Pages tilt, curve, or sit under shadows.
- Characters can look alike, such as the letter "O" and the digit "0", or "l", "I", and "1".
- Characters can touch each other or break apart into pieces, so one letter looks like two or two letters look like one.
An engine must handle all of this and decide on a single character at each position. It has no understanding of what the page is about, apart from whatever language information it was given. This is why image quality and preprocessing, covered in chapters 4 and 5, have such a large effect on results.
Typical OCR Errors
Errors follow patterns. Knowing them helps you spot problems in output quickly.
| Error type | Example | Typical cause | Column | Column |
|---|---|---|---|---|
| Look-alike substitution | "invoice 2024" read as "invo1ce 2O24" | Similar glyph shapes, poor resolution | ||
| Dropped characters | "Total" read as "Tota" | Faint ink, tight cropping | ||
| Merged or split words | "New York" read as "NewYork" | Narrow gaps, noise in spaces | ||
| Garbage lines | "~~ | .. ;" | Borders, stains, or images read as text | |
| Wrong reading order | Columns interleaved | Layout not understood |
Notice that the first row contains the same sample used later to measure accuracy. A single wrong character in an invoice number can break a lookup, so even a small error rate matters in some uses.
The Shape of an OCR System
The next chapter explains each stage. This diagram previews the overall flow so you can place later topics in context.
Each box maps to a later chapter. Preprocessing is chapter 5, detection and recognition are chapter 2, and post-processing is chapter 9. Not every system uses every stage, but most production systems use more than the single call shown earlier.
Common Misconceptions
- "OCR is solved." On clean, printed, modern documents, accuracy can be very high. On photos, handwriting, and degraded scans, errors are common.
- "A high confidence score means correct text." Confidence is the engine's estimate. It is useful for filtering and not a guarantee.
- "The engine reads like a person." The engine matches shapes. It does not check whether the result makes sense unless you add that check yourself.
- "Better OCR is always the answer." Often the cheaper fix is a better image: more light, a flatter page, a higher scan resolution.
- "OCR returns structured data." It returns text and positions. Turning "Total: 42.10" into a number in a database field is your job.
Deciding Whether OCR Is Right for Your Task
Before you write code, ask a few questions. They save time later.
- Does a text layer already exist? If so, extract it directly.
- How clean are the images? Flat scans at good resolution are far easier than phone photos.
- What does an error cost? Searchable archives tolerate mistakes. Financial data does not.
- Is the layout known? Fixed forms let you crop fields, which improves accuracy.
- Is the text printed or handwritten? Classic engines handle printed text far better than handwriting.
What Comes Next
The next chapter breaks OCR into its pipeline stages: detecting where text is, recognizing what it says, and producing output. Chapter 3 then runs Tesseract on real images. From there the tutorial covers why image quality matters, how to improve it, how to tune the engine, how to read boxes and scores, how to measure accuracy, and when a different tool fits better.
Summary
OCR converts pixels into text. It is needed when text exists only as an image, such as in scans, photos, and screenshots. Engines return text, and often boxes, confidence scores, and layout. Uses range from searchable archives to invoice processing, plate reading, and accessibility tools. The cost of an error and the quality of the images determine how much care a system needs. Output is always a set of guesses, so good systems verify and review results.
Exercise
You receive a folder of PDFs. Some were exported from a word processor, and some were made by scanning paper. Describe a quick way to tell which ones need OCR, and explain why running OCR on all of them would be a poor choice.
Show answer
Try selecting and copying text in each PDF, or run a text-extraction tool and check whether it returns characters. PDFs that return text have a text layer and do not need OCR. PDFs that return nothing, or behave like a single image, are scans and need OCR. Running OCR on everything would waste time and could also introduce recognition errors into text that was already exact.
Exercise
A system reads invoice totals with OCR and one word in the output has a confidence score of 97, but the total is wrong by one digit. What does this show about confidence scores, and what safeguard would you add?
Show answer
It shows that a confidence score is the engine's estimate and not a guarantee of correctness. A safeguard is validation against other data, for example checking that the line items add up to the total, plus routing mismatches to human review. Keeping the original image makes that review possible.
Exercise
Name two image conditions that would make a phone photo of a receipt harder to read than a flat office scan of the same receipt, and name one cheap fix for each that does not involve changing the OCR code.
Show answer
Possible answers: low contrast or shadows, fixed by better, even lighting; tilt or perspective, fixed by photographing the receipt flat and straight on; blur, fixed by holding the camera steady or using more light; low resolution, fixed by taking the photo closer or at a higher camera setting.