Files
37duAutomation/libs/desktopauto/desktopauto/cardocr/cards.py
T
puddy 39b768d0b7 feat(sdk): desktopauto 0.5.3 银行卡/证件 OCR 增强、dingtalk 1.1.0、aitable 0.1.3
- desktopauto:cardocr 引擎/流水线/校验与 ocr 调整,sdk.json/pyproject/版本三处一致
- dingtalk:AI 表格读写与错误封装扩充
- aitable:client/cli/自测与打包配置更新
2026-11-18 18:56:09 +08:00

267 lines
11 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 -*-
"""卡片区域定位:在照片里找出身份证 / 银行卡的四边形,做透视矫正。
一张照片里可能同时有两张卡(很多人把两张卡摆在一起拍),所以返回多个候选。
定位失败时由上层的整图识别兜底,不影响主流程。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional, Sequence, Tuple
import cv2
import numpy as np
from .img import CARD_ASPECT, four_point_warp, order_points, quad_area, to_gray
@dataclass
class CardRegion:
pts: np.ndarray # 4x2 原图坐标
area: float # 像素面积
aspect: float # 长宽比(已归一化到 >=1)
score: float # 越像卡片分越高
warped: Optional[np.ndarray] = None
source: str = "contour" # contour / fallback
def _aspect_score(ar: float) -> float:
"""长宽比越接近 1.585 分越高(身份证、银行卡同尺寸)。"""
if ar <= 0:
return 0.0
# 允许 1.3~1.9 的透视偏差
dev = abs(ar - CARD_ASPECT) / CARD_ASPECT
if dev > 0.28:
return 0.0
return max(0.0, 1.0 - dev / 0.28)
def _rect_score(pts: np.ndarray) -> float:
"""四个角接近直角、对边接近等长的程度。"""
pts = order_points(pts)
sides = []
for i in range(4):
sides.append(float(np.linalg.norm(pts[(i + 1) % 4] - pts[i])))
if min(sides) <= 0:
return 0.0
# 对边长度比
pair_ok = min(sides[0], sides[2]) / max(sides[0], sides[2]) * \
min(sides[1], sides[3]) / max(sides[1], sides[3])
# 直角性:用相邻边点积
ang_ok = 1.0
for i in range(4):
a = pts[(i - 1) % 4] - pts[i]
b = pts[(i + 1) % 4] - pts[i]
cosv = abs(float(np.dot(a, b)) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-9))
ang_ok *= max(0.0, 1.0 - cosv)
return float(max(0.0, pair_ok) * max(0.0, ang_ok) ** 0.25)
def _candidate_quads(gray: np.ndarray) -> List[np.ndarray]:
quads: List[np.ndarray] = []
h, w = gray.shape[:2]
scale = 1000.0 / max(h, w)
if scale < 1.0:
small = cv2.resize(gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
inv = 1.0 / scale
else:
small, inv = gray, 1.0
blur = cv2.GaussianBlur(small, (5, 5), 0)
for lo, hi in ((40, 120), (80, 200)):
edges = cv2.Canny(blur, lo, hi)
edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE,
cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)))
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
area = cv2.contourArea(c)
if area < (small.shape[0] * small.shape[1]) * 0.03:
continue
peri = cv2.arcLength(c, True)
for eps in (0.02, 0.035, 0.05):
ap = cv2.approxPolyDP(c, eps * peri, True)
if len(ap) == 4:
quads.append(np.asarray(ap, dtype=np.float32).reshape(4, 2) * inv)
break
# 面积由小到大的合并去重(同一张卡的多层轮廓只留一个)
return quads
def _dedupe(regions: Sequence[CardRegion], iou_thr: float = 0.6) -> List[CardRegion]:
kept: List[CardRegion] = []
for r in sorted(regions, key=lambda x: -x.score):
dup = False
for k in kept:
# 用外接矩形 IoU 判重
a = cv2.boundingRect(np.asarray(r.pts, dtype=np.int32))
b = cv2.boundingRect(np.asarray(k.pts, dtype=np.int32))
from .img import iou_rect # noqa: PLC0415
if iou_rect(a, b) > iou_thr:
dup = True
break
if not dup:
kept.append(r)
return kept
def find_cards(img: np.ndarray, max_cards: int = 3,
warp_width: int = 0) -> List[CardRegion]:
"""在照片里定位卡片,返回按可信度排序的区域(含透视矫正图)。"""
gray = to_gray(img)
quads = _candidate_quads(gray)
cands: List[CardRegion] = []
for q in quads:
ar_raw = max(quad_area(q), 1e-6)
ar = 0.0
pts = order_points(q)
w1 = float(np.linalg.norm(pts[1] - pts[0]))
w2 = float(np.linalg.norm(pts[2] - pts[3]))
h1 = float(np.linalg.norm(pts[3] - pts[0]))
h2 = float(np.linalg.norm(pts[2] - pts[1]))
ww, hh = (w1 + w2) / 2.0, (h1 + h2) / 2.0
if min(ww, hh) > 0:
ar = max(ww / hh, hh / ww)
score = _aspect_score(ar) * _rect_score(pts)
if score <= 0.05:
continue
cands.append(CardRegion(pts=pts, area=ar_raw, aspect=ar, score=sqrt_(score)))
cands = _dedupe(cands)
out: List[CardRegion] = []
for r in cands[:max_cards]:
r.warped, _ = four_point_warp(img, r.pts, width=warp_width or 0)
out.append(r)
return out
def sqrt_(x: float) -> float:
return float(np.sqrt(max(0.0, x)))
def expand_pts(pts: np.ndarray, ratio: float, shape: Tuple[int, int]) -> np.ndarray:
"""把四边形向外扩一点(卡片边缘会把字裁掉时用)。"""
c = pts.mean(axis=0)
return (pts - c) * (1.0 + ratio) + c
# ---------------------------------------------------------------- 色块兜底定位
# Canny 找四边形要求卡边基本连续,反光/压边/桌面同色时常直接失败(实测有的卡图
# 一张都找不到)。卡面通常是一整块同色区域,所以再补两条更宽松的路子:
# 1) 量化主色相 → 色块掩膜 → 最大轮廓 → 最小外接矩形;
# 2) Canny 边缘闭运算桥接反光断口 → 最大几个轮廓 → 最小外接矩形。
def _mask_card_rects(small: np.ndarray) -> List[Tuple]:
hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)
h, w = small.shape[:2]
sel = (hsv[..., 1] > 60) & (hsv[..., 2] > 25)
if int(sel.sum()) < h * w * 0.02:
return []
hue = hsv[..., 0][sel].astype(np.int32)
hist = np.bincount(hue // 15, minlength=12)[:12]
out: List[Tuple] = []
for t in np.argsort(hist)[::-1][:2]:
if hist[t] < h * w * 0.01:
continue
lo = int(t * 15)
m = cv2.inRange(hsv, (lo, 60, 25), (lo + 14, 255, 255))
m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((41, 41), np.uint8))
m = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((11, 11), np.uint8))
cnts, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if not cnts:
continue
c = max(cnts, key=cv2.contourArea)
if cv2.contourArea(c) < h * w * 0.05:
continue
out.append(cv2.minAreaRect(c))
return out
def _edge_card_rects(small: np.ndarray) -> List[Tuple]:
h, w = small.shape[:2]
edges = cv2.Canny(cv2.GaussianBlur(to_gray(small), (5, 5), 0), 40, 120)
# 大核闭运算把反光造成的断口接上,否则轮廓不闭合
edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, np.ones((15, 15), np.uint8))
cnts, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
out: List[Tuple] = []
for c in sorted(cnts, key=cv2.contourArea, reverse=True)[:5]:
if cv2.contourArea(c) < h * w * 0.05:
continue
out.append(cv2.minAreaRect(c))
return out
def _warp_card(img: np.ndarray, rect: Tuple, width: int) -> np.ndarray:
"""按最小外接矩形矫正,并保证「卡长边 → 图宽」(否则会横拉成瘦长条)。"""
(cx, cy), (rw, rh), ang = rect
box = cv2.boxPoints(((cx, cy), (rw, rh), ang)).astype(np.float32)
pts = order_points(box)
e_w = float(np.linalg.norm(pts[1] - pts[0])) # 将映射到「宽」的那条边
e_h = float(np.linalg.norm(pts[3] - pts[0])) # 将映射到「高」的那条边
if e_w < e_h: # 横边是短边 → 卡长边在竖直方向
pts = np.roll(pts, -1, axis=0)
w = int(width)
h = int(round(width / CARD_ASPECT))
m = cv2.getPerspectiveTransform(
pts, np.float32([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]]))
return cv2.warpPerspective(img, m, (w, h), flags=cv2.INTER_CUBIC)
def find_card_color(img: np.ndarray, warp_width: int = 1712) -> Optional[CardRegion]:
"""色块/边缘兜底找卡(find_cards 失败时用),返回已矫正的卡图。
比例按 85.6:54 还原,长边对应图宽;方向(上下/左右)不在这里判,由调用方
根据 OCR 结果决定,避免再引入一次不可靠的方向猜测。
"""
h, w = img.shape[:2]
scale = 1000.0 / max(h, w)
if scale < 1.0:
small = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
inv = 1.0 / scale
else:
small, inv = img, 1.0
rects = _mask_card_rects(small) + _edge_card_rects(small)
best, best_score = None, 0.0
for rect in rects:
(cx, cy), (rw, rh), ang = rect
if min(rw, rh) <= 0:
continue
# 只按长宽比评分,不奖励面积:边缘法经常把「卡+桌面」框成一个同样比例的大矩形,
# 按面积优选就会选中那个,矫正后的卡反而变小、卡号更难认。
score = _aspect_score(max(rw, rh) / min(rw, rh))
if score > best_score:
best, best_score = rect, score
if best is None:
return None
(cx, cy), (rw, rh), ang = best
rect_full = ((cx * inv, cy * inv), (rw * inv, rh * inv), ang)
pts = order_points(cv2.boxPoints(rect_full).astype(np.float32))
region = CardRegion(pts=pts, area=rw * rh * inv * inv,
aspect=max(rw, rh) / min(rw, rh), score=best_score,
source="color")
region.warped = _warp_card(img, rect_full, warp_width)
return region
def _digit_score(lines) -> int:
n = sum(1 for x in lines for ch in x.text if ch.isdigit())
rows = sum(1 for x in lines if sum(ch.isdigit() for ch in x.text) >= 4)
return n + 5 * rows
def locate_bank_card(img: np.ndarray, warp_width: int = 1712) -> Optional[np.ndarray]:
"""色块兜底找卡 + 用 OCR 结果判方向,返回「摆正的卡图」;找不到返回 None。"""
region = find_card_color(img, warp_width=warp_width)
if region is None or region.warped is None or region.warped.size == 0:
return None
from .engine import lines as ocr_lines # noqa: PLC0415 避免循环引用
card = region.warped
scored = [(_digit_score(ocr_lines(np.ascontiguousarray(np.rot90(card, k)))), k)
for k in (0, 2)]
scored.sort(reverse=True)
if scored[0][0] <= 0: # 0/180 都读不到数字,说明卡是横躺的
scored = [(_digit_score(ocr_lines(np.ascontiguousarray(np.rot90(card, k)))), k)
for k in (1, 3)]
scored.sort(reverse=True)
k = scored[0][1]
return np.ascontiguousarray(np.rot90(card, k))