DriverLicenseOCR

Driver license OCR in Python: Tesseract, the PDF417 barcode or an API

Published 2026-11-04 · By the Koncile team

There are three ways to read a driver's license in Python: run an open source OCR engine such as Tesseract on the front and write your own parsing, decode the barcode on the back (PDF417) with zxing-cpp and split the AAMVA fields, or send the image to an OCR API that returns named fields. The first is free but leaves you with raw text, the second is exact but only works on US and Canadian cards with a readable barcode, the third costs per page but handles both sides and any layout. None of them tells you whether the holder is still allowed to drive. Below, working code for each, the output you can expect, and where each one breaks.

Driver's license held over a laptop with code; smartphone showing scanned license; barcode scanner on desk.

Three ways to extract data from a driver license in Python

Before writing code, decide what you need back. A block of text you will search with regular expressions, the exact data the issuing state encoded, or named fields with a confidence score you can route on. The table sums up the trade offs we see when teams build this.

ApproachPython librariesWhat you getWorks onMain limit
1. Open source OCR on the frontpytesseract, EasyOCR, PaddleOCR, OpenCVRaw text lines, no field namesAny card, any country, in theoryYou write and maintain the parsing for every layout
2. Decode the PDF417 on the backzxing-cpp, then a small AAMVA parserExact fields as encoded by the state (DAQ, DCS, DBB...)US and Canadian licenses with an intact barcodeNothing from the front, nothing outside North America, fails on a blurred or damaged code
3. OCR APIrequests, or the vendor's SDKNamed fields with a confidence score, often both sides mergedDepends on the vendor; Koncile reads US states and other countriesPaid per page, the image leaves your servers

Most production setups end up combining two of them: an API or OCR for the printed fields, plus the barcode when it is there, and a comparison of both as a consistency check. The sections below go through each one with code you can run.

Option 1: Tesseract or EasyOCR on the front of the card

Optical character recognition (OCR) engines turn the image into text. Tesseract is the classic one, wrapped by pytesseract; EasyOCR and PaddleOCR use neural networks and usually do better on phone photos. The public GitHub projects for driver license OCR in Python mostly follow this route: OpenCV to clean the image, Tesseract to read it, regular expressions to pull out the name and the number.

# pip install pytesseract opencv-python  (and install the Tesseract binary)
import re
import cv2
import pytesseract

img = cv2.imread("license-front.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

text = pytesseract.image_to_string(gray)
print(text)

# Everything after this line is your own parsing, state by state
dates = re.findall(r"\b\d{2}/\d{2}/\d{4}\b", text)
number = re.search(r"\bDL\s*:?\s*([A-Z0-9 ]{6,20})", text)
print(dates, number.group(1) if number else None)

This runs in a few lines and costs nothing, which is why it shows up in so many tutorials. The trouble starts after the OCR call:

  • The output has no structure. Tesseract returns lines in reading order, mixed with labels ("DOB", "EXP", "ISS", "4d DLN") whose wording and position change from one state to the next. Each regular expression works for the cards you tested.
  • Layouts change. Each of the 50 states and the District of Columbia issues its own design, and older designs stay valid until they expire, so several layouts circulate per state at the same time.
  • Photos are hard. Glare on the laminate, the guilloche background, holograms over the dates and a tilted card all cost characters. Preprocessing (resizing, thresholding, deskewing) helps; it does not remove the problem.
  • There is no confidence per field. pytesseract can give a confidence per word, but nothing tells you that "08/15/2030" is the expiration date rather than the issue date.

Option 1 is the right choice for a prototype, for one state's cards, or when no image may leave your network and you accept to maintain the parsing yourself.

Option 2: decode the PDF417 barcode and parse the AAMVA data

On US and Canadian licenses, the back carries a two dimensional barcode (PDF417) that repeats the holder's data as text, in the format defined by the AAMVA DL/ID Card Design Standard. Decoding it gives you the values the state encoded, without any OCR error. In Python, zxing-cpp reads PDF417 from an image loaded with OpenCV or Pillow:

# pip install zxing-cpp opencv-python
import cv2
import zxingcpp

img = cv2.imread("license-back.jpg")
codes = [r for r in zxingcpp.read_barcodes(img)
         if r.format == zxingcpp.BarcodeFormat.PDF417]
if not codes:
    raise SystemExit("No PDF417 found: retake the photo of the back")

raw = codes[0].text
assert raw.startswith("@") and "ANSI " in raw[:10], "not an AAMVA barcode"

# First subfile designator: "DL" + offset (4 digits) + length (4 digits)
off, length = int(raw[23:27]), int(raw[27:31])
sub = raw[off:off + length]
if not sub.startswith("DL"):              # offsets are often wrong in practice
    sub = raw[raw.index("DL", 31):]

fields = {}
for line in sub[2:].replace("\r", "\n").split("\n"):
    line = line.strip()
    if len(line) > 3 and line[:3].isalpha() and line[:3].isupper():
        fields.setdefault(line[:3], line[3:].strip())   # "DAQ" -> license number

print(fields.get("DAQ"), fields.get("DCS"), fields.get("DBB"), fields.get("DBA"))

The parser above is deliberately short. A real one checks the AAMVA version in the header (version 01 headers are laid out differently), reads the jurisdiction subfile (ZA, ZC...) as well, and converts dates, which come as MMDDCCYY on US cards and CCYYMMDD on Canadian ones. Our guide to the AAMVA PDF417 format lists every element code with its length and gives a complete minimal parser.

ElementMeaningExample on a fictional specimen
DAQLicense numberS00012345678
DCSFamily nameMARTIN
DACFirst nameALEX
DBBDate of birth03141990
DBAExpiration date08152030
DBDIssue date08152022
DCAClassD
DAJState or provinceST

What this route cannot do:

  • It needs a good photo of the back. A PDF417 tolerates some damage through error correction, but a blurred, cropped or glared code often does not decode at all, and you get nothing instead of a partial result.
  • It ignores the front. The portrait, the signature and anything printed only on the front stay unread.
  • It covers North America only. Licenses from the UK, the EU and most other countries have no AAMVA barcode.
  • It proves little about authenticity. Anyone can encode a PDF417 with chosen data. A barcode that decodes cleanly says the format is right, not that the card is genuine; comparing it with the printed front is more telling.

Option 3: call an OCR API from Python (Koncile example)

An API takes the image and returns named fields. Mindee, Amazon Textract Analyze ID and Koncile all have one; their output and coverage differ, and our comparison of driver license reader software puts them side by side. The example below uses the Koncile API, which we know best: front and back merged into one record, a confidence score for every value, and checks on the document in the same pass (expiration, dates that fit together, signs of editing).

Before the first call

  1. Create an account on app.koncile.ai. New accounts get 20 free credits with no credit card, enough for ten licenses front and back.
  2. Generate an API key in Settings, API. Only company administrators see this screen, and the key is shown once: store it in an environment variable or a secrets manager, never in your code.
  3. Pick the template. The default driver's license template already has the fields; note its id, or create your own template and fields through the API or the interface.
  4. Check the key with POST /v1/check_api_key, which answers {"success": true}.

The full script: front, back, result

Two endpoints do the work. /v1/upload_file/ accepts one file per request and returns task ids; /v1/fetch_tasks_results/ returns the status and the fields. The back of the card joins the front through the doc_id parameter: the two files are merged into one document, which is processed again as a whole.

# pip install requests
import os
import time
import requests

API = "https://api.koncile.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['KONCILE_API_KEY']}"}
TEMPLATE_ID = int(os.environ["KONCILE_TEMPLATE_ID"])  # your driver license template


def upload(path, doc_id=None):
    params = {"template_id": TEMPLATE_ID}
    if doc_id:
        params["doc_id"] = doc_id                 # attach to an existing document
    while True:
        with open(path, "rb") as f:               # one file per request
            r = requests.post(f"{API}/upload_file/", headers=HEADERS,
                              params=params, files={"files": f}, timeout=60)
        if r.status_code == 429:                  # rate limit: no credit used
            time.sleep(int(r.headers.get("Retry-After", "2")))
            continue
        r.raise_for_status()
        return r.json()["task_ids"][0]


def wait_for(task_id, every=2, timeout=120):
    start = time.time()
    while time.time() - start < timeout:
        r = requests.get(f"{API}/fetch_tasks_results/", headers=HEADERS,
                         params={"task_id": task_id}, timeout=30)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "2")))
            continue
        r.raise_for_status()
        result = r.json()
        if result["status"] in ("DONE", "DUPLICATE"):
            return result
        if result["status"] == "FAILED":
            raise RuntimeError(result.get("status_message"))
        time.sleep(every)                         # IN PROGRESS
    raise TimeoutError(task_id)


front = wait_for(upload("license-front.jpg"))
both = wait_for(upload("license-back.jpg", doc_id=front["document_id"]))

for name, field in both["General_fields"].items():
    print(f"{name:22} {field['value']!s:28} {field['confidence_score']:.2f}")

The response for the fictional specimen used on this site looks like this (fields depend on your template):

{
  "status": "DONE",
  "document_id": 1048211,
  "status_message": "",
  "General_fields": {
    "License number":  {"value": "S000 1234 5678", "confidence_score": 0.99},
    "Last name":       {"value": "MARTIN", "confidence_score": 0.99},
    "First names":     {"value": "ALEX", "confidence_score": 0.99},
    "Date of birth":   {"value": "1990-03-14", "confidence_score": 0.99},
    "Issuing state":   {"value": "Sample State", "confidence_score": 0.97},
    "Expiration date": {"value": "2030-08-15", "confidence_score": 0.98},
    "Class":           {"value": "D", "confidence_score": 0.97},
    "Valid license":   {"value": "Yes", "confidence_score": 0.99},
    "Sides provided":  {"value": "Front and back", "confidence_score": 0.99}
  },
  "Line_fields": {}
}

The status is DONE, IN PROGRESS, DUPLICATE or FAILED. A file already sent comes back as DUPLICATE and is not billed twice. Images up to 10 MB and PDFs up to 300 MB are accepted, in JPEG, PNG or PDF. For a closer look at each field and at the checks in the response, see the page on driver license parsing through the API.

With the official SDK

Koncile also publishes a Python SDK on PyPI (package koncile, version 0.1.0 when we read it). It wraps the same endpoints; in that version the upload method asks for a folder_id or a user_id in addition to the template.

# pip install koncile   (official SDK, package koncile_sdk)
from koncile_sdk.client import KoncileAPIClient

client = KoncileAPIClient(api_key=API_KEY)       # checks the key on creation
up = client.files.upload(folder_id=FOLDER_ID, template_id=TEMPLATE_ID,
                         file_paths=["license-front.jpg"])
result = client.tasks.fetch_tasks_results(task_id=up["task_ids"][0])

Use the confidence score instead of trusting every value

Whatever the engine, some reads will be wrong: a 0 read as an O in the license number, a date half hidden by a reflection. The point of a per field score is to stop those cases before they reach your database. A simple rule that works well in onboarding flows:

THRESHOLD = 0.90
REQUIRED = ["License number", "Last name", "Date of birth", "Expiration date"]

def route(result):
    fields = result["General_fields"]
    missing = [k for k in REQUIRED if not fields.get(k, {}).get("value")]
    doubtful = [k for k, f in fields.items() if f["confidence_score"] < THRESHOLD]
    if missing or doubtful:
        return "review", missing + doubtful       # a person looks at these fields
    if fields.get("Valid license", {}).get("value") != "Yes":
        return "reject", ["expired"]
    if fields.get("Sides provided", {}).get("value") != "Front and back":
        return "review", ["missing side"]
    return "accept", []

Start with a high threshold, look at what lands in review for a few weeks, then lower it field by field. The license number and the dates deserve a stricter threshold than the address.

Webhooks instead of polling

Polling is fine for a script. In production, set a webhook in Settings, API: Koncile posts the same JSON to your endpoint when the document is done, filtered by folder or template if you want. With a signing secret, each request carries X-Koncile-Signature and X-Koncile-Timestamp headers, and the signature is an HMAC SHA256 of "{timestamp}.{raw body}". Verify it before you trust the payload:

import hashlib, hmac, time

def is_from_koncile(raw_body: bytes, signature: str, timestamp: str, secret: str) -> bool:
    if abs(time.time() - int(timestamp)) > 300:   # older than 5 minutes: refuse
        return False
    message = f"{timestamp}.{raw_body.decode('utf-8')}".encode("utf-8")
    expected = hmac.new(secret.encode("utf-8"), message, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature, expected)

Sign the raw bytes you received, not a JSON object you parsed and dumped again, or the signature never matches.

Errors and rate limits to handle

HTTP codeMeaningWhat your code should do
400, 422Bad parameter or validation errorCheck template_id, doc_id and the file type
401, 403Missing, invalid or unauthorized keySend the key as a Bearer token; regenerate it if revoked
402Usage or billing limit reachedAdd credits or change plan
413File too large, or more than one file in the requestSend one file per request
429Rate limitWait for Retry-After seconds, then retry; no credit is used

Limits apply per API key: one upload per second with bursts of five, two result reads per second with bursts of twenty. For batches of thousands of licenses, queue the uploads instead of sending them in parallel threads.

What no Python script can check on a license

Reading the card well is half the job, and the limits are the same whichever option you pick:

  • The right to drive. A genuine license that has been suspended or revoked looks exactly like a valid one. In the US, that answer comes from the state, through the AAMVA Driver's License Data Verification (DLDV) service or a motor vehicle record (MVR).
  • The person. Matching the portrait with a selfie (face match) and checking that a live person is present (liveness) are separate products. Koncile does neither.
  • A good physical fake. OCR and barcode decoding read a counterfeit as easily as a real card. Document checks catch edited files and inconsistent dates; a well made fake photographed cleanly can still pass. Treat any score as a signal to verify, never an accusation.

Treat a license image as personal data from the moment you receive it: name, address, date of birth and portrait. Keep the file only as long as your process needs it, and if you send it to an API, check where it is processed and whether it is kept. Koncile is SOC 2 Type II and GDPR compliant, deletes documents after analysis and does not use them to train models.

Frequently asked questions

01Can I do driver license OCR in Python for free?

Yes, with Tesseract (through pytesseract), EasyOCR or PaddleOCR on the front, and zxing-cpp to decode the PDF417 barcode on the back of US and Canadian cards. You get raw text or barcode data and write the parsing yourself. Hosted APIs usually have a free tier for testing; Koncile gives 20 free credits at signup.

02What is the best Python library to read a driver license?

It depends on the side. For the barcode on the back, zxing-cpp decodes PDF417 reliably from a sharp image. For the printed front, EasyOCR and PaddleOCR handle phone photos better than Tesseract in our experience, but none of them names the fields. For named fields on any layout, an OCR API is less code to maintain.

03How do I read the barcode on a driver's license in Python?

Load the photo of the back with OpenCV or Pillow, call zxingcpp.read_barcodes, keep the PDF417 result and split its text into lines: each data element starts with a three letter code, such as DAQ for the license number and DBB for the date of birth. Dates are MMDDCCYY on US cards and CCYYMMDD on Canadian ones.

04Is there a driver license OCR project on GitHub?

Several. Most combine OpenCV preprocessing, Tesseract and regular expressions to pull a name and a license number from one layout. They are useful to learn from; expect to rewrite the parsing for each state and to add a confidence check before using one in production.

05Does the Koncile API read both sides of the license?

Yes. Send the front, read the document_id from the result, then send the back with doc_id set to that id. The two files are merged into one document and processed again, and the result says which sides were received.

06Does the Koncile API decode the PDF417 barcode?

Not as a guaranteed feature. Koncile reads the printed text on both sides of the card. If you need the barcode data, decode it with zxing-cpp as shown above and compare it with the fields the API returns.

07Can a Python script tell me if a driver's license is valid?

It can tell you if the card has expired and if its dates are consistent. It cannot tell you if the license is suspended or revoked: that comes from the issuing state, through AAMVA DLDV or a motor vehicle record check, with the driver's consent where the law requires it.

08How long does an API call take?

The upload returns at once with a task id; the extraction runs in the background and is usually done within seconds for a single license. Poll every two seconds or so, or use a webhook to be called back when the document is ready.

Sources

Run the script on your own licenses

Create a Koncile account, generate an API key and send a few licenses, front and back. You get named fields, a confidence score for each one and the document checks.

Create a Koncile accountTalk to an expert

20 free credits, no credit card. Documents are deleted after analysis.