如何使用Python读取NADRA NIC二维码并提取英乌尔都语信息?
解决方案:读取巴基斯坦NADRA NIC二维码信息
核心步骤与代码实现
1. 确保二维码扫描准确
先确认图像清晰无干扰,使用pyzbar库完成基础扫描:
from pyzbar.pyzbar import decode from PIL import Image # 加载NIC二维码图像 img = Image.open("nic_qr.png") # 解码二维码内容 qr_results = decode(img) if not qr_results: print("未检测到二维码,请检查图像清晰度或重新扫描") else: raw_bytes = qr_results[0].data
2. 处理乌尔都语编码(关键)
NADRA NIC二维码的文本编码通常为Windows-1256(兼容乌尔都语),而非默认UTF-8,需指定编码解码:
# 优先尝试Windows-1256解码 try: decoded_content = raw_bytes.decode("windows-1256") except UnicodeDecodeError: # 兼容旧版卡片的ISO-8859-6编码 decoded_content = raw_bytes.decode("iso-8859-6", errors="replace") print("解码后原始内容:", decoded_content)
3. 解析结构化字段
NADRA的二维码数据用固定分隔符(多为|或\t)拆分字段,典型字段顺序包含NIC号、英文姓名、乌尔都语姓名、父亲姓名、出生日期等,示例解析:
# 按实际分隔符拆分(这里以|为例) fields = decoded_content.split("|") # 字段映射需根据实际数据调整索引 nic_number = fields[0] english_full_name = fields[1] urdu_full_name = fields[2] father_english_name = fields[3] father_urdu_name = fields[4] date_of_birth = fields[5] # 输出提取的信息 print(f"NIC号码:{nic_number}") print(f"英文姓名:{english_full_name}") print(f"乌尔都语姓名:{urdu_full_name}") print(f"出生日期:{date_of_birth}")
4. 图像预处理(针对模糊/反光二维码)
如果扫描失败,对图像做灰度化、二值化预处理:
# 转为灰度图 img = img.convert("L") # 二值化增强对比度 img = img.point(lambda x: 0 if x < 128 else 255, '1') # 重新扫描 qr_results = decode(img)
内容的提问来源于stack exchange,提问作者Tahira
相关产品推荐
相关产品推荐

