- desktopauto:cardocr 引擎/流水线/校验与 ocr 调整,sdk.json/pyproject/版本三处一致 - dingtalk:AI 表格读写与错误封装扩充 - aitable:client/cli/自测与打包配置更新
653 lines
26 KiB
Python
653 lines
26 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""识别流水线:粗识别 → 方向补测 → 文字块精修 → 字段抽取 → 交叉校验。
|
|
|
|
为什么不直接「一步 OCR 全图」:手机拍的照片边长动辄 4000~5700 像素,
|
|
PP-OCR 的检测网络会先把整图缩到 ~1600,卡面上的小字(尤其浮雕卡号)就直接糊了。
|
|
所以这里做两级:先小图定位文字块(快),再把原图上对应的块按原分辨率切出来精识别
|
|
(准),卡号读不出来时再对数字带做多路增强 + 多遍投票,最后用校验位把错字纠回来。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import logging
|
|
import os
|
|
import time
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Dict, List, Optional, Sequence, Tuple
|
|
|
|
import cv2
|
|
import numpy as np
|
|
|
|
from . import bankcard, idcard
|
|
from .cards import find_cards, locate_bank_card
|
|
from .engine import Line, join_text, lines as ocr_lines, row_texts, text_line
|
|
from .img import apply_exif, gray_variants, imread, resize_side, rotate90, to_gray
|
|
from .validators import (_CONFUSABLE, PRIMARY, card_candidates, id_candidates,
|
|
normalize_text)
|
|
|
|
logger = logging.getLogger("cardocr")
|
|
|
|
IMAGE_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"}
|
|
|
|
# 粗识别缩图边长:太小丢小字,太大慢且和精修重复
|
|
_COARSE_SIDE = 1440
|
|
# 精修块最长边
|
|
_FINE_SIDE = 2200
|
|
# 数字带目标字高
|
|
_STRIP_H = 120
|
|
# 数字带做增强的通道(越多越准;跳过检测网络后单路只要 0.1~0.3s)
|
|
_STRIP_VARIANT_NAMES = ("gray", "blackhat", "otsu_inv", "sharp", "tophat")
|
|
|
|
|
|
|
|
@dataclass
|
|
class View:
|
|
"""一次 OCR 的输入区域(整图粗识别 / 精修块 / 卡片矫正图)。"""
|
|
|
|
name: str
|
|
image: np.ndarray
|
|
source: str # coarse / fine / strip / quad
|
|
rect: Tuple[int, int, int, int]
|
|
lines: List[Line] = field(default_factory=list)
|
|
text: str = ""
|
|
kind: str = "unknown" # id / bank / both / unknown
|
|
|
|
def to_dict(self) -> dict:
|
|
return {"name": self.name, "source": self.source, "rect": list(self.rect),
|
|
"size": [int(self.image.shape[1]), int(self.image.shape[0])],
|
|
"kind": self.kind, "lines": len(self.lines), "text": self.text[:180]}
|
|
|
|
|
|
def classify(text: str) -> str:
|
|
if not text.strip():
|
|
return "unknown"
|
|
is_id = idcard.looks_like_id(text)
|
|
is_bank = bankcard.looks_like_bank_card(text)
|
|
if is_id and is_bank:
|
|
return "both"
|
|
if is_id:
|
|
return "id"
|
|
if is_bank:
|
|
return "bank"
|
|
return "unknown"
|
|
|
|
|
|
def _digitish(text: str) -> int:
|
|
return sum(1 for ch in text if ch.isdigit() or ch in _CONFUSABLE)
|
|
|
|
|
|
def number_runs(text: str, min_len: int = 6) -> List[str]:
|
|
"""从一段文本里抽数字串(易混字母按首选映射还原),用于人工核对时的「命中分析」。"""
|
|
s = normalize_text(text)
|
|
norm = "".join(ch if ch.isdigit() else PRIMARY.get(ch, " ") for ch in s)
|
|
runs: List[str] = []
|
|
cur = []
|
|
for ch in norm:
|
|
if ch.isdigit():
|
|
cur.append(ch)
|
|
else:
|
|
if len(cur) >= min_len:
|
|
runs.append("".join(cur))
|
|
cur = []
|
|
if len(cur) >= min_len:
|
|
runs.append("".join(cur))
|
|
return runs
|
|
|
|
|
|
def _looks_rotated(lines: Sequence[Line]) -> bool:
|
|
"""文字框普遍「高 > 宽」→ 照片被拍成横的,值得转 90/270 度补测。"""
|
|
if not lines:
|
|
return True
|
|
tall = sum(1 for x in lines if x.height > 1.6 * x.width)
|
|
return tall >= max(2, len(lines) * 0.3)
|
|
|
|
|
|
# ---------------------------------------------------------------- 文字块
|
|
def group_blocks(lines: Sequence[Line], max_blocks: int = 12) -> List[List[Line]]:
|
|
"""把同一张卡上的文字行聚成块(按竖直间距 + 水平重叠)。"""
|
|
if not lines:
|
|
return []
|
|
items = sorted(lines, key=lambda x: (x.top, x.left))
|
|
med_h = float(np.median([x.height for x in items])) if items else 0.0
|
|
blocks: List[List[Line]] = []
|
|
cur = [items[0]]
|
|
for ln in items[1:]:
|
|
prev = cur[-1]
|
|
vgap = ln.top - prev.bottom
|
|
overlap = min(ln.right, prev.right) - max(ln.left, prev.left)
|
|
same_row = overlap > 0.15 * min(ln.width, prev.width) and \
|
|
abs(ln.y_mid - prev.y_mid) < 0.6 * max(ln.height, prev.height)
|
|
if vgap <= max(10.0, med_h * 1.2) or same_row or vgap < 0:
|
|
cur.append(ln)
|
|
else:
|
|
blocks.append(cur)
|
|
cur = [ln]
|
|
blocks.append(cur)
|
|
blocks.sort(key=lambda b: -len(b))
|
|
return blocks[:max_blocks]
|
|
|
|
|
|
def _bbox(lines: Sequence[Line], pad_x: float, pad_y: float,
|
|
bounds: Tuple[int, int]) -> Tuple[int, int, int, int]:
|
|
x1 = min(x.left for x in lines)
|
|
y1 = min(x.top for x in lines)
|
|
x2 = max(x.right for x in lines)
|
|
y2 = max(x.bottom for x in lines)
|
|
px = int((x2 - x1) * pad_x) + 8
|
|
py = int((y2 - y1) * pad_y) + 8
|
|
w, h = bounds
|
|
return max(0, x1 - px), max(0, y1 - py), min(w, x2 + px), min(h, y2 + py)
|
|
|
|
|
|
def _fit(img: np.ndarray, max_side: int = _FINE_SIDE, min_h: int = 0) -> np.ndarray:
|
|
out = img
|
|
if max(out.shape[:2]) > max_side:
|
|
out = resize_side(out, max_side=max_side)
|
|
if min_h and min(out.shape[:2]) < min_h:
|
|
out = resize_side(out, min_side=min_h)
|
|
return out
|
|
|
|
|
|
# ---------------------------------------------------------------- 精修
|
|
def _fine_views(img: np.ndarray, coarse: View,
|
|
budget: int = 3) -> List[View]:
|
|
"""从粗识别文字块里挑出信息最密的若干块,回原图按原生分辨率切开精识别。"""
|
|
blocks = group_blocks(coarse.lines)
|
|
picked: List[Tuple[float, List[Line]]] = []
|
|
for b in blocks:
|
|
t = join_text(b)
|
|
s = 0.0
|
|
if idcard.looks_like_id(t):
|
|
s += 3.0
|
|
if bankcard.looks_like_bank_card(t):
|
|
s += 2.5
|
|
d = _digitish(t)
|
|
if d >= 8:
|
|
s += 2.0
|
|
elif d >= 6:
|
|
s += 1.0
|
|
if len(b) >= 2:
|
|
s += 0.5
|
|
if s > 0:
|
|
picked.append((s, b))
|
|
picked.sort(key=lambda x: -x[0])
|
|
h, w = img.shape[:2]
|
|
# 粗识别是在缩图(≤1440)上做的,坐标要按比例放大回原图
|
|
scale = w / float(coarse.image.shape[1])
|
|
out: List[View] = []
|
|
for s, b in picked[:budget]:
|
|
x1, y1, x2, y2 = _bbox(b, 0.18, 0.55, (w, h))
|
|
x1, y1 = int(x1 * scale), int(y1 * scale)
|
|
x2, y2 = min(w, int(x2 * scale)), min(h, int(y2 * scale))
|
|
if x2 <= x1 or y2 <= y1:
|
|
continue
|
|
crop = img[y1:y2, x1:x2]
|
|
if crop.size == 0:
|
|
continue
|
|
# 与已有精修块大面积重叠则跳过(同一张卡被拆成多块时会重复)
|
|
if any(_iou_rect((x1, y1, x2 - x1, y2 - y1), v.rect) > 0.55 for v in out):
|
|
continue
|
|
crop = _fit(crop)
|
|
out.append(View(name=f"fine{len(out) + 1}", image=crop, source="fine",
|
|
rect=(x1, y1, x2 - x1, y2 - y1)))
|
|
return out
|
|
|
|
|
|
def _iou_rect(a, b) -> float:
|
|
ax, ay, aw, ah = a
|
|
bx, by, bw, bh = b
|
|
x1, y1 = max(ax, bx), max(ay, by)
|
|
x2, y2 = min(ax + aw, bx + bw), min(ay + ah, by + bh)
|
|
if x2 <= x1 or y2 <= y1:
|
|
return 0.0
|
|
inter = (x2 - x1) * (y2 - y1)
|
|
return inter / float(aw * ah + bw * bh - inter)
|
|
|
|
|
|
def _strip_variants(view: View, lines: Sequence[Line], want: int = 2):
|
|
"""对数字行做多路增强识别,逐路 yield 行文本(调用方可以随时提前收工)。
|
|
|
|
窄条图直接用识别网络(跳过检测网络),单路约 0.1~0.3s,可放心多跑几路。
|
|
"""
|
|
jobs = [ln for ln in lines if _digitish(ln.text) >= 6 and ln.width >= 100]
|
|
jobs.sort(key=lambda x: -_digitish(x.text))
|
|
for ln in jobs[:want]:
|
|
h, w = view.image.shape[:2]
|
|
px = max(6, int(ln.height * 0.2))
|
|
x1, y1 = max(0, ln.left - px), max(0, ln.top - px)
|
|
x2, y2 = min(w, ln.right + px), min(h, ln.bottom + px)
|
|
crop = _fit(view.image[y1:y2, x1:x2], max_side=1600, min_h=96)
|
|
if crop.size == 0:
|
|
continue
|
|
gray = to_gray(crop)
|
|
for name, var in gray_variants(gray, upscale=1.0):
|
|
if name in _STRIP_VARIANT_NAMES:
|
|
text = text_line(var)
|
|
if text:
|
|
yield [text]
|
|
|
|
|
|
# ---------------------------------------------------------------- 主流程
|
|
def analyze_image(path: str, expected_name: str = "",
|
|
mark_dir: Optional[str] = None,
|
|
extra_passes: bool = True,
|
|
fast: bool = False) -> dict:
|
|
"""识别单张照片,返回结构化结果。
|
|
|
|
Args:
|
|
path: 图片路径(支持中文 / 空格)。
|
|
expected_name: 表格或文件夹里的姓名,用来校验身份证上的姓名。
|
|
mark_dir: 若给目录,把命中区域的标注图存下去方便人工复核。
|
|
extra_passes: 卡号/身份证号没读准时,是否追加多遍增强识别。
|
|
fast: 只跑粗识别(快,但精度下降)。
|
|
"""
|
|
t0 = time.time()
|
|
p = Path(path)
|
|
img = imread(str(p))
|
|
img = apply_exif(img, str(p))
|
|
H, W = img.shape[:2]
|
|
views: List[View] = []
|
|
|
|
def add_view(v: View) -> None:
|
|
v.lines = ocr_lines(v.image)
|
|
v.text = join_text(v.lines)
|
|
v.kind = classify(v.text)
|
|
views.append(v)
|
|
|
|
# ---- 1) 粗识别(原方向;缩略图先放大,否则小字根本没有像素)
|
|
coarse_src = img if max(H, W) >= 1000 else resize_side(img, min_side=1000)
|
|
coarse_img = resize_side(coarse_src, max_side=_COARSE_SIDE)
|
|
coarse = View(name="coarse", image=coarse_img, source="coarse", rect=(0, 0, W, H))
|
|
add_view(coarse)
|
|
chosen_rot = 0
|
|
img_work = img
|
|
|
|
# ---- 2) 方向补测:只在「身份证号 / 卡号」都没读准时才做(每多一次约 2~4s)
|
|
if not fast:
|
|
def quick_q(views: Sequence[View]) -> int:
|
|
idok = any(c.checksum_ok for c in id_candidates(rows_of(views, "id"), limit=3))
|
|
cok = any(c.luhn_ok for c in card_candidates(rows_of(views, "bank"), limit=3))
|
|
return int(idok) + int(cok)
|
|
|
|
q = quick_q(views)
|
|
# 文字是竖排的(整张照片拍横了)或几乎没识别到字,才值得换方向重认
|
|
rotated_text = _looks_rotated(coarse.lines)
|
|
few_text = len(coarse.lines) <= 2
|
|
if q < 2 and (rotated_text or few_text):
|
|
best_q, best_k = q, 0
|
|
for k in (1, 3):
|
|
small = resize_side(rotate90(img, k), max_side=_COARSE_SIDE)
|
|
probe = View(name="probe", image=small, source="coarse", rect=(0, 0, W, H))
|
|
probe.lines = ocr_lines(small)
|
|
probe.text = join_text(probe.lines)
|
|
probe.kind = classify(probe.text)
|
|
qk = quick_q([probe])
|
|
if qk > best_q:
|
|
best_q, best_k = qk, k
|
|
if qk == 2:
|
|
break
|
|
if best_k:
|
|
chosen_rot = best_k
|
|
img_work = rotate90(img, chosen_rot)
|
|
views.clear()
|
|
coarse = View(name="coarse",
|
|
image=resize_side(img_work, max_side=_COARSE_SIDE),
|
|
source="coarse",
|
|
rect=(0, 0, img_work.shape[1], img_work.shape[0]))
|
|
add_view(coarse)
|
|
|
|
# ---- 3) 首版字段抽取
|
|
id_res, bank_res = _extract(views, expected_name)
|
|
extra_used = 0
|
|
extra_rows: List[str] = []
|
|
|
|
# ---- 4) 精修:只在字段缺失 / 不可信时,回原图按原生分辨率切块重识别
|
|
need_id = not id_res.checksum_ok
|
|
need_card = not (bank_res.found and bank_res.luhn_ok
|
|
and bank_res.length in (16, 18, 19))
|
|
if (need_id or need_card) and not fast:
|
|
budget = 2
|
|
for v in _fine_views(img_work, coarse, budget=budget):
|
|
add_view(v)
|
|
id_res, bank_res = _extract(views, expected_name)
|
|
|
|
# ---- 5) 多路增强:数字带换灰度/黑帽/Otsu 反相再识别一遍(浮雕字、反光靠这层)
|
|
if extra_passes and not fast and (not id_res.checksum_ok
|
|
or not (bank_res.found and bank_res.luhn_ok)):
|
|
# 5.1 整图灰度/CLAHE 通道:彩色图上漏掉的卡号,灰度图经常能出来(实测很有效)
|
|
if not (bank_res.found and bank_res.luhn_ok):
|
|
base = resize_side(img_work, max_side=_COARSE_SIDE)
|
|
for vname, var in gray_variants(to_gray(base), upscale=1.0):
|
|
if vname not in ("gray", "clahe"):
|
|
continue
|
|
add_view(View(name=f"gray_{vname}", image=var, source="fine",
|
|
rect=(0, 0, base.shape[1], base.shape[0])))
|
|
id_res, bank_res = _extract(views, expected_name)
|
|
if bank_res.found and bank_res.luhn_ok:
|
|
break
|
|
|
|
# 5.2 小图放大补识别:短边 <800px 的缩略图,卡号笔画往往只有几个像素
|
|
if (not (bank_res.found and bank_res.luhn_ok)) and min(W, H) < 800:
|
|
big = resize_side(img_work, min_side=2400)
|
|
for vname, var in gray_variants(to_gray(big), upscale=1.0):
|
|
if vname not in ("gray", "adaptive"):
|
|
continue
|
|
add_view(View(name=f"zoom_{vname}", image=var, source="fine",
|
|
rect=(0, 0, big.shape[1], big.shape[0])))
|
|
id_res, bank_res = _extract(views, expected_name)
|
|
if bank_res.found and bank_res.luhn_ok:
|
|
break
|
|
|
|
# 5.3 数字带窄条:跳过检测网络,多路增强 + 出现合法卡号就收工
|
|
if not (bank_res.found and bank_res.luhn_ok):
|
|
digit_views = [v for v in views if v.source in ("fine", "quad", "coarse")]
|
|
digit_views.sort(key=lambda v: -_digitish(v.text))
|
|
for v in digit_views[:2]:
|
|
for rows in _strip_variants(v, v.lines, want=2):
|
|
extra_rows.extend(rows)
|
|
extra_used += len(rows)
|
|
id_res, bank_res = _extract(views, expected_name, extra_rows=extra_rows)
|
|
if bank_res.found and bank_res.luhn_ok:
|
|
break
|
|
if bank_res.found and bank_res.luhn_ok:
|
|
break
|
|
|
|
# ---- 6) 兜底:卡号/身份证没读出来时,试一次卡片矫正
|
|
# 注意条件不能只看「几乎没文字」:手机拍卡常能认出「招商银行/银联」几行,
|
|
# 文字够多但卡号一个都没检出,这时同样需要矫正后再认一遍。
|
|
if not fast and (len([ln for v in views for ln in v.lines]) < 3
|
|
or (not (bank_res.found and bank_res.luhn_ok)
|
|
and bankcard.looks_like_bank_card(
|
|
" ".join(v.text for v in views)))):
|
|
quads = list(find_cards(img_work, max_cards=2, warp_width=1712))
|
|
if not quads:
|
|
# Canny 四边形找不到(反光打断卡边)时,退到色块/边缘兜底
|
|
flat = locate_bank_card(img_work, warp_width=1712)
|
|
if flat is not None:
|
|
add_view(View(name="quad1", image=flat, source="quad",
|
|
rect=(0, 0, flat.shape[1], flat.shape[0])))
|
|
for i, r in enumerate(quads):
|
|
if r.warped is not None and r.warped.size:
|
|
add_view(View(name=f"quad{i + 1}", image=r.warped, source="quad",
|
|
rect=cv2.boundingRect(np.asarray(r.pts, dtype=np.int32))))
|
|
if len(views) > 1:
|
|
id_res, bank_res = _extract(views, expected_name)
|
|
|
|
# ---- 5) 汇总标记
|
|
flags: List[str] = []
|
|
if id_res.found and not id_res.checksum_ok:
|
|
flags.append("id_checksum_fail")
|
|
if not id_res.found:
|
|
flags.append("id_not_found")
|
|
if not bank_res.found:
|
|
flags.append("card_not_found")
|
|
elif not bank_res.luhn_ok:
|
|
flags.append("card_luhn_fail")
|
|
if bank_res.found and bank_res.length not in (16, 18, 19):
|
|
flags.append("card_length_odd")
|
|
if id_res.number and bank_res.number and id_res.number == bank_res.number:
|
|
flags.append("same_number_id_and_card")
|
|
if expected_name and id_res.name and id_res.name != expected_name:
|
|
flags.append("id_name_mismatch")
|
|
if min(H, W) < 400:
|
|
flags.append("low_resolution")
|
|
if chosen_rot:
|
|
flags.append(f"rotated_{chosen_rot * 90}")
|
|
|
|
# 所有识别到过的数字片段(含被淘汰的候选),供「和已知号码比对」时找证据
|
|
runs: List[str] = []
|
|
for row in rows_of(views) + extra_rows:
|
|
runs.extend(number_runs(row, 6))
|
|
unique_runs = list(dict.fromkeys(runs))[:40]
|
|
|
|
res = {
|
|
"file": str(p), "filename": p.name,
|
|
"bytes": p.stat().st_size if p.exists() else 0,
|
|
"width": W, "height": H,
|
|
"sha256": sha256_file(p),
|
|
"elapsed_s": round(time.time() - t0, 2),
|
|
"rotation_applied": chosen_rot * 90,
|
|
"views": [v.to_dict() for v in views],
|
|
"layout": _layout(views),
|
|
"id_card": id_res.to_dict(),
|
|
"bank_card": bank_res.to_dict(),
|
|
"digit_runs": unique_runs,
|
|
"flags": flags,
|
|
"ocr_passes": len(views) + extra_used,
|
|
}
|
|
if mark_dir:
|
|
res["marks"] = _save_marks(views, str(mark_dir), p.stem)
|
|
return res
|
|
|
|
|
|
def idline(views: Sequence[View], kind: str) -> List[Line]:
|
|
focus = [v for v in views if v.kind in (kind, "both")]
|
|
return [ln for v in (focus or views) for ln in v.lines]
|
|
|
|
|
|
def bline(views: Sequence[View], kind: str) -> List[Line]:
|
|
focus = [v for v in views if v.kind in (kind, "both")]
|
|
return [ln for v in (focus or views) for ln in v.lines]
|
|
|
|
|
|
def rows_of(views: Sequence[View], kind: str = "") -> List[str]:
|
|
"""按视图取「行文本」;kind 传 id/bank 时只取对应卡片视图(没有则退回全部)。"""
|
|
focus = [v for v in views if v.kind in (kind, "both")] if kind else list(views)
|
|
out: List[str] = []
|
|
for v in (focus or views):
|
|
out.extend(row_texts(v.lines))
|
|
return out
|
|
|
|
|
|
def _extract(views: Sequence[View], expected_name: str,
|
|
extra_rows: Optional[Sequence[str]] = None):
|
|
"""按视图集合跑一遍字段抽取(extra_rows 是补充识别出来的行文本)。"""
|
|
all_text = " ".join(v.text for v in views)
|
|
extra = list(extra_rows or ())
|
|
id_res = idcard.parse(idline(views, "id"), expected_name=expected_name,
|
|
full_text=all_text, rows=rows_of(views, "id") + extra)
|
|
bank_res = bankcard.parse(bline(views, "bank"), all_text,
|
|
exclude=[id_res.number] if id_res.number else (),
|
|
rows=rows_of(views, "bank") + extra)
|
|
return id_res, bank_res
|
|
|
|
|
|
def _layout(views: Sequence[View]) -> str:
|
|
kinds = {v.kind for v in views}
|
|
if "both" in kinds or ("id" in kinds and "bank" in kinds):
|
|
return "both"
|
|
if kinds == {"id"}:
|
|
return "id_only"
|
|
if kinds == {"bank"}:
|
|
return "bank_only"
|
|
return "unknown"
|
|
|
|
|
|
def sha256_file(p: Path) -> str:
|
|
h = hashlib.sha256()
|
|
with open(p, "rb") as f:
|
|
for chunk in iter(lambda: f.read(1 << 20), b""):
|
|
h.update(chunk)
|
|
return h.hexdigest()
|
|
|
|
|
|
# ---------------------------------------------------------------- 标注图
|
|
_FONT_CACHE: Dict[int, object] = {}
|
|
|
|
|
|
def _font(size: int = 16):
|
|
if size in _FONT_CACHE:
|
|
return _FONT_CACHE[size]
|
|
try:
|
|
from PIL import ImageFont # noqa: PLC0415
|
|
|
|
for cand in (r"C:\Windows\Fonts\msyh.ttc", r"C:\Windows\Fonts\simhei.ttf",
|
|
r"C:\Windows\Fonts\simsun.ttc"):
|
|
if os.path.isfile(cand):
|
|
try:
|
|
_FONT_CACHE[size] = ImageFont.truetype(cand, size)
|
|
return _FONT_CACHE[size]
|
|
except Exception: # noqa: BLE001
|
|
continue
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
_FONT_CACHE[size] = None
|
|
return None
|
|
|
|
|
|
def _save_marks(views: Sequence[View], out_dir: str, stem: str) -> List[str]:
|
|
os.makedirs(out_dir, exist_ok=True)
|
|
font = _font(16)
|
|
paths: List[str] = []
|
|
for v in views:
|
|
base = v.image.copy()
|
|
for ln in v.lines:
|
|
cv2.rectangle(base, (ln.left, ln.top), (ln.right, ln.bottom), (0, 200, 0), 1)
|
|
if font is not None:
|
|
from PIL import Image, ImageDraw # noqa: PLC0415
|
|
|
|
pil = Image.fromarray(cv2.cvtColor(base, cv2.COLOR_BGR2RGB))
|
|
draw = ImageDraw.Draw(pil)
|
|
for ln in v.lines:
|
|
ty = ln.top - 18 if ln.top >= 18 else ln.bottom + 2
|
|
draw.text((ln.left, ty), ln.text[:24], fill=(255, 0, 0), font=font)
|
|
canvas = np.array(pil)[:, :, ::-1]
|
|
else:
|
|
canvas = base
|
|
out = os.path.join(out_dir, f"{stem}.{v.name}.{v.kind}.png")
|
|
ok, buf = cv2.imencode(".png", canvas)
|
|
if ok:
|
|
buf.tofile(out)
|
|
paths.append(out)
|
|
return paths
|
|
|
|
|
|
# ---------------------------------------------------------------- 批量
|
|
def analyze_folder(root: str, expected_names: Optional[Dict[str, str]] = None,
|
|
mark_dir: Optional[str] = None, extra_passes: bool = True,
|
|
fast: bool = False, limit: int = 0) -> List[dict]:
|
|
"""按「姓名/图片」目录结构批量识别,同人多图合并成一条记录。"""
|
|
root_p = Path(root)
|
|
if not root_p.is_dir():
|
|
raise FileNotFoundError(f"目录不存在:{root}")
|
|
persons: List[dict] = []
|
|
cache: Dict[str, dict] = {} # sha256 → 识别结果(同一张图被传到两列时只跑一遍)
|
|
for d in sorted(root_p.iterdir()):
|
|
if not d.is_dir():
|
|
continue
|
|
imgs = sorted(p for p in d.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_EXT)
|
|
if not imgs:
|
|
continue
|
|
name = (expected_names or {}).get(d.name, d.name)
|
|
rows = []
|
|
for p in (imgs[:limit] if limit else imgs):
|
|
digest = ""
|
|
try:
|
|
digest = sha256_file(p)
|
|
if digest in cache:
|
|
cached = cache[digest]
|
|
rows.append({**cached, "file": str(p), "filename": p.name,
|
|
"reused_from": cached.get("filename")})
|
|
continue
|
|
res = analyze_image(str(p), expected_name=name, mark_dir=mark_dir,
|
|
extra_passes=extra_passes, fast=fast)
|
|
cache[digest] = res
|
|
rows.append(res)
|
|
logger.info("%s/%s 完成:%.1fs id=%s card=%s", d.name, p.name,
|
|
res.get("elapsed_s", 0),
|
|
res.get("id_card", {}).get("number") or "-",
|
|
res.get("bank_card", {}).get("number") or "-")
|
|
except Exception as e: # noqa: BLE001
|
|
logger.exception("识别失败:%s", p)
|
|
rows.append({"file": str(p), "filename": p.name, "ok": False,
|
|
"sha256": digest, "error": f"{type(e).__name__}: {e}"})
|
|
persons.append(_merge_person(d.name, name, rows))
|
|
return persons
|
|
|
|
|
|
def _merge_person(folder_name: str, expected_name: str, rows: List[dict]) -> dict:
|
|
ok_rows = [r for r in rows if r.get("ok", True) and "id_card" in r]
|
|
hashes = {r.get("sha256") for r in ok_rows if r.get("sha256")}
|
|
|
|
def best(key: str, prefer: str) -> dict:
|
|
# 号码没识别出来,但卡面银行名 / 身份证姓名读到了,也要保留(交叉核对时有用)
|
|
items = [r[key] for r in ok_rows
|
|
if r.get(key, {}).get("found") or r.get(key, {}).get("bank")
|
|
or r.get(key, {}).get("name")]
|
|
if not items:
|
|
return {}
|
|
rank = {"high": 3, "medium": 2, "low": 1}
|
|
|
|
def score(d: dict) -> tuple:
|
|
return (1 if d.get(prefer) else 0, rank.get(d.get("confidence"), 0),
|
|
max([c.get("score", 0) for c in d.get("candidates", [])] or [0]))
|
|
|
|
return max(items, key=score)
|
|
|
|
id_best = best("id_card", "checksum_ok")
|
|
bank_best = best("bank_card", "luhn_ok")
|
|
flags: List[str] = []
|
|
if len(ok_rows) < 2:
|
|
flags.append("missing_one_photo")
|
|
if len(hashes) == 1 and len(ok_rows) >= 2:
|
|
flags.append("duplicate_photo")
|
|
# 只按「人」的最终结果判定字段问题,不把「这张图没拍到身份证」当成整人的问题
|
|
if not id_best.get("number"):
|
|
flags.append("id_not_found")
|
|
elif not id_best.get("checksum_ok"):
|
|
flags.append("id_checksum_fail")
|
|
elif expected_name and id_best.get("name") and id_best["name"] != expected_name:
|
|
flags.append("id_name_mismatch")
|
|
if not bank_best.get("number"):
|
|
flags.append("card_not_found")
|
|
elif not bank_best.get("luhn_ok"):
|
|
flags.append("card_luhn_fail")
|
|
elif bank_best.get("length") not in (16, 18, 19):
|
|
flags.append("card_length_odd")
|
|
# 图像质量类问题才从单图冒泡上来
|
|
for r in ok_rows:
|
|
for f in r.get("flags", []):
|
|
if f in ("low_resolution", "rotated_90", "rotated_180", "rotated_270",
|
|
"card_not_located", "multiple_cards_in_photo") and f not in flags:
|
|
flags.append(f)
|
|
|
|
return {
|
|
"folder": folder_name, "expected_name": expected_name,
|
|
"files": [{"filename": r.get("filename"), "sha256": (r.get("sha256") or "")[:16],
|
|
"layout": r.get("layout"), "flags": r.get("flags", [])} for r in rows],
|
|
"id_card": id_best, "bank_card": bank_best,
|
|
"duplicate_photo": len(hashes) == 1 and len(ok_rows) >= 2,
|
|
"flags": flags,
|
|
"raw": ok_rows,
|
|
}
|
|
|
|
|
|
def _disp_width(s: str) -> int:
|
|
import unicodedata # noqa: PLC0415
|
|
|
|
return sum(2 if unicodedata.east_asian_width(c) in ("W", "F") else 1 for c in str(s))
|
|
|
|
|
|
def _pad(s: str, width: int) -> str:
|
|
s = str(s)
|
|
return s + " " * max(1, width - _disp_width(s))
|
|
|
|
|
|
def summary_table(persons: Sequence[dict]) -> str:
|
|
head = (_pad("姓名", 9) + _pad("身份证号", 22) + _pad("校验", 5) + _pad("银行卡号", 24)
|
|
+ _pad("Luhn", 6) + _pad("发卡行", 20) + "标记")
|
|
lines = [head, "-" * 104]
|
|
for p in persons:
|
|
idc, bk = p.get("id_card", {}), p.get("bank_card", {})
|
|
lines.append(
|
|
_pad(p.get("folder", ""), 9)
|
|
+ _pad(idc.get("number") or "-", 22)
|
|
+ _pad("✓" if idc.get("checksum_ok") else "✗", 5)
|
|
+ _pad(bk.get("number") or "-", 24)
|
|
+ _pad("✓" if bk.get("luhn_ok") else "✗", 6)
|
|
+ _pad(bk.get("bank") or "-", 20)
|
|
+ ",".join(p.get("flags", [])))
|
|
return "\n".join(lines)
|
|
|