Python OCR: pytesseract, EasyOCR and Cloud APIs Tutorial

November 11, 2026 · 11 min read

Python OCR: Read Text in Images with pytesseract and EasyOCR

Python OCR turns the text inside an image into a string your code can search, store or reformat. The free route is pytesseract, a wrapper around the Tesseract engine, with EasyOCR for photos. This tutorial covers installing both, cleaning images for better accuracy, filtering by confidence, calling a cloud API, and producing tidy Markdown.

Which Python OCR Library Should You Use?

OCR (optical character recognition) means finding letters in pixels and returning them as text. In Python you have three realistic options, and they differ more in setup and cost than in code.

FeaturepytesseractEasyOCRCloud API
Installpip package plus a system binarypip package, pulls in PyTorchClient library plus a cloud account
Runs offlineYesYes, after the model downloadNo
GPUNot neededOptionalNot needed
Languages100+80+Many
HandwritingWeakNot yet (on its roadmap)Yes
CostFree, Apache 2.0Free, Apache 2.0Paid per image or page

The cloud column covers services such as Google Cloud Vision, AWS Textract and Azure AI Vision.

We start with pytesseract for clean scans and screenshots, and reach for EasyOCR on photos of signs, labels and mixed scripts. A cloud API only earns its setup cost when you need handwriting or form fields, or when local accuracy stops being good enough.

Privacy is the other deciding factor. Both local libraries keep the image on your machine, which matters for invoices, IDs and medical letters. A cloud API sends every image to the provider.

How Do You Install pytesseract and Tesseract?

pytesseract doesn't recognise anything itself. It calls the tesseract program, so you install two things: the Python package and the engine.

pip install pytesseract pillow

# Ubuntu or Debian
sudo apt install tesseract-ocr
sudo apt install tesseract-ocr-fra   # optional: French language data

# macOS with Homebrew
brew install tesseract
brew install tesseract-lang          # optional: extra languages

On Windows, download the installer from UB Mannheim, which the Tesseract installation docs point to. The installer may not add Tesseract to your PATH, so tell pytesseract where the executable lives:

import pytesseract

# Windows only, if tesseract.exe isn't on your PATH
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

print(pytesseract.get_tesseract_version())

That last line prints the engine version (5.5.3 on our Mac), and pytesseract.get_languages() lists the language packs Tesseract can find. If you see TesseractNotFoundError instead, the binary is missing or tesseract_cmd points to the wrong file. The current pytesseract release on PyPI is 0.3.13 and needs Python 3.8 or newer.

Your First Python OCR Script with pytesseract

Running OCR takes one function call: open the image and pass it to image_to_string. Here it reads a clean image of a printed community garden notice.

from PIL import Image
import pytesseract

text = pytesseract.image_to_string(Image.open("notice.png"), lang="eng")
print(text)

On a clean, high-contrast image like this, Tesseract returns the text line by line:

COMMUNITY GARDEN NOTICE

OPENING HOURS
- Monday to Friday: 8am to 6pm
- Saturday: 9am to 1pm

RULES
1. Close the gate behind you

2. Water before 10am in summer
3. Label your plot

CONTACT
Questions go to the garden committee
noticeboard by the shed.

Three arguments do most of the tuning. lang="eng+fra" reads English and French together, provided both language packs are installed. config="--psm 6" tells Tesseract to treat the image as one uniform block of text. --psm 7 treats it as a single line, which helps when you've cropped one field. The default, --psm 3, segments the page automatically. Finally, timeout=5 stops a slow job after five seconds and raises RuntimeError.

Real jobs rarely stop at one image, so most OCR Python scripts end up as a loop over a folder. Catch the timeout so one stubborn file is skipped instead of stalling or crashing the run:

from pathlib import Path
import pytesseract

for path in sorted(Path("scans").glob("*.png")):
    try:
        text = pytesseract.image_to_string(str(path), timeout=30)
    except RuntimeError:  # raised when the timeout expires
        print(f"{path.name}: timed out, skipped")
        continue
    path.with_suffix(".txt").write_text(text, encoding="utf-8")
    print(f"{path.name}: {len(text.split())} words")

Each image gets a matching .txt file next to it, and the loop prints a word count so empty results stand out. The pytesseract README lists the other helpers, including image_to_boxes for character boxes and image_to_pdf_or_hocr for a searchable PDF.

Preprocess Images to Improve Python OCR Accuracy

Tesseract does well on clean scans and badly on photos. Its guide to improving output quality says the engine works best at 300 DPI or more. It also covers binarisation (converting to black and white), deskewing so text lines run straight, and adding a small white border. For Tesseract 4.x, it advises dark text on a light background.

We tested that with a deliberately poor image: small grey text on a noisy, unevenly lit beige background. Plain image_to_string returned an empty string. Four lines of Pillow fixed most of it:

from PIL import Image, ImageOps
import pytesseract

def preprocess(path, scale=3, threshold=100):
    img = Image.open(path).convert("L")                      # grayscale
    img = img.resize((img.width * scale, img.height * scale),
                     Image.Resampling.LANCZOS)               # upscale
    img = ImageOps.autocontrast(img)                         # stretch contrast
    return img.point(lambda v: 255 if v > threshold else 0)  # binarise

print(pytesseract.image_to_string(preprocess("photo.jpg")))

The same image now gives:

‘COMMUNITY GARDEN NOTICE

OPENING HOURS
- Monday to Fnday Bam to 6pm
-Saturday 9am to tem

RULES

1 Ctose the gate behing you

Much better, though not perfect. The threshold matters: on this image 100 worked and 128 returned almost nothing, so test a few values on your own samples. Image.Resampling.LANCZOS needs Pillow 9.1 or newer. If lighting varies across the page, OpenCV's cv2.adaptiveThreshold picks a threshold per region instead of one for the whole image.

Is OCR 100% Accurate? Reading Confidence Scores in Python

No. Blur, low resolution, unusual fonts, multi-column layouts and handwriting all cause errors, and Tesseract won't tell you which words are wrong unless you ask. image_to_data returns one row per detected element, with a confidence from 0 to 100 for each word and -1 for the page, block, paragraph and line rows.

import pytesseract
from pytesseract import Output
# reuses preprocess() from the previous section

data = pytesseract.image_to_data(preprocess("photo.jpg"), output_type=Output.DICT)

for word, conf in zip(data["text"], data["conf"]):
    if conf == -1 or not word.strip():
        continue
    flag = "" if conf >= 60 else "  <- check"
    print(f"{conf:>3}  {word}{flag}")

Part of the output from our test image:

 25  NOTICE  <- check
 88  Fnday
 80  Bam
 53  6pm  <- check
 45  tem  <- check
 89  Ctose

The cut-off of 60 is our choice, not a Tesseract rule. This output also shows the limitation: confidence caught the garbled tem, but Fnday and Ctose scored in the high 80s, and the correct NOTICE scored 25. Treat confidence as a hint for review, not proof. Tesseract is also weak on handwriting and on photos taken at an angle, so send those to EasyOCR or a cloud service. Our handwritten OCR guide covers the tools that cope with cursive and handwritten notes.

OCR in Python with EasyOCR

EasyOCR uses deep learning models built on PyTorch, so pip install easyocr is a much larger download than pytesseract. In return it needs no system binary, and in our experience it copes better with photos and signs. It also covers non-Latin scripts such as Chinese, Arabic and Devanagari. Its README lists 80+ supported languages, and the current release is 1.7.2.

import easyocr

reader = easyocr.Reader(["en"], gpu=False)  # loads the model once; reuse it

for bbox, text, conf in reader.readtext("photo.jpg"):
    if conf > 0.5:
        print(f"{conf:.2f}  {text}")

print(reader.readtext("photo.jpg", detail=0))  # just a list of strings

Each result is a tuple of bounding box, text and confidence, and EasyOCR's confidence runs from 0 to 1 rather than 0 to 100. Creating the Reader is slow because it loads the model into memory, and the first run downloads the weights. Create it once and reuse it for every image. Leave out gpu=False if you have a supported GPU.

Calling an OCR API from Python: Google, AWS and Azure

A cloud API is the right call for handwriting, dense forms, or accuracy your local setup can't reach. The trade-offs are a cloud account, credentials, per-request billing (check each provider's pricing page) and images leaving your machine.

With Google Cloud Vision, install google-cloud-vision and set up Application Default Credentials. Then:

from google.cloud import vision

client = vision.ImageAnnotatorClient()
with open("notice.png", "rb") as f:
    image = vision.Image(content=f.read())

response = client.document_text_detection(image=image)
if response.error.message:
    raise RuntimeError(response.error.message)
print(response.full_text_annotation.text)

Google's Vision OCR docs describe text_detection for text in photos and document_text_detection for dense documents and handwriting. On AWS, boto3.client("textract").detect_document_text(Document={"Bytes": data}) returns blocks, and the LINE blocks hold each line of text. That call is synchronous and suits single images; multi-page documents go through the asynchronous StartDocumentTextDetection instead. Azure's equivalent is the azure-ai-vision-imageanalysis package with VisualFeatures.READ, which reads printed and handwritten text.

Which provider should you pick? Usually the one where your app and credentials already live, since setup work tends to outweigh small quality differences. If accuracy decides it, run the same ten awkward images through each before you commit.

Turn Python OCR Output into Markdown

Raw OCR text loses its structure: headings, lists and paragraphs come back as loose lines. A short heuristic restores most of it. Short ALL-CAPS lines become headings, bullet and numbered lines stay list items, and wrapped lines join into paragraphs.

import re

LIST_ITEM = re.compile(r"^([-*•]|\d+[.)])\s+")

def ocr_to_markdown(text):
    out, para = [], []

    def flush():
        if para:
            out.extend(["", " ".join(para), ""])
            para.clear()

    for line in (raw.strip() for raw in text.splitlines()):
        if not line:
            flush()
        elif LIST_ITEM.match(line):
            flush()
            out.append(re.sub(r"^[*•]\s+", "- ", line))
        elif line.isupper() and len(line) < 60:
            flush()
            level = "##" if out else "#"
            out.extend(["", f"{level} {line.title()}", ""])
        else:
            para.append(line)
    flush()
    return re.sub(r"\n{3,}", "\n\n", "\n".join(out)).strip() + "\n"

Fed the garden notice text from the first script, it returns:

# Community Garden Notice

## Opening Hours

- Monday to Friday: 8am to 6pm
- Saturday: 9am to 1pm

## Rules

1. Close the gate behind you
2. Water before 10am in summer
3. Label your plot

## Contact

Questions go to the garden committee noticeboard by the shed.

The editor below holds the same Markdown. Fix any OCR slips by hand and check that the headings and lists render as you expect:

Community Garden Notice

Text recovered with Python OCR, then cleaned into Markdown.

Opening Hours

  • Monday to Friday: 8am to 6pm
  • Saturday: 9am to 1pm

Rules

  1. Close the gate behind you
  2. Water before 10am in summer
  3. Label your plot

Contact

Questions go to the garden committee noticeboard by the shed.

58 words320 characters14 lines
Markdown

For a one-off image you don't need Python at all. Our image to Markdown tool runs Tesseract (via tesseract.js) in your browser, so the image isn't uploaded to our server. It handles one image at a time and applies a similar heading and list pass. It doesn't read handwriting. Our image to text converter guide covers the tools built into phones, Windows and Mac.

To render the Markdown as HTML in a script, see our Python Markdown guide; to go back to plain text, see Markdown to plain text. For scanned PDFs, our PDF conversion guide shows how OCRmyPDF adds a text layer first. When a PDF already has a text layer, Microsoft's MarkItDown library converts it to Markdown without OCR.

Quick Answers on pytesseract, PyMuPDF and JSON Output

Python OCR works best as a pipeline: install Tesseract, clean the image, read it with pytesseract or EasyOCR, flag low-confidence words, then reshape the text. Start with the free libraries and move to a cloud API only when handwriting or accuracy demands it. When the Markdown comes out, paste it into the editor to check every heading and list before you save it.