跳到正文
DEV Community· Sivakumar Mahalingam·· 56 分鐘前AI 評分48

FastMRZ 3:以純 Python 擷取護照 MRZ,毋須 Tesseract

FastMRZ 3 - Passport MRZ Extraction in Pure Python, No Tesseract

AI 導讀

FastMRZ 3 移除 Tesseract,改用專為 MRZ 字元集訓練的 ONNX 文字辨識器,以純 Python 擷取及驗證護照等文件的 MRZ。它支援多種輸入格式、TD1、TD2、TD3、MRV-A 和 MRV-B 文件格式,以及並行批次處理;所有操作均在本機 CPU 執行,文件影像不會離開用戶裝置。

正文

If you have ever built KYC onboarding, hotel check-in or border-control software, you know the MRZ: the two or three lines of <<<-padded text at the bottom of a passport, ID card or visa.

Reading it sounds simple. It is 37 possible characters (A-Z, 0-9 and <) in a fixed layout defined by ICAO 9303. In practice, most Python MRZ tools come with the same setup ritual:

  1. Install Tesseract at system level
  2. Download a special MRZ traineddata file
  3. Copy it into the correct tessdata folder
  4. Make sure all of that also exists in your Docker image, Lambda layer, CI runner and the Windows laptop of whoever joins the team next

And after all that, it still struggles with phone photos that are skewed, blurred or badly lit.

The first versions of FastMRZ had the same problem, because they used Tesseract under the hood. With FastMRZ 3, I removed Tesseract completely.

What's new in FastMRZ 3

  • No Tesseract. FastMRZ now ships its own ONNX text recogniser, trained only for the MRZ character set.
  • Pure Python install. The only dependencies are numpy, opencv-python-headless and pymupdf. No system packages, no traineddata files.
  • More accurate than the Tesseract-based versions, because the recogniser only has to tell apart 37 characters in one fixed font, not every glyph in every language.
  • More input types. File paths, NumPy arrays, Base64 strings, raw bytes, PDFs and plain MRZ text.
  • Batch processing in parallel.
  • More document formats. TD1, TD2, TD3, MRV-A and MRV-B.

Install

pip install fastmrz

That's the whole setup.

Quick start

from fastmrz import FastMRZ

fast_mrz = FastMRZ()

details = fast_mrz.get_details("passport.jpg")
print(details)

Output (trimmed):

{
  "mrz_type": "TD3",
  "surname": "ERIKSSON",
  "given_name": "ANNA MARIA",
  "birth_date": "1974-08-12",
  "sex": "F",
  "expiry_date": "2012-04-15",
  "status": "SUCCESS"
}

status is SUCCESS only when the format and every ICAO 9303 check digit are valid. Otherwise it is FAILURE, and status_message tells you the first problem found. If no MRZ is found in the image at all, you get:

{"status": "FAILURE", "status_message": "No MRZ detected"}

No exceptions to catch, no silent garbage. Either the data passed the checksums or you're told why it didn't.

Every input type you'll actually use

In real systems, images rarely arrive as files on disk. They come from an upload endpoint, a camera frame or a scanned PDF. FastMRZ takes all of them:

# Raw MRZ text instead of parsed fields
text = fast_mrz.get_details("passport.jpg", ignore_parse=True)

# OpenCV / camera frame (BGR or grayscale ndarray)
details = fast_mrz.get_details(image_array, input_type="numpy")

# From a web or mobile client
details = fast_mrz.get_details(b64_string, input_type="base64")

# Straight from an upload or S3 object
details = fast_mrz.get_details(image_bytes, input_type="bytes")

# Scanned PDF - uses the first page with an MRZ
details = fast_mrz.get_details("scan.pdf", input_type="pdf")

# Already have the MRZ string? Parse and validate only
details = fast_mrz.get_details(mrz_string, input_type="text")

Two more helpers:

# Check digits only
result = fast_mrz.validate_mrz(mrz_string)
# {"is_valid": ..., "status_message": ...}

# Get the rectified MRZ crop, useful for audit logs or manual review
strip = fast_mrz.get_mrz_image("passport.jpg")

Batch processing

results = fast_mrz.get_details_batch(["a.jpg", "b.jpg", "c.jpg"])
  • Results come back in input order
  • Runs in parallel. workers defaults to your CPU count, capped at 8
  • Expect roughly 1.5x the throughput of a plain loop on a 4-core CPU
  • A file that can't be read doesn't stop the batch. Its entry just comes back as FAILURE with a message

It takes the same options as get_details:

get_details_batch(inputs, input_type="imagepath", ignore_parse=False,
                  include_checkdigit=True, workers=None)

How it works

  1. Locate. OpenCV contour detection plus an ONNX model find the MRZ region, even when the document isn't perfectly aligned in the photo.
  2. Rectify. The MRZ strip is cropped, deskewed and normalised.
  3. Recognise. A small ONNX model reads the characters. Because it only has to handle the 37 MRZ symbols in the OCR-B font, it can be far smaller and more reliable on this job than a general-purpose OCR engine.
  4. Validate. Every check digit defined by ICAO 9303 is verified, and the fields are parsed into clean, structured output.

Everything runs locally on CPU. No document image ever leaves your machine, which matters when you're handling passports.

Supported documents

Format Used on Lines x chars
TD1 ID cards 3 x 30
TD2 Older ID cards, some visas 2 x 36
TD3 Passports 2 x 44
MRV-A Visas (large) 2 x 44
MRV-B Visas (small) 2 x 36

Migrating from PassportEye

# PassportEye
from passporteye import read_mrz
mrz = read_mrz("passport.jpg")
data = mrz.to_dict()

# FastMRZ
from fastmrz import FastMRZ
data = FastMRZ().get_details("passport.jpg")

No Tesseract install, and the status field tells you whether the checksums passed.

Upgrading from FastMRZ 1.x / 2.x

Remove Tesseract from your Dockerfile and setup scripts. You no longer need it. If you still pass the old tesseract_path or tessdata_path arguments, FastMRZ 3 ignores them and raises a FutureWarning, so you can clean them up at your own pace.

Where it fits

  • KYC and customer onboarding in banking and fintech
  • Hotel, airline and car-rental check-in
  • Travel, immigration and visa processing
  • Any back-office workflow where staff type passport details by hand today

Try it, break it, tell me

FastMRZ is open source under Apache-2.0.

The most useful thing you can send me is a failure case. If FastMRZ can't read one of your documents, open an issue with a redacted sample and I'll use it to improve the model. And if it saves you a Tesseract install, a star on GitHub helps other developers find it.

來源:DEV Community · dev.to