Files
37duAutomation/libs/cardreader/cardreader/cardocr/enhance.py
T
puddy 675e62dbad feat(cardreader): 新增自包含卡证识别 SDK,XQ0084 改用它读卡号
cardocr(身份证/银行卡分析)与 YOLO 卡面检测模型整体迁入 cardreader,插件不再依赖 desktopauto;常规识别读不出合法卡号时按 balanced→thorough 补读。
2026-11-23 10:26:10 +08:00

521 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""浮雕/反光银行卡号增强识别(卡号带定位 + 4 位分组识别 + Luhn 裁决)。
为什么单独一层:普通整图 OCR 会把 16 位卡号当成「一行长文本」送进识别网络,
而识别网络输入宽度有限(约 320px),16 位挤在一起每个字只剩十几像素,必然丢字;
浮雕数字(卡面暗、字是同色凸起)又会和背景花纹混在一起,检测网络经常直接看不见。
这一层不改模型,只改「怎么喂」:
1. 用 MSER 找到「一排字高一致的大字」,定位卡号带(它比背景花纹更成块);
多行候选按「跨度 + 字高」排序,再用一次便宜的试读挑出真正能读出 4 位的那条;
2. 按卡片宽度先验把卡号带切成 4 组,每组左右微调,挑「能稳定读出 4 位」的窗口;
3. 每组在多路增强(灰度/均衡/CLAHE/梯度/形态学梯度)上各识别一次,逐位投票;
4. 用 Luhn + 位数 + BIN/卡面银行 做裁决;投票有分歧时在「易混数字」里做
代价递增的有限搜索,只返回通过 Luhn 的候选,并按「改动代价」排序。
原则:宁可返回候选 + 需人工,也不硬猜一个通过不了校验的号码。
"""
from __future__ import annotations
import logging
import time
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Sequence, Tuple
import cv2
import numpy as np
from .engine import text_line
from .img import imread, to_gray
from .validators import bin_bank, digitize, luhn_ok, prefix_ok
logger = logging.getLogger("cardocr")
# 卡号带的 y 区间先验(标准卡面比例):卡号一般在卡高 40%~92% 处(含拍歪/留白)
_BAND_Y_RATIO = (0.40, 0.92)
# 卡号横向跨度先验(占卡宽比例),按可能性排序;主假设失败才试后面的
_SPAN_RATIOS = ((0.045, 0.955), (0.060, 0.920), (0.075, 0.900))
# 分组窗口的左右微调量(相对组宽)
_OFFSETS = (0.0, 0.10, -0.10, 0.20, -0.20)
# 识别通路:灰度 / 全局均衡 / CLAHE / 梯度 / 形态学梯度(后两者对浮雕边缘最敏感)
_VARIANTS = ("gray", "eq", "clahe", "grad", "morph")
_PROBE = ("eq", "morph") # 挑窗口时只跑这两路,省时间
_MAX_CANDIDATES = 5
_MAX_COST = 5 # 候选最多容许的「改动代价」总和
_MAX_NODES = 300000 # 搜索节点上限,防病态图卡死
_MAX_BANDS = 3
# 浮雕数字的易混对:反光会把 6 认成 8、0 认成 9、7 认成 2、5 认成 6
_EMBOSS_CONFUSION: Dict[str, str] = {
"0": "089", "1": "17", "2": "27", "3": "38", "4": "4",
"5": "56", "6": "658", "7": "712", "8": "8630", "9": "904",
}
@dataclass
class GroupRead:
"""一个 4 位分组的识别情况。"""
rect: Tuple[int, int, int, int] # x1, y1, x2, y2
offset: float # 相对基线的微调量(组宽倍数)
reads: Dict[str, str] = field(default_factory=dict) # 通路 → 数字串
digits: str = "" # 逐位投票结果
votes: List[Dict[str, int]] = field(default_factory=list)
def options(self, i: int) -> List[Tuple[str, int, int]]:
"""第 i 位的候选 (数字, 改动代价, 票数),按「代价低、票数高」排序。"""
votes = self.votes[i] if i < len(self.votes) else {}
if not votes:
return [(d, 3, 0) for d in "0123456789"]
top = max(votes.items(), key=lambda kv: (kv[1], kv[0]))[0]
alts = _EMBOSS_CONFUSION.get(top, top)
pool = set(votes) | set(alts) | {top}
out: List[Tuple[str, int, int]] = []
for d in pool:
if d == top:
cost = 0
elif d in votes:
cost = 1
elif d in alts:
cost = 2
else:
cost = 3
out.append((d, cost, votes.get(d, 0)))
out.sort(key=lambda o: (o[1], -o[2], o[0]))
return out
def to_dict(self) -> dict:
return {"rect": list(self.rect), "offset": round(self.offset, 3),
"digits": self.digits, "reads": self.reads,
"votes": [dict(v) for v in self.votes]}
@dataclass
class NumberReading:
number: str = ""
luhn_ok: bool = False
length: int = 0
bank: str = ""
confidence: str = "low" # high / medium / low
status: str = "failed" # ok / candidate / failed
band: Tuple[int, int, int, int] = (0, 0, 0, 0)
groups: List[GroupRead] = field(default_factory=list)
candidates: List[dict] = field(default_factory=list)
elapsed_s: float = 0.0
def to_dict(self) -> dict:
return {"number": self.number, "luhn_ok": self.luhn_ok,
"length": self.length, "bank": self.bank,
"confidence": self.confidence, "status": self.status,
"band": list(self.band),
"groups": [g.to_dict() for g in self.groups],
"candidates": self.candidates,
"elapsed_s": round(self.elapsed_s, 2)}
# ---------------------------------------------------------------- 卡号带定位
def _mser_boxes(gray: np.ndarray) -> List[Tuple[int, int, int, int]]:
h, w = gray.shape[:2]
mser = cv2.MSER_create()
mser.setMinArea(max(800, int(h * w * 0.0004)))
mser.setMaxArea(int(h * w * 0.08))
mser.setDelta(5)
try:
_, bboxes = mser.detectRegions(gray)
except cv2.error: # 个别 OpenCV 构建没编 MSER
return []
boxes: List[Tuple[int, int, int, int]] = []
for (x, y, bw, bh) in bboxes:
if bh < h * 0.030 or bh > h * 0.130:
continue
if bw < bh * 0.15 or bw > bh * 1.80:
continue
boxes.append((int(x), int(y), int(bw), int(bh)))
# MSER 会对同一个字给出多个尺度,按中心点去重(保留面积最大的)
boxes.sort(key=lambda b: -b[2] * b[3])
keep: List[Tuple[int, int, int, int]] = []
tol = max(12, int(min(h, w) * 0.02))
for b in boxes:
cx, cy = b[0] + b[2] / 2.0, b[1] + b[3] / 2.0
if any(abs(cx - (k[0] + k[2] / 2.0)) < tol
and abs(cy - (k[1] + k[3] / 2.0)) < tol for k in keep):
continue
keep.append(b)
return keep
def _cluster_rows(boxes: Sequence[Tuple[int, int, int, int]]):
if not boxes:
return []
items = sorted(boxes, key=lambda b: b[1] + b[3] / 2.0)
rows: List[List[Tuple[int, int, int, int]]] = []
for b in items:
yc = b[1] + b[3] / 2.0
for row in rows:
ref_c = float(np.median([x[1] + x[3] / 2.0 for x in row]))
ref_h = float(np.median([x[3] for x in row]))
if abs(yc - ref_c) < ref_h * 0.60 and 0.55 < b[3] / ref_h < 1.8:
row.append(b)
break
else:
rows.append([b])
return rows
def find_number_bands(gray: np.ndarray, limit: int = _MAX_BANDS
) -> List[Tuple[int, int, int, int]]:
"""定位卡号带的若干候选(按可能性排序),返回 [(x1, y1, x2, y2), ...]。
返回的 x 跨度是 MSER 行自己的实际范围(不再写死整图 3%~97%),
这样卡片没占满画面、或者只是裁出来的卡图,分组窗口都能对得上。
"""
if gray is None or gray.size == 0:
return []
h, w = gray.shape[:2]
scale = 1400.0 / max(h, w)
small = gray if scale >= 1.0 else cv2.resize(gray, None, fx=scale, fy=scale,
interpolation=cv2.INTER_AREA)
rows = _cluster_rows(_mser_boxes(small))
scraped = []
for row in rows:
if len(row) < 3:
continue
x1 = min(b[0] for b in row)
x2 = max(b[0] + b[2] for b in row)
span = (x2 - x1) / float(small.shape[1])
if span < 0.45:
continue
yc = float(np.median([b[1] + b[3] / 2.0 for b in row])) / small.shape[0]
if not (_BAND_Y_RATIO[0] <= yc <= _BAND_Y_RATIO[1]):
continue
med_h = float(np.median([b[3] for b in row]))
score = 2.0 * span + min(len(row), 12) / 12.0 + 12.0 * (med_h / small.shape[0])
scraped.append((score, float(np.median([b[1] + b[3] / 2.0 for b in row])), med_h,
float(x1), float(x2)))
scraped.sort(key=lambda x: -x[0])
inv = 1.0 / scale if scale < 1.0 else 1.0
out: List[Tuple[int, int, int, int]] = []
centers: List[float] = []
for _score, yc_s, med_h_s, x1_s, x2_s in scraped:
yc, med_h = yc_s * inv, med_h_s * inv
if any(abs(yc - c) < max(med_h * 0.6, 8) for c in centers):
continue
# 卡号字高一般占卡高 6%~9%;MSER 常把上下花纹并进来,这里收到上限,避免竖条太高
half = min(med_h * 0.70, h * 0.050)
half = max(half, h * 0.030)
y1 = max(0, int(yc - half))
y2 = min(h, int(yc + half))
# x 跨度用 MSER 行自己的实际范围(原来写死 3%~97%,卡片没占满画面时分组窗口会整体错位)
x1, x2 = int(x1_s * inv), int(x2_s * inv)
pad = max(4, int((x2 - x1) * 0.04))
out.append((max(0, x1 - pad), y1, min(w, x2 + pad), y2))
centers.append(yc)
if len(out) >= limit:
break
return out
# ---------------------------------------------------------------- 分组识别
def _variant(name: str, crop: np.ndarray) -> Optional[np.ndarray]:
if name == "gray":
return crop
if name == "eq":
return cv2.equalizeHist(crop)
if name == "clahe":
try:
return cv2.createCLAHE(3.0, (8, 8)).apply(crop)
except Exception: # noqa: BLE001
return cv2.equalizeHist(crop)
if name == "grad":
gx = np.abs(cv2.Sobel(crop, cv2.CV_32F, 1, 0, ksize=3))
gy = np.abs(cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3))
return cv2.normalize(cv2.magnitude(gx, gy), None, 0, 255,
cv2.NORM_MINMAX).astype(np.uint8)
if name == "morph":
big = cv2.resize(crop, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
return cv2.morphologyEx(big, cv2.MORPH_GRADIENT, np.ones((3, 3), np.uint8))
return None
def _read_crop(gray: np.ndarray, rect: Tuple[int, int, int, int],
variants: Sequence[str]) -> Dict[str, str]:
h, w = gray.shape[:2]
x1, y1, x2, y2 = rect
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(w, x2), min(h, y2)
if x2 - x1 < 20 or y2 - y1 < 20:
return {}
crop = gray[y1:y2, x1:x2]
reads: Dict[str, str] = {}
for name in variants:
img = _variant(name, crop)
if img is not None:
reads[name], _ = digitize(text_line(img))
return reads
def _vote(reads: Dict[str, str]) -> Tuple[str, List[Dict[str, int]]]:
"""逐位投票:只采纳「正好 4 位」的识别结果。"""
good = [v for v in reads.values() if len(v) == 4]
votes: List[Dict[str, int]] = [{} for _ in range(4)]
for s in good:
for i, ch in enumerate(s):
votes[i][ch] = votes[i].get(ch, 0) + 1
digits = "".join(
max(v.items(), key=lambda kv: (kv[1], kv[0]))[0] if v else "0" for v in votes)
return digits, votes
def _pick_group(gray: np.ndarray, xa: int, xb: int, y1: int, y2: int) -> GroupRead:
"""在 [xa, xb] 附近微调窗口位置,选出「最像一组 4 位数字」的窗口。"""
gw = max(60, xb - xa)
best_score, best_ratio, best_rect = -1e9, 0.0, (xa, y1, xb, y2)
# 先试基线窗口:形态学梯度能读出 4 位就直接用(多数分组都命中,省一轮扫描)
if len(_read_crop(gray, best_rect, ("morph",)).get("morph", "")) == 4:
g = GroupRead(rect=best_rect, offset=0.0)
g.reads = _read_crop(gray, g.rect, _VARIANTS)
g.digits, g.votes = _vote(g.reads)
return g
for k, ratio in enumerate(_OFFSETS):
d = int(round(gw * ratio))
rect = (xa + d, y1, xb + d, y2)
probe = _read_crop(gray, rect, _PROBE)
exact = sum(1 for v in probe.values() if len(v) == 4)
score = 2.0 * exact - 0.3 * abs(k)
if score > best_score:
best_score, best_ratio, best_rect = score, ratio, rect
if exact >= 2: # 两路都稳定读出同一组 4 位,不用再试别的偏移
break
g = GroupRead(rect=best_rect, offset=best_ratio)
g.reads = _read_crop(gray, g.rect, _VARIANTS)
g.digits, g.votes = _vote(g.reads)
return g
# ---------------------------------------------------------------- 规则裁决
def _search(groups: Sequence[GroupRead], face_bank: str,
budget: int) -> Dict[str, Tuple[int, int]]:
"""在「改动代价 ≤ budget」的范围内搜出所有通过 Luhn 的号码。
代价递增搜索:投票串本身合法(代价 0)或只需改 1~2 位时,解空间很小;
不用 itertools.product 全量展开(歧义位多时是 8^16,必然被截断漏解)。
"""
opts: List[List[Tuple[str, int, int]]] = []
for g in groups:
for i in range(4):
opts.append(g.options(i))
n = len(opts)
found: Dict[str, Tuple[int, int]] = {}
nodes = 0
digits: List[str] = []
def dfs(pos: int, cost: int, votes: int) -> None:
nonlocal nodes
if nodes >= _MAX_NODES:
return
nodes += 1
if pos == n:
num = "".join(digits)
if len(num) not in (16, 18, 19) or not prefix_ok(num) or not luhn_ok(num):
return
bank = bin_bank(num)
if face_bank and bank and bank != face_bank:
return
prev = found.get(num)
if prev is None or (cost, -votes) < (prev[0], -prev[1]):
found[num] = (cost, votes)
return
for d, c, v in opts[pos]:
if cost + c > budget:
continue
digits.append(d)
dfs(pos + 1, cost + c, votes + v)
digits.pop()
dfs(0, 0, 0)
return found
def _resolve(groups: Sequence[GroupRead], face_text: str = "") -> NumberReading:
"""投票结果 → Luhn 裁决 → 排序候选。"""
res = NumberReading()
res.groups = list(groups)
voted = "".join(g.digits for g in groups)
res.number = voted
res.length = len(voted)
face_bank = _bank_from_text(face_text)
found: Dict[str, Tuple[int, int]] = {}
for budget in range(1, _MAX_COST + 1):
found = _search(groups, face_bank, budget)
if found or budget >= 3:
break
ranked = sorted(found.items(), key=lambda kv: (kv[1][0], -kv[1][1], kv[0]))
res.candidates = [{"number": n, "luhn_ok": True, "length": len(n),
"bank": bin_bank(n), "cost": c, "votes": v}
for n, (c, v) in ranked[:_MAX_CANDIDATES]]
if not res.candidates:
res.number = "" # 没有通过校验的解:不返回可疑号码,交由人工
res.status, res.confidence = "failed", "low"
return res
top_num, (top_cost, _) = ranked[0]
res.number = top_num
res.length = len(top_num)
res.luhn_ok = True
res.bank = bin_bank(top_num) or face_bank
# 投票串本身就合法 → 高置信;靠易混枚举纠回来 → 中/低置信(建议人工复核)
if voted == top_num and top_cost == 0:
res.status, res.confidence = "ok", "high"
elif top_cost <= 1:
res.status, res.confidence = "candidate", "medium"
else:
res.status, res.confidence = "candidate", "low"
return res
def _bank_from_text(text: str) -> str:
from .bankcard import _bank_from_face # noqa: PLC0415 避免循环引用
return _bank_from_face(text) if text else ""
# ---------------------------------------------------------------- 对外接口
def _warp_fallback(bgr: np.ndarray) -> Optional[np.ndarray]:
"""整图找不到卡号带时的兜底:按色块/边缘找卡并摆正,失败返回 None。"""
try:
from .cards import locate_bank_card # noqa: PLC0415 避免循环引用
return locate_bank_card(bgr)
except Exception: # noqa: BLE001 兜底链路不允许把主流程带崩
logger.debug("找卡兜底失败", exc_info=True)
return None
def _text_bands(bgr: np.ndarray) -> List[Tuple[int, int, int, int]]:
"""MSER 找不到卡号带时的兜底:用 OCR 检出的数字行定 y、卡宽定 x。
浮雕卡片的数字是「同色凸起」,MSER 经常整行都检测不到;而 OCR 检测网络对
这类卡面仍能框出部分数字(哪怕只读到 4 位),用它定纵向位置更稳。
"""
try:
from .engine import lines as ocr_lines # noqa: PLC0415 避免循环引用
ls = ocr_lines(bgr)
except Exception: # noqa: BLE001
return []
h, w = bgr.shape[:2]
rows = [ln for ln in ls if sum(1 for ch in ln.text if ch.isdigit()) >= 2]
rows.sort(key=lambda ln: -ln.width)
out: List[Tuple[int, int, int, int]] = []
for ln in rows[:2]:
cy = (ln.top + ln.bottom) / 2.0
half = max(24, int(ln.height * 0.75))
out.append((int(w * _SPAN_RATIOS[0][0]), max(0, int(cy - half)),
int(w * _SPAN_RATIOS[0][1]), min(h, int(cy + half))))
return out
def _band_probe(gray: np.ndarray, band: Tuple[int, int, int, int]) -> int:
"""便宜地试读一条带子:只跑 morph 一路,数「正好 4 位」的分组个数。"""
xa, y1, xb, y2 = band
h, w = gray.shape[:2]
if xb - xa < w * 0.6: # 带子比整图窄:按带子自己的跨度切
xa, xb = max(0, xa), min(w, xb)
else:
xa, xb = int(w * _SPAN_RATIOS[0][0]), int(w * _SPAN_RATIOS[0][1])
gw = (xb - xa) / 4.0
good = 0
for i in range(4):
rect = (int(round(xa + gw * i)), y1, int(round(xa + gw * (i + 1))), y2)
v = _read_crop(gray, rect, ("morph",)).get("morph", "")
if len(v) == 4:
good += 1
return good
def _quality(groups: Sequence[GroupRead]) -> int:
"""分组读得干不干净:4 位命中次数 + 每位最高票数(用于在多个跨度假设间选优)。"""
q = 0
for g in groups:
q += 2 * sum(1 for v in g.reads.values() if len(v) == 4)
q += sum(max(v.values()) for v in g.votes if v)
return q
def read_bank_card_number(image, face_text: str = "") -> NumberReading:
"""识别一张卡图上的卡号(浮雕/反光卡兜底用)。
Args:
image: 图片路径,或已读入的 BGR/灰度 ndarray(建议传入已摆正/透视矫正的卡图)。
face_text: 卡面 OCR 文本(含银行名时用于 BIN 交叉校验,如 "招商银行")。
Returns:
NumberReading;`.number` 为最终号码,`.candidates` 为按可信度排序的候选,
`.status` 为 ok / candidate / failed。读不准就返回候选并把 status 置为
candidate/failed,不硬猜。
"""
t0 = time.time()
src = image if isinstance(image, np.ndarray) else imread(str(image))
if src is None or getattr(src, "size", 0) == 0:
return NumberReading(elapsed_s=time.time() - t0)
gray = to_gray(src)
res = NumberReading()
bands = find_number_bands(gray)
if not bands and getattr(src, "ndim", 0) == 3:
# 整图定位不到卡号带(卡没占满画面、拍歪、反光打断):先自动找卡摆正再试
warped = _warp_fallback(src)
if warped is not None:
gray = to_gray(warped)
bands = find_number_bands(gray) or _text_bands(warped)
if not bands and getattr(src, "ndim", 0) == 3:
bands = _text_bands(src)
if not bands:
res.elapsed_s = time.time() - t0
return res
# 用一次便宜试读挑带子:顶部花纹/有效期行通常读不出 4 位
scored = [(_band_probe(gray, b), -i, b) for i, b in enumerate(bands)]
scored.sort(reverse=True)
ordered = [b for s, _, b in scored if s >= 2] or bands
h, w = gray.shape[:2]
best: Optional[NumberReading] = None
best_key = (-1, -1, -1, -1)
for band in ordered[:2]:
bx1, y1, bx2, y2 = band
pad = max(4, int((y2 - y1) * 0.06))
y1, y2 = max(0, y1 - pad), min(h, y2 + pad)
spans = []
if 0 < bx2 - bx1 < w * 0.85:
# 带子明显比整图窄:优先用它自己的实际跨度(卡没占满画面时固定百分比会错位)
pw = max(4, int((bx2 - bx1) * 0.04))
spans.append((max(0, bx1 - pw) / float(w), min(w, bx2 + pw) / float(w)))
spans.extend(_SPAN_RATIOS)
for (ra, rb) in spans:
xa, xb = int(w * ra), int(w * rb)
gw = (xb - xa) / 4.0
groups = [_pick_group(gray, int(round(xa + gw * i)),
int(round(xa + gw * (i + 1))), y1, y2)
for i in range(4)]
cand = _resolve(groups, face_text)
cand.band = band
cand.elapsed_s = time.time() - t0
if cand.status == "ok": # 投票串本身就合法,直接返回
return cand
q = _quality(groups)
key = (q, *_rank(cand))
if best is None or key > best_key:
best, best_key = cand, key
if q >= 12: # 本带已读得很干净,不必再试更窄的跨度
break
assert best is not None
best.elapsed_s = time.time() - t0
return best
def _rank(res: NumberReading) -> Tuple[int, int, int]:
level = {"high": 3, "medium": 2, "low": 1}.get(res.confidence, 0)
min_cost = min([c.get("cost", 9) for c in res.candidates] or [9])
return (1 if res.luhn_ok else 0, level, -min_cost)