ID card OCR in Python, tested on 20 cards
136 of 140
fields right with RapidOCR, scans and photos alike
Made-up cards for Utopia, the ICAO test state: no real person or card design.
The code: RapidOCR, then a label rule
It reads the card with RapidOCR, finds each label and takes the value after it. A value that fails its format check is left out.
pip install rapidocr==3.10.0 onnxruntime==1.31.1
python id_card_ocr.py card.png
id_card_ocr.py, the whole script
# pip install rapidocr==3.10.0 onnxruntime==1.31.1
# python id_card_ocr.py card.png -> the 7 fields as JSON (null when a field is not found)
import datetime, difflib, json, re, sys
from rapidocr import RapidOCR
NAME = r"[A-Z]+(?: [A-Z]+)*"
DATE = r"\d{2}\.\d{2}\.\d{4}"
FIELDS = {
"Surname": NAME,
"Given names": NAME,
"Date of birth": DATE,
"Place of birth": NAME,
"Sex": r"[MF]",
"Document no.": r"[A-Z0-9]{9}",
"Date of expiry": DATE,
}
def is_date(s):
try:
return bool(datetime.datetime.strptime(s, "%d.%m.%Y"))
except ValueError:
return False
def pick(text):
"""{label: value} from OCR text: find each label line (small slips allowed), take the rest of that line or
else the next non-empty line, keep it only if it passes the field's format check."""
lines = [s.strip(" #*:|") for s in text.splitlines() if s.strip(" #*:|")]
out = {}
for i, line in enumerate(lines):
low = line.lower()
score, label = max(
(difflib.SequenceMatcher(None, low[: len(k)], k.lower()).ratio(), k)
for k in FIELDS
)
if score < 0.8 or label in out:
continue
for value in (
line[len(label) :].strip(" :"),
lines[i + 1] if i + 1 < len(lines) else "",
):
if re.fullmatch(FIELDS[label], value) and (
"Date" not in label or is_date(value)
):
out[label] = value
break
return out
def read(path):
"""OCR text, one box a line: rows top to bottom, each row left to right."""
r = RapidOCR(params={"Global.log_level": "critical"})(path)
rows = []
for text, b in sorted(
zip(r.txts or (), r.boxes if r.boxes is not None else ()),
key=lambda t: t[1][:, 1].min() + t[1][:, 1].max(),
):
mid, h = (b[:, 1].min() + b[:, 1].max()) / 2, b[:, 1].max() - b[:, 1].min()
if rows and abs(mid - rows[-1][0]) < h / 2:
rows[-1][1].append((b[:, 0].min(), text))
else:
rows.append((mid, [(b[:, 0].min(), text)]))
return "\n".join(t for _, row in rows for _, t in sorted(row, key=lambda x: x[0]))
if __name__ == "__main__":
fields = pick(read(sys.argv[1]))
print(json.dumps({k: fields.get(k) for k in FIELDS}, indent=1))
On the card above, it printed:
{
"Surname": "VAPEVAWA",
"Given names": "HIJUNA",
"Date of birth": "18.04.1975",
"Place of birth": "HIVINA",
"Sex": "F",
"Document no.": "18KPCF306",
"Date of expiry": "18.12.2031"
}
6 of 7 right. The document number is 18KPCF3O6, with the letter O. RapidOCR read a zero, and the format check let it pass.
RapidOCR got 16 of 20 cards, photos too
| Way | Scans | Photos |
|---|---|---|
Tesseract, --psm 3 (default) |
4 | 0 |
Tesseract, --psm 11 |
8 | 0 |
| RapidOCR 3.10.0 | 16 | 16 |
| Apple Vision | 12 | 1 |
| Our Actor's page code | 3 | 0 |
- Scan: the card as a flat PNG at 300 dpi.
- Photo: on a table, tilted up to 3 degrees, smaller and blurred, as a JPEG.
Every number: fields read, picked, wrong, seconds
| Way, image | Read | Picked | Silent wrong | Cards | Seconds |
|---|---|---|---|---|---|
| Tesseract psm 3, scan | 126 | 119 | 9 | 4 | 0.26 |
| Tesseract psm 3, photo | 116 | 0 | 0 | 0 | 0.27 |
| Tesseract psm 11, scan | 128 | 128 | 9 | 8 | 0.28 |
| Tesseract psm 11, photo | 117 | 0 | 0 | 0 | 0.26 |
| RapidOCR, scan | 136 | 136 | 4 | 16 | 2.39 |
| RapidOCR, photo | 136 | 136 | 4 | 16 | 2.37 |
| Apple Vision, scan | 132 | 132 | 8 | 12 | 0.26 |
| Apple Vision, photo | 131 | 104 | 7 | 1 | 0.29 |
| Our Actor, scan | 125 | 118 | 12 | 3 | 6.98 |
| Our Actor, photo | 135 | 0 | 1 | 0 | 4.27 |
- Read: the true value is somewhere in the text, of 140. Picked: the label rule returned it.
- Silent wrong: a wrong value that passed its format check. Cards: all 7 fields right, of 20.
- Seconds: the median for one image, at background priority.
Small grey labels sink Tesseract on photos
- On the photos Tesseract read most values but dropped every small label, in both page modes, so the rule picked nothing.
-
On scans,
--psm 11kept the lone M or F. The default page mode dropped it on 9 of 20. - Apple Vision cut photo labels short, as in "nt no" and "Date of ex", or dropped them. 29 fields came back empty.
54 wrong fields in 10 runs looked right
- 48 were in the document number, mostly O and 0. In this bold font they look almost the same.
- 18KPCF3O6 came out as 18KPCF306 in all 5 ways.
- Also S for 5, I for 1, and a lost space: HIVI DULO came out as HIVIDULO.
- This card's front has no check digits. On an ICAO ID card, the MRZ on the back has them, for the number and the dates: see MRZ OCR in Python.
Our Actor: page text, then your rule
Our Apify Actor, PDF to Markdown OCR, turns scanned PDFs and images into Markdown in bulk.
- On photos it joined the fields into one paragraph, so none came out right. Split at the labels: 133 of 140, its code on this Mac.
- It runs on Apify's servers: send only cards you may process, by signed link to a private store record.
curl -s -X POST "https://api.apify.com/v2/acts/brasspage~pdf-ocr-to-markdown/run-sync-get-dataset-items" \
-H "Authorization: Bearer $APIFY_TOKEN" \
-H "Content-Type: application/json" \
-d '{"documentUrls": ["https://example.com/your-card.png"]}' \
| jq -r '.[].markdown' > card.md
import re
from id_card_ocr import FIELDS, pick
markdown = open("card.md").read()
SPLIT = re.compile("(" + "|".join(re.escape(k) for k in FIELDS) + ")")
fields = pick(SPLIT.sub(r"\n\1\n", markdown))
Free datasets to test on, and paid APIs
| Set | What is in it | License |
|---|---|---|
| MIDV-500 | 500 phone clips of 50 printed ID document types, with field text | CC BY-SA 2.5 |
| MIDV-2020 | 1,000 mock IDs of 10 types: clips, scans, photos | CC BY-SA 2.5 |
| DocXPand-25k | 24,994 synthetic ID images, 9 made-up designs | CC BY-NC-SA 4.0, non-commercial |
| IDNet | Synthetic US licenses and European IDs, for fraud work | CC0 |
Paid ID APIs: what they read, the price
| API | Reads | Price |
|---|---|---|
| AWS Textract AnalyzeID | US driver's licenses and US passports | $0.025 a page, $0.01 after 100,000 (Oregon) |
| Azure Document Intelligence, prebuilt-idDocument | Passports worldwide, US, India and Australia IDs, and more | Not checked |
| Google Document AI, US Driver License Parser | All 50 states and D.C. | $0.10 a document of up to 10 pages |
- From their own pages on Nov 28, 2026. I did not test them.
How I tested it
- 20 ID card fronts for Utopia (UTO), the ICAO 9303 test state, 85.6 by 54 mm at 300 dpi. Names and towns are random syllables.
- 7 fields in one column, grey labels above bold values, in Libre Franklin. Document numbers mix O, 0, I, 1, S and 5.
- Photo: on a brown table, tilted up to 3 degrees, at 62% size, blurred, noisy and unevenly lit, saved as JPEG quality 75.
- Tesseract 5.5.4 with the fast English model, RapidOCR 3.10.0 with its default models, Apple Vision (accurate) through ocrmac 1.0.1.
- Our Actor: its own page code (build 0.1.147) on this Mac. It read the scans with Tesseract and the photos with RapidOCR.
- Right: the label rule in the script returned the exact true value. The same rule for every way. macOS 26.6, Apple Silicon.
What I did not test
- Real cards, glare, holograms, worn or bent cards, real security backgrounds.
- Other layouts (two columns, labels beside values, two languages), other scripts, the back, the MRZ and barcodes.
- Angles over 3 degrees, low light, Windows, Linux, GPU and cloud APIs.
Sources
- RapidOCR on GitHub (Apache-2.0)
- Tesseract on GitHub (Apache-2.0)
- ocrmac on GitHub (MIT)
- IDNet on Zenodo (CC0)
- AWS Textract AnalyzeID and its pricing
- Azure prebuilt ID document model
- Google Document AI processors and pricing
- Scripts and results stay in our private repo, in research/bench/id-card-ocr-2026-11-28/.
- We make the Apify Actor, not these tools.
Questions people ask
What is the best free OCR for ID cards in Python?
In this test, RapidOCR. It got all 7 fields right on 16 of 20 cards, as scans and as photos. Apple Vision got 12 scans but 1 photo, and Tesseract no photo.
Why does Tesseract miss fields on ID card photos?
On our photos it dropped every small grey label, at psm 3 and at psm 11, so a label rule found nothing. It still read most values. RapidOCR kept the labels.
Can a format check catch O read as 0?
No. Over all 10 runs, 48 of the 54 wrong fields were document numbers that passed it. The front of these cards has no check digits. On an ICAO ID card, the MRZ on the back has them.
Is there a free ID card dataset for OCR?
MIDV-500 gives the true text of each field, under CC BY-SA 2.5, and MIDV-2020 has the same license. DocXPand-25k is non-commercial. IDNet is CC0, built for fraud work.
Related guides
- MRZ OCR in Python: PassportEye, fastmrz and RapidOCR tested
- RapidOCR in Python: tested vs Tesseract and PaddleOCR
- Apple Vision OCR vs Tesseract, tested on 523 scans
- Tesseract psm modes: which one to use, tested
- Receipt OCR in Python: Tesseract 33%, RapidOCR 84%
- Business card scanner to Excel for free: 5 ways tested on 24 cards