cardocr(身份证/银行卡分析)与 YOLO 卡面检测模型整体迁入 cardreader,插件不再依赖 desktopauto;常规识别读不出合法卡号时按 balanced→thorough 补读。
284 lines
10 KiB
Python
284 lines
10 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""核心实现:检测卡 → 多视角读取 → 投票 → 输出结论。
|
|
|
|
视角(按开销从低到高):
|
|
full 整图交给 cardreader.cardocr 的 analyze_image(会自己做方向/多遍增强)
|
|
crop 按 YOLO 框裁出来的卡,四个方向各读一次
|
|
band 在卡上按固定位置切号带 + 饱和度掩码 + 多尺度(最慢,专治压印银字)
|
|
|
|
依赖:卡证识别(分析/找卡/OCR/校验)全部内置在 cardreader.cardocr,无外部 SDK 依赖。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import tempfile
|
|
import time
|
|
from collections import Counter
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
|
|
import cv2
|
|
import numpy as np
|
|
import onnxruntime as ort
|
|
|
|
from .cardocr.cards import locate_bank_card
|
|
from .cardocr.engine import text_line
|
|
from .cardocr.img import apply_exif, imread, rotate90
|
|
from .cardocr.pipeline import analyze_image
|
|
from .cardocr.validators import digitize, luhn_ok
|
|
|
|
_HERE = Path(__file__).resolve().parent
|
|
MODEL = _HERE / "models" / "xq0084_card.onnx"
|
|
N = 512
|
|
CONF = 0.25
|
|
IOU = 0.5
|
|
CLS = {0: "bank_card", 1: "id_card"}
|
|
|
|
__all__ = ["Result", "read_card", "detect"]
|
|
|
|
|
|
@dataclass
|
|
class Result:
|
|
number: str = ""
|
|
luhn_ok: bool = False
|
|
confidence: str = "low" # high / medium / low
|
|
needs_review: bool = True
|
|
votes: int = 0
|
|
source: str = ""
|
|
elapsed: float = 0.0
|
|
boxes: list = field(default_factory=list)
|
|
kinds: list = field(default_factory=list) # 检出的卡片类别:bank_card / id_card
|
|
views: dict = field(default_factory=dict)
|
|
|
|
def to_dict(self) -> dict:
|
|
return {"number": self.number, "luhn_ok": self.luhn_ok,
|
|
"confidence": self.confidence, "needs_review": self.needs_review,
|
|
"votes": self.votes, "source": self.source,
|
|
"elapsed": round(self.elapsed, 2),
|
|
"boxes": self.boxes, "kinds": self.kinds, "views": self.views}
|
|
|
|
|
|
_SESS = None
|
|
|
|
|
|
def _session():
|
|
global _SESS
|
|
if _SESS is None:
|
|
if not MODEL.is_file():
|
|
raise FileNotFoundError(f"缺少检测模型:{MODEL}")
|
|
_SESS = ort.InferenceSession(str(MODEL), providers=["CPUExecutionProvider"])
|
|
return _SESS
|
|
|
|
|
|
def _letterbox(img):
|
|
h, w = img.shape[:2]
|
|
r = min(N / w, N / h)
|
|
nw, nh = int(round(w * r)), int(round(h * r))
|
|
canvas = np.full((N, N, 3), 114, np.uint8)
|
|
dx, dy = (N - nw) // 2, (N - nh) // 2
|
|
canvas[dy:dy + nh, dx:dx + nw] = cv2.resize(img, (nw, nh))
|
|
return canvas, r, dx, dy
|
|
|
|
|
|
def _nms(boxes, scores, thr=IOU):
|
|
order = scores.argsort()[::-1]
|
|
keep = []
|
|
while order.size:
|
|
i = int(order[0])
|
|
keep.append(i)
|
|
if order.size == 1:
|
|
break
|
|
rest = order[1:]
|
|
xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
|
|
yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
|
|
xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
|
|
yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
|
|
inter = np.clip(xx2 - xx1, 0, None) * np.clip(yy2 - yy1, 0, None)
|
|
a1 = (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
|
|
a2 = (boxes[rest, 2] - boxes[rest, 0]) * (boxes[rest, 3] - boxes[rest, 1])
|
|
iou = inter / np.maximum(a1 + a2 - inter, 1e-9)
|
|
order = rest[iou <= thr]
|
|
return keep
|
|
|
|
|
|
def detect(img):
|
|
"""检测图中的银行卡/身份证框。返回 [{"cls","conf","box":[x1,y1,x2,y2]}, ...]。"""
|
|
sess = _session()
|
|
canvas, r, dx, dy = _letterbox(img)
|
|
x = canvas[:, :, ::-1].transpose(2, 0, 1)[None].astype(np.float32) / 255.0
|
|
out = sess.run(None, {sess.get_inputs()[0].name: x})[0][0].T
|
|
scores = out[:, 4:]
|
|
cls = scores.argmax(1)
|
|
conf = scores.max(1)
|
|
m = conf >= CONF
|
|
out, cls, conf = out[m], cls[m], conf[m]
|
|
if not len(out):
|
|
return []
|
|
b = out[:, :4]
|
|
boxes = np.stack([b[:, 0] - b[:, 2] / 2, b[:, 1] - b[:, 3] / 2,
|
|
b[:, 0] + b[:, 2] / 2, b[:, 1] + b[:, 3] / 2], 1)
|
|
boxes = (boxes - np.array([dx, dy, dx, dy])) / r
|
|
res = []
|
|
for c in np.unique(cls):
|
|
idx = np.where(cls == c)[0]
|
|
for k in _nms(boxes[idx], conf[idx]):
|
|
j = idx[k]
|
|
res.append({"cls": CLS.get(int(c), str(c)), "conf": float(conf[j]),
|
|
"box": [float(v) for v in boxes[j]]})
|
|
res.sort(key=lambda d: -d["conf"])
|
|
return res
|
|
|
|
|
|
def crop_card(img, box, pad=0.02):
|
|
h, w = img.shape[:2]
|
|
x1, y1, x2, y2 = box
|
|
px, py = (x2 - x1) * pad, (y2 - y1) * pad
|
|
x1, y1 = int(max(0, x1 - px)), int(max(0, y1 - py))
|
|
x2, y2 = int(min(w, x2 + px)), int(min(h, y2 + py))
|
|
if x2 - x1 < 8 or y2 - y1 < 8:
|
|
return None
|
|
return img[y1:y2, x1:x2]
|
|
|
|
|
|
def _analyze(path: Path, fast: bool):
|
|
r = analyze_image(str(path), fast=fast)
|
|
bc = r.get("bank_card") or {}
|
|
return (bc.get("number") or ""), bool(bc.get("luhn_ok"))
|
|
|
|
|
|
def _band_reads(card: np.ndarray, scales=(2.0, 3.0)):
|
|
"""固定号带 + 饱和度掩码(低 V 阈值)+ 多尺度,返回候选列表。"""
|
|
out = []
|
|
H, W = card.shape[:2]
|
|
for y0 in (0.45, 0.50, 0.55, 0.60, 0.65, 0.70):
|
|
band = card[int(y0 * H):int(min(H, (y0 + 0.17) * H)), int(0.04 * W):int(0.94 * W)]
|
|
if band.size == 0:
|
|
continue
|
|
hsv = cv2.cvtColor(band, cv2.COLOR_BGR2HSV)
|
|
_, s, v = cv2.split(hsv)
|
|
for st, vt in ((70, 80), (85, 95), (75, 110), (85, 120)):
|
|
m = ((s < st) & (v > vt)).astype(np.uint8) * 255
|
|
m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
|
|
for sc in scales:
|
|
big = cv2.resize(m, None, fx=sc, fy=sc, interpolation=cv2.INTER_CUBIC)
|
|
d, _ = digitize(text_line(big))
|
|
for n in (16, 19):
|
|
for i in range(len(d) - n + 1):
|
|
w = d[i:i + n]
|
|
if w.startswith("62") and luhn_ok(w):
|
|
out.append(w)
|
|
return out
|
|
|
|
|
|
def _read_strip(img: np.ndarray):
|
|
"""整张图本身就像"号带"(很扁)时,直接只跑识别,不找卡。"""
|
|
out = []
|
|
for k in (0, 2):
|
|
im = rotate90(img, k) if k else img
|
|
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) if im.ndim == 3 else im
|
|
for base_img in (im, gray):
|
|
for sc in (1.0, 2.0):
|
|
big = cv2.resize(base_img, None, fx=sc, fy=sc,
|
|
interpolation=cv2.INTER_CUBIC) if sc != 1.0 else base_img
|
|
d, _ = digitize(text_line(big))
|
|
if len(d) in (16, 19) and d.startswith("62") and luhn_ok(d):
|
|
out.append(d) # 整串就是合法卡号,优先
|
|
continue
|
|
for n in (16, 19):
|
|
for i in range(len(d) - n + 1):
|
|
w = d[i:i + n]
|
|
if w.startswith("62") and luhn_ok(w):
|
|
out.append(w)
|
|
return out
|
|
|
|
|
|
def read_card(path, mode: str = "balanced") -> Result:
|
|
"""识别一张照片里的银行卡号。
|
|
|
|
mode:
|
|
fast 整图快读 + 卡框四向(~1s)
|
|
balanced 再加慢读兜底(默认,~3s)
|
|
thorough 再加号带掩码密集搜索(~10s)
|
|
"""
|
|
t0 = time.time()
|
|
p = Path(path)
|
|
img = apply_exif(imread(str(p)), str(p))
|
|
dets = detect(img)
|
|
banks = [d for d in dets if d["cls"] == "bank_card"]
|
|
res = Result(boxes=[d["box"] for d in dets], kinds=[d["cls"] for d in dets])
|
|
votes: Counter = Counter()
|
|
luhn_votes: Counter = Counter()
|
|
views: dict = {}
|
|
|
|
def add(view: str, num: str, ok: bool):
|
|
if num:
|
|
votes[num] += 1
|
|
if ok:
|
|
luhn_votes[num] += 1
|
|
views[view] = num
|
|
|
|
add("full_fast", *_analyze(p, True))
|
|
if mode != "fast" and not votes:
|
|
add("full_slow", *_analyze(p, False))
|
|
|
|
# 整图本身就是号带(很扁)→ 只走条带识别,不找卡、不裁切
|
|
h0, w0 = img.shape[:2]
|
|
if max(w0, h0) / max(1, min(w0, h0)) >= 4:
|
|
first = next(iter(_read_strip(img)), "")
|
|
if first:
|
|
for _ in range(3):
|
|
add("strip", first, True)
|
|
res.views = views
|
|
num, cnt = (luhn_votes or votes).most_common(1)[0] if votes else ("", 0)
|
|
if num:
|
|
res.number, res.votes, res.luhn_ok = num, cnt, luhn_ok(num)
|
|
res.source = ",".join(k for k, v in views.items() if v == num)
|
|
if res.luhn_ok and cnt >= 2:
|
|
res.confidence, res.needs_review = "high", False
|
|
elif res.luhn_ok:
|
|
res.confidence, res.needs_review = "medium", False
|
|
else:
|
|
res.confidence, res.needs_review = "low", True
|
|
res.elapsed = time.time() - t0
|
|
return res
|
|
|
|
if banks:
|
|
crop = crop_card(img, banks[0]["box"])
|
|
if crop is not None and crop.size:
|
|
tmp = Path(tempfile.gettempdir()) / f"_cr_{os.getpid()}.png"
|
|
for k in range(4):
|
|
rot = rotate90(crop, k)
|
|
ok, buf = cv2.imencode(".png", rot)
|
|
tmp.write_bytes(buf.tobytes())
|
|
add(f"crop_r{k * 90}", *_analyze(tmp, True))
|
|
if mode != "fast" and not votes:
|
|
add("crop_slow", *_analyze(tmp, False))
|
|
if mode == "thorough":
|
|
base = locate_bank_card(crop)
|
|
card = base if base is not None else crop
|
|
if card.shape[0] > card.shape[1]:
|
|
card = cv2.rotate(card, cv2.ROTATE_90_CLOCKWISE)
|
|
for k in range(4):
|
|
for n in _band_reads(rotate90(card, k)):
|
|
add("band", n, True)
|
|
|
|
if votes:
|
|
# 优先 Luhn 通过且票数最高的
|
|
pool = luhn_votes or votes
|
|
num, cnt = pool.most_common(1)[0]
|
|
res.number = num
|
|
res.votes = cnt
|
|
res.luhn_ok = luhn_ok(num)
|
|
res.source = ",".join(k for k, v in views.items() if v == num)
|
|
if res.luhn_ok and cnt >= 2:
|
|
res.confidence, res.needs_review = "high", False
|
|
elif res.luhn_ok:
|
|
res.confidence, res.needs_review = "medium", False
|
|
else:
|
|
res.confidence, res.needs_review = "low", True
|
|
if len(pool) > 1 and pool.most_common(2)[0][1] == pool.most_common(2)[1][1]:
|
|
res.needs_review = True # 两个号票数相同,人工确认
|
|
res.views = views
|
|
res.elapsed = time.time() - t0
|
|
return res
|