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

207 lines
6.6 KiB
Python

# -*- coding: utf-8 -*-
"""OCR 引擎封装(RapidOCR / onnxruntime,纯离线,模型随包)。"""
from __future__ import annotations
import logging
import threading
from dataclasses import dataclass
from typing import Iterable, List, Optional
import numpy as np
logger = logging.getLogger("cardocr")
_ENGINE = None
_LOCK = threading.Lock()
@dataclass
class Line:
"""一段识别文本 + 图内像素框。"""
text: str
left: int
top: int
width: int
height: int
score: float
@property
def right(self) -> int:
return self.left + self.width
@property
def bottom(self) -> int:
return self.top + self.height
@property
def x_mid(self) -> float:
return self.left + self.width / 2.0
@property
def y_mid(self) -> float:
return self.top + self.height / 2.0
def to_dict(self) -> dict:
return {"text": self.text, "left": self.left, "top": self.top,
"width": self.width, "height": self.height,
"score": round(float(self.score), 3)}
def engine_available() -> bool:
try:
import importlib.util # noqa: PLC0415
return importlib.util.find_spec("rapidocr") is not None
except Exception: # noqa: BLE001
return False
def _silence_rapidocr() -> None:
"""把 RapidOCR 自带的控制台日志压到 ERROR。
RapidOCR 在 import 时给 "RapidOCR" logger 挂了 stderr handler,识别不到文字等
WARNING 会直接写 stderr,被执行机当成 ERROR 刷进运行日志(`[ERROR] [WARNING] ...`)。
这里只压掉 WARNING 及以下的噪音,ERROR 仍然保留。
"""
lg = logging.getLogger("RapidOCR")
lg.setLevel(logging.ERROR)
lg.propagate = False
def _get_engine():
global _ENGINE
if _ENGINE is not None:
return _ENGINE
with _LOCK:
if _ENGINE is not None:
return _ENGINE
from rapidocr import RapidOCR # noqa: PLC0415
# 固定线程数:默认会按核数开线程,在共享办公机上反而抖动严重(同一张图 2s~13s)
params = {
"Global.log_level": "ERROR",
"EngineConfig.onnxruntime.intra_op_num_threads": 4,
"EngineConfig.onnxruntime.inter_op_num_threads": 1,
}
try:
_ENGINE = RapidOCR(params=params)
except Exception: # noqa: BLE001 旧版本不支持 params
_ENGINE = RapidOCR()
_silence_rapidocr()
return _ENGINE
def lines(img: np.ndarray, min_score: float = 0.0) -> List[Line]:
"""对一张 BGR / 灰度图做识别,返回按阅读顺序排序的文本行。"""
if img is None or img.size == 0:
return []
if img.ndim == 3:
bgr = img
else:
bgr = np.dstack([img, img, img])
engine = _get_engine()
# 显式给全开关:RapidOCR 会把上次调用的开关记在实例上,写错一次后面全错
out = engine(np.ascontiguousarray(bgr), use_det=True, use_cls=True, use_rec=True)
boxes = getattr(out, "boxes", None)
txts = getattr(out, "txts", None)
scores = getattr(out, "scores", None)
if boxes is None or txts is None:
return []
res: List[Line] = []
for i, (box, text) in enumerate(zip(boxes, txts)):
text = str(text or "").strip()
if not text:
continue
score = float(scores[i]) if scores is not None and i < len(scores) else 1.0
if score < min_score:
continue
pts = np.asarray(box, dtype=np.float32).reshape(-1, 2)
l, t = int(np.floor(pts[:, 0].min())), int(np.floor(pts[:, 1].min()))
r, b = int(np.ceil(pts[:, 0].max())), int(np.ceil(pts[:, 1].max()))
if r <= l or b <= t:
continue
res.append(Line(text=text, left=l, top=t, width=r - l, height=b - t, score=score))
res.sort(key=lambda x: (x.top // 10, x.left))
return res
def text_line(img: np.ndarray) -> str:
"""把「只含一行文字」的裁剪图直接送进识别网络(跳过检测网络,快约 10 倍)。
卡号带这种窄条图只有一行字,检测/分类没有意义,跳过能省掉一次 1~5s 的推理。
"""
if img is None or img.size == 0:
return ""
if img.ndim == 2:
bgr = np.dstack([img, img, img])
else:
bgr = img
engine = _get_engine()
try:
try:
out = engine(np.ascontiguousarray(bgr), use_det=False, use_cls=False)
finally:
# 这两个开关会写进引擎实例,必须恢复,否则后面的整图识别会全部变成「无框」
engine.update_params(use_det=True, use_cls=True, use_rec=True)
except TypeError: # 老版本不支持这些开关
return join_text(lines(img))
except Exception: # noqa: BLE001
return join_text(lines(img))
txts = getattr(out, "txts", None)
if not txts:
return ""
return " ".join(str(t) for t in txts if t)
def join_text(items: List[Line]) -> str:
"""把多行文本拼成一段(换行变空格,便于人看 / 关键词判断,不用于抓号码)。"""
return " ".join(x.text for x in items)
def row_texts(items: List[Line], y_tol: float = 0.75, gap_factor: float = 1.6) -> List[str]:
"""把同一视觉行上的文字框合并成「行文本」,再按横向间距切成若干段。
抓号码必须在「行」粒度上做:整图拼接会把相邻两行的数字连成一个假号码
(例如卡号 5443 后面紧跟有效期里的 2000,会被读成 19 位)。
"""
if not items:
return []
med_h = float(np.median([x.height for x in items]))
clusters: List[List[Line]] = []
for ln in sorted(items, key=lambda x: x.y_mid):
for cl in clusters:
if abs(ln.y_mid - cl[-1].y_mid) <= y_tol * max(med_h, ln.height):
cl.append(ln)
break
else:
clusters.append([ln])
rows: List[str] = []
for cl in clusters:
cl.sort(key=lambda x: x.left)
parts: List[str] = [cl[0].text]
last = cl[0]
for ln in cl[1:]:
if ln.left - last.right <= gap_factor * med_h:
parts[-1] = parts[-1] + " " + ln.text
else:
parts.append(ln.text)
last = ln
rows.extend(parts)
return rows
def row_texts_multi(views: Iterable) -> List[str]:
"""多个视图的行文本汇总(每个视图单独分行,避免跨卡片串号)。"""
out: List[str] = []
for v in views:
out.extend(row_texts(v.lines))
return out
def load(path: str) -> Optional[np.ndarray]:
from .img import imread # noqa: PLC0415
return imread(path)