feat(cardreader): 新增自包含卡证识别 SDK,XQ0084 改用它读卡号
cardocr(身份证/银行卡分析)与 YOLO 卡面检测模型整体迁入 cardreader,插件不再依赖 desktopauto;常规识别读不出合法卡号时按 balanced→thorough 补读。
This commit is contained in:
@@ -0,0 +1,670 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"sdk_id": "cardreader",
|
||||
"version": "0.1.0",
|
||||
"modules": {
|
||||
"cardreader": {
|
||||
"exports": [
|
||||
"Result",
|
||||
"read_card",
|
||||
"detect",
|
||||
"cardocr",
|
||||
"analyze_image",
|
||||
"analyze_folder",
|
||||
"read_bank_card_number",
|
||||
"ocr_card",
|
||||
"ocr_cards"
|
||||
],
|
||||
"all": [
|
||||
"Result",
|
||||
"read_card",
|
||||
"detect",
|
||||
"cardocr",
|
||||
"analyze_image",
|
||||
"analyze_folder",
|
||||
"read_bank_card_number",
|
||||
"ocr_card",
|
||||
"ocr_cards"
|
||||
],
|
||||
"signatures": {
|
||||
"Result": "(number: 'str' = '', luhn_ok: 'bool' = False, confidence: 'str' = 'low', needs_review: 'bool' = True, votes: 'int' = 0, source: 'str' = '', elapsed: 'float' = 0.0, boxes: 'list' = <factory>, kinds: 'list' = <factory>, views: 'dict' = <factory>) -> None",
|
||||
"read_card": "(path, mode: 'str' = 'balanced') -> 'Result'",
|
||||
"detect": "(img)",
|
||||
"analyze_image": "(path: 'str', expected_name: 'str' = '', mark_dir: 'Optional[str]' = None, extra_passes: 'bool' = True, fast: 'bool' = False) -> 'dict'",
|
||||
"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]'",
|
||||
"read_bank_card_number": "(image, face_text: 'str' = '') -> 'NumberReading'",
|
||||
"ocr_card": "(path: 'str', expected_name: 'str' = '', mark_dir: 'Optional[str]' = None, extra_passes: 'bool' = True, fast: 'bool' = False) -> 'dict'",
|
||||
"ocr_cards": "(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]'"
|
||||
}
|
||||
},
|
||||
"cardreader.__main__": {
|
||||
"exports": [
|
||||
"EXTS",
|
||||
"Path",
|
||||
"annotations",
|
||||
"argparse",
|
||||
"csv",
|
||||
"json",
|
||||
"main",
|
||||
"read_card",
|
||||
"sys"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"Path": "(*args, **kwargs)",
|
||||
"main": "() -> 'None'",
|
||||
"read_card": "(path, mode: 'str' = 'balanced') -> 'Result'"
|
||||
}
|
||||
},
|
||||
"cardreader._selftest": {
|
||||
"exports": [
|
||||
"CASES",
|
||||
"Path",
|
||||
"SAMPLE",
|
||||
"annotations",
|
||||
"case",
|
||||
"core",
|
||||
"main",
|
||||
"sys",
|
||||
"tempfile",
|
||||
"traceback"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"Path": "(*args, **kwargs)",
|
||||
"case": "(name: 'str')",
|
||||
"main": "(argv: 'list[str] | None' = None) -> 'int'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr": {
|
||||
"exports": [
|
||||
"analyze_image",
|
||||
"analyze_folder",
|
||||
"check_person",
|
||||
"check_persons",
|
||||
"write_review_workbook",
|
||||
"verify_workbook",
|
||||
"__version__"
|
||||
],
|
||||
"all": [
|
||||
"analyze_image",
|
||||
"analyze_folder",
|
||||
"check_person",
|
||||
"check_persons",
|
||||
"write_review_workbook",
|
||||
"verify_workbook",
|
||||
"__version__"
|
||||
],
|
||||
"signatures": {
|
||||
"analyze_image": "(path: 'str', expected_name: 'str' = '', mark_dir: 'Optional[str]' = None, extra_passes: 'bool' = True, fast: 'bool' = False) -> 'dict'",
|
||||
"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]'",
|
||||
"check_person": "(person: 'dict', truth: 'Dict[str, str]') -> 'dict'",
|
||||
"check_persons": "(persons: 'Sequence[dict]', truth_map: 'Dict[str, Dict[str, str]]') -> 'List[dict]'",
|
||||
"write_review_workbook": "(persons, path, source_root: 'str' = '') -> 'str'",
|
||||
"verify_workbook": "(path: 'str') -> 'dict'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.__main__": {
|
||||
"exports": [
|
||||
"main"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"main": "(argv=None) -> 'int'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.bankcard": {
|
||||
"exports": [
|
||||
"BANK_KEYWORDS",
|
||||
"BANK_NAMES",
|
||||
"BIN_BANK",
|
||||
"BankCardResult",
|
||||
"CardCandidate",
|
||||
"Dict",
|
||||
"Line",
|
||||
"List",
|
||||
"Optional",
|
||||
"Sequence",
|
||||
"annotations",
|
||||
"bin_bank",
|
||||
"card_candidates",
|
||||
"dataclass",
|
||||
"field",
|
||||
"join_text",
|
||||
"looks_like_bank_card",
|
||||
"luhn_ok",
|
||||
"normalize_text",
|
||||
"parse",
|
||||
"re"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"BankCardResult": "(number: 'str' = '', luhn_ok: 'bool' = False, length: 'int' = 0, bank: 'str' = '', bank_source: 'str' = '', expiry: 'str' = '', card_type: 'str' = '', found: 'bool' = False, confidence: 'str' = 'low', evidence: 'List[str]' = <factory>, candidates: 'List[dict]' = <factory>) -> None",
|
||||
"CardCandidate": "(number: 'str', digits: 'int', luhn_ok: 'bool', prefix: 'str' = '', bank: 'str' = '', origin: 'str' = 'raw', edits: 'int' = 0, votes: 'int' = 1, score: 'float' = 0.0) -> None",
|
||||
"Dict": "(*args, **kwargs)",
|
||||
"Line": "(text: 'str', left: 'int', top: 'int', width: 'int', height: 'int', score: 'float') -> None",
|
||||
"List": "(*args, **kwargs)",
|
||||
"Optional": "(*args, **kwds)",
|
||||
"Sequence": "(*args, **kwargs)",
|
||||
"bin_bank": "(no: 'str') -> 'str'",
|
||||
"card_candidates": "(text: 'Union[str, Sequence[str]]', want_lengths: 'Sequence[int]' = (16, 19, 18), limit: 'int' = 8, exclude: 'Sequence[str]' = ()) -> 'List[CardCandidate]'",
|
||||
"dataclass": "(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)",
|
||||
"field": "(*, default=<dataclasses._MISSING_TYPE object at 0xADDR>, default_factory=<dataclasses._MISSING_TYPE object at 0xADDR>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object at 0xADDR>)",
|
||||
"join_text": "(items: 'List[Line]') -> 'str'",
|
||||
"looks_like_bank_card": "(text: 'str') -> 'bool'",
|
||||
"luhn_ok": "(no: 'str') -> 'bool'",
|
||||
"normalize_text": "(text: 'str') -> 'str'",
|
||||
"parse": "(lines: 'Sequence[Line]', full_text: 'str' = '', exclude: 'Sequence[str]' = (), rows: 'Optional[Sequence[str]]' = None) -> 'BankCardResult'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.cards": {
|
||||
"exports": [
|
||||
"CARD_ASPECT",
|
||||
"CardRegion",
|
||||
"List",
|
||||
"Optional",
|
||||
"Sequence",
|
||||
"Tuple",
|
||||
"annotations",
|
||||
"cv2",
|
||||
"dataclass",
|
||||
"expand_pts",
|
||||
"find_card_color",
|
||||
"find_cards",
|
||||
"four_point_warp",
|
||||
"locate_bank_card",
|
||||
"np",
|
||||
"order_points",
|
||||
"quad_area",
|
||||
"sqrt_",
|
||||
"to_gray"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"CardRegion": "(pts: 'np.ndarray', area: 'float', aspect: 'float', score: 'float', warped: 'Optional[np.ndarray]' = None, source: 'str' = 'contour') -> None",
|
||||
"List": "(*args, **kwargs)",
|
||||
"Optional": "(*args, **kwds)",
|
||||
"Sequence": "(*args, **kwargs)",
|
||||
"Tuple": "(*args, **kwargs)",
|
||||
"dataclass": "(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)",
|
||||
"expand_pts": "(pts: 'np.ndarray', ratio: 'float', shape: 'Tuple[int, int]') -> 'np.ndarray'",
|
||||
"find_card_color": "(img: 'np.ndarray', warp_width: 'int' = 1712) -> 'Optional[CardRegion]'",
|
||||
"find_cards": "(img: 'np.ndarray', max_cards: 'int' = 3, warp_width: 'int' = 0) -> 'List[CardRegion]'",
|
||||
"four_point_warp": "(img: 'np.ndarray', pts: 'Sequence[Sequence[float]]', width: 'int' = 0, height: 'int' = 0) -> 'Tuple[np.ndarray, np.ndarray]'",
|
||||
"locate_bank_card": "(img: 'np.ndarray', warp_width: 'int' = 1712) -> 'Optional[np.ndarray]'",
|
||||
"order_points": "(pts: 'Sequence[Sequence[float]]') -> 'np.ndarray'",
|
||||
"quad_area": "(pts: 'np.ndarray') -> 'float'",
|
||||
"sqrt_": "(x: 'float') -> 'float'",
|
||||
"to_gray": "(img: 'np.ndarray') -> 'np.ndarray'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.cli": {
|
||||
"exports": [
|
||||
"Path",
|
||||
"analyze_folder",
|
||||
"analyze_image",
|
||||
"annotations",
|
||||
"argparse",
|
||||
"check_persons",
|
||||
"json",
|
||||
"load_persons",
|
||||
"load_truth_workbook",
|
||||
"logging",
|
||||
"main",
|
||||
"print_report",
|
||||
"print_verify",
|
||||
"summary_table",
|
||||
"sys",
|
||||
"verify_workbook",
|
||||
"write_review_workbook"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"Path": "(*args, **kwargs)",
|
||||
"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]'",
|
||||
"analyze_image": "(path: 'str', expected_name: 'str' = '', mark_dir: 'Optional[str]' = None, extra_passes: 'bool' = True, fast: 'bool' = False) -> 'dict'",
|
||||
"check_persons": "(persons: 'Sequence[dict]', truth_map: 'Dict[str, Dict[str, str]]') -> 'List[dict]'",
|
||||
"load_persons": "(json_path: 'str') -> 'List[dict]'",
|
||||
"load_truth_workbook": "(path: 'str') -> 'Dict[str, Dict[str, str]]'",
|
||||
"main": "(argv=None) -> 'int'",
|
||||
"print_report": "(rows: 'Sequence[dict]') -> 'str'",
|
||||
"print_verify": "(result: 'dict') -> 'None'",
|
||||
"summary_table": "(persons: 'Sequence[dict]') -> 'str'",
|
||||
"verify_workbook": "(path: 'str') -> 'dict'",
|
||||
"write_review_workbook": "(persons: 'Sequence[dict]', path: 'str', source_root: 'str' = '') -> 'str'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.engine": {
|
||||
"exports": [
|
||||
"Iterable",
|
||||
"Line",
|
||||
"List",
|
||||
"Optional",
|
||||
"annotations",
|
||||
"dataclass",
|
||||
"engine_available",
|
||||
"join_text",
|
||||
"lines",
|
||||
"load",
|
||||
"logger",
|
||||
"logging",
|
||||
"np",
|
||||
"row_texts",
|
||||
"row_texts_multi",
|
||||
"text_line",
|
||||
"threading"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"Iterable": "(*args, **kwargs)",
|
||||
"Line": "(text: 'str', left: 'int', top: 'int', width: 'int', height: 'int', score: 'float') -> None",
|
||||
"List": "(*args, **kwargs)",
|
||||
"Optional": "(*args, **kwds)",
|
||||
"dataclass": "(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)",
|
||||
"engine_available": "() -> 'bool'",
|
||||
"join_text": "(items: 'List[Line]') -> 'str'",
|
||||
"lines": "(img: 'np.ndarray', min_score: 'float' = 0.0) -> 'List[Line]'",
|
||||
"load": "(path: 'str') -> 'Optional[np.ndarray]'",
|
||||
"row_texts": "(items: 'List[Line]', y_tol: 'float' = 0.75, gap_factor: 'float' = 1.6) -> 'List[str]'",
|
||||
"row_texts_multi": "(views: 'Iterable') -> 'List[str]'",
|
||||
"text_line": "(img: 'np.ndarray') -> 'str'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.enhance": {
|
||||
"exports": [
|
||||
"Dict",
|
||||
"GroupRead",
|
||||
"List",
|
||||
"NumberReading",
|
||||
"Optional",
|
||||
"Sequence",
|
||||
"Tuple",
|
||||
"annotations",
|
||||
"bin_bank",
|
||||
"cv2",
|
||||
"dataclass",
|
||||
"digitize",
|
||||
"field",
|
||||
"find_number_bands",
|
||||
"imread",
|
||||
"logger",
|
||||
"logging",
|
||||
"luhn_ok",
|
||||
"np",
|
||||
"prefix_ok",
|
||||
"read_bank_card_number",
|
||||
"text_line",
|
||||
"time",
|
||||
"to_gray"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"Dict": "(*args, **kwargs)",
|
||||
"GroupRead": "(rect: 'Tuple[int, int, int, int]', offset: 'float', reads: 'Dict[str, str]' = <factory>, digits: 'str' = '', votes: 'List[Dict[str, int]]' = <factory>) -> None",
|
||||
"List": "(*args, **kwargs)",
|
||||
"NumberReading": "(number: 'str' = '', luhn_ok: 'bool' = False, length: 'int' = 0, bank: 'str' = '', confidence: 'str' = 'low', status: 'str' = 'failed', band: 'Tuple[int, int, int, int]' = (0, 0, 0, 0), groups: 'List[GroupRead]' = <factory>, candidates: 'List[dict]' = <factory>, elapsed_s: 'float' = 0.0) -> None",
|
||||
"Optional": "(*args, **kwds)",
|
||||
"Sequence": "(*args, **kwargs)",
|
||||
"Tuple": "(*args, **kwargs)",
|
||||
"bin_bank": "(no: 'str') -> 'str'",
|
||||
"dataclass": "(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)",
|
||||
"digitize": "(text: 'str') -> 'Tuple[str, List[int]]'",
|
||||
"field": "(*, default=<dataclasses._MISSING_TYPE object at 0xADDR>, default_factory=<dataclasses._MISSING_TYPE object at 0xADDR>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object at 0xADDR>)",
|
||||
"find_number_bands": "(gray: 'np.ndarray', limit: 'int' = 3) -> 'List[Tuple[int, int, int, int]]'",
|
||||
"imread": "(path: 'str') -> 'np.ndarray'",
|
||||
"luhn_ok": "(no: 'str') -> 'bool'",
|
||||
"prefix_ok": "(no: 'str') -> 'bool'",
|
||||
"read_bank_card_number": "(image, face_text: 'str' = '') -> 'NumberReading'",
|
||||
"text_line": "(img: 'np.ndarray') -> 'str'",
|
||||
"to_gray": "(img: 'np.ndarray') -> 'np.ndarray'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.idcard": {
|
||||
"exports": [
|
||||
"Dict",
|
||||
"ID_KEYWORDS",
|
||||
"IdCandidate",
|
||||
"IdCardResult",
|
||||
"Line",
|
||||
"List",
|
||||
"Optional",
|
||||
"Sequence",
|
||||
"annotations",
|
||||
"dataclass",
|
||||
"field",
|
||||
"id_birth",
|
||||
"id_candidates",
|
||||
"id_checksum_ok",
|
||||
"id_gender",
|
||||
"id_plausible",
|
||||
"id_region",
|
||||
"join_text",
|
||||
"looks_like_id",
|
||||
"normalize_text",
|
||||
"parse",
|
||||
"re"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"Dict": "(*args, **kwargs)",
|
||||
"IdCandidate": "(number: 'str', checksum_ok: 'bool', origin: 'str' = 'raw', edits: 'int' = 0, score: 'float' = 0.0) -> None",
|
||||
"IdCardResult": "(number: 'str' = '', checksum_ok: 'bool' = False, birth: 'str' = '', gender: 'str' = '', name: 'str' = '', ethnicity: 'str' = '', address: 'str' = '', issue: 'str' = '', valid_to: 'str' = '', confidence: 'str' = 'low', evidence: 'List[str]' = <factory>, candidates: 'List[dict]' = <factory>, found: 'bool' = False) -> None",
|
||||
"Line": "(text: 'str', left: 'int', top: 'int', width: 'int', height: 'int', score: 'float') -> None",
|
||||
"List": "(*args, **kwargs)",
|
||||
"Optional": "(*args, **kwds)",
|
||||
"Sequence": "(*args, **kwargs)",
|
||||
"dataclass": "(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)",
|
||||
"field": "(*, default=<dataclasses._MISSING_TYPE object at 0xADDR>, default_factory=<dataclasses._MISSING_TYPE object at 0xADDR>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object at 0xADDR>)",
|
||||
"id_birth": "(no: 'str') -> 'str'",
|
||||
"id_candidates": "(text: 'Union[str, Sequence[str]]', limit: 'int' = 8) -> 'List[IdCandidate]'",
|
||||
"id_checksum_ok": "(no: 'str') -> 'bool'",
|
||||
"id_gender": "(no: 'str') -> 'str'",
|
||||
"id_plausible": "(no: 'str') -> 'bool'",
|
||||
"id_region": "(no: 'str') -> 'str'",
|
||||
"join_text": "(items: 'List[Line]') -> 'str'",
|
||||
"looks_like_id": "(text: 'str') -> 'bool'",
|
||||
"normalize_text": "(text: 'str') -> 'str'",
|
||||
"parse": "(lines: 'Sequence[Line]', expected_name: 'str' = '', full_text: 'str' = '', rows: 'Optional[Sequence[str]]' = None) -> 'IdCardResult'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.img": {
|
||||
"exports": [
|
||||
"CARD_ASPECT",
|
||||
"Iterable",
|
||||
"List",
|
||||
"Optional",
|
||||
"Sequence",
|
||||
"Tuple",
|
||||
"annotations",
|
||||
"apply_exif",
|
||||
"cv2",
|
||||
"four_point_warp",
|
||||
"gray_variants",
|
||||
"imread",
|
||||
"iou_rect",
|
||||
"np",
|
||||
"order_points",
|
||||
"os",
|
||||
"quad_area",
|
||||
"resize_side",
|
||||
"rotate90",
|
||||
"to_gray"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"Iterable": "(*args, **kwargs)",
|
||||
"List": "(*args, **kwargs)",
|
||||
"Optional": "(*args, **kwds)",
|
||||
"Sequence": "(*args, **kwargs)",
|
||||
"Tuple": "(*args, **kwargs)",
|
||||
"apply_exif": "(img: 'np.ndarray', path: 'str') -> 'np.ndarray'",
|
||||
"four_point_warp": "(img: 'np.ndarray', pts: 'Sequence[Sequence[float]]', width: 'int' = 0, height: 'int' = 0) -> 'Tuple[np.ndarray, np.ndarray]'",
|
||||
"gray_variants": "(gray: 'np.ndarray', upscale: 'float' = 1.0) -> 'List[Tuple[str, np.ndarray]]'",
|
||||
"imread": "(path: 'str') -> 'np.ndarray'",
|
||||
"iou_rect": "(a: 'Tuple[int, int, int, int]', b: 'Tuple[int, int, int, int]') -> 'float'",
|
||||
"order_points": "(pts: 'Sequence[Sequence[float]]') -> 'np.ndarray'",
|
||||
"quad_area": "(pts: 'np.ndarray') -> 'float'",
|
||||
"resize_side": "(img: 'np.ndarray', max_side: 'int' = 0, min_side: 'int' = 0) -> 'np.ndarray'",
|
||||
"rotate90": "(img: 'np.ndarray', k: 'int') -> 'np.ndarray'",
|
||||
"to_gray": "(img: 'np.ndarray') -> 'np.ndarray'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.match": {
|
||||
"exports": [
|
||||
"Dict",
|
||||
"EXACT",
|
||||
"Iterable",
|
||||
"LABEL",
|
||||
"List",
|
||||
"PARTIAL",
|
||||
"PRIMARY",
|
||||
"STRONG",
|
||||
"Sequence",
|
||||
"Tuple",
|
||||
"WEAK",
|
||||
"annotations",
|
||||
"bin_bank",
|
||||
"check_person",
|
||||
"check_persons",
|
||||
"coverage",
|
||||
"difflib",
|
||||
"digits",
|
||||
"normalize_text",
|
||||
"print_report"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"Dict": "(*args, **kwargs)",
|
||||
"Iterable": "(*args, **kwargs)",
|
||||
"List": "(*args, **kwargs)",
|
||||
"Sequence": "(*args, **kwargs)",
|
||||
"Tuple": "(*args, **kwargs)",
|
||||
"bin_bank": "(no: 'str') -> 'str'",
|
||||
"check_person": "(person: 'dict', truth: 'Dict[str, str]') -> 'dict'",
|
||||
"check_persons": "(persons: 'Sequence[dict]', truth_map: 'Dict[str, Dict[str, str]]') -> 'List[dict]'",
|
||||
"coverage": "(expected: 'str', runs: 'Iterable[str]', card_mode: 'bool' = True, id_digits: 'str' = '') -> 'Tuple[float, str, str]'",
|
||||
"digits": "(text: 'str') -> 'str'",
|
||||
"normalize_text": "(text: 'str') -> 'str'",
|
||||
"print_report": "(rows: 'Sequence[dict]') -> 'str'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.pipeline": {
|
||||
"exports": [
|
||||
"Dict",
|
||||
"IMAGE_EXT",
|
||||
"Line",
|
||||
"List",
|
||||
"Optional",
|
||||
"PRIMARY",
|
||||
"Path",
|
||||
"Sequence",
|
||||
"Tuple",
|
||||
"View",
|
||||
"analyze_folder",
|
||||
"analyze_image",
|
||||
"annotations",
|
||||
"apply_exif",
|
||||
"bankcard",
|
||||
"bline",
|
||||
"card_candidates",
|
||||
"classify",
|
||||
"cv2",
|
||||
"dataclass",
|
||||
"field",
|
||||
"find_cards",
|
||||
"gray_variants",
|
||||
"group_blocks",
|
||||
"hashlib",
|
||||
"id_candidates",
|
||||
"idcard",
|
||||
"idline",
|
||||
"imread",
|
||||
"join_text",
|
||||
"locate_bank_card",
|
||||
"logger",
|
||||
"logging",
|
||||
"normalize_text",
|
||||
"np",
|
||||
"number_runs",
|
||||
"ocr_lines",
|
||||
"os",
|
||||
"resize_side",
|
||||
"rotate90",
|
||||
"row_texts",
|
||||
"rows_of",
|
||||
"sha256_file",
|
||||
"summary_table",
|
||||
"text_line",
|
||||
"time",
|
||||
"to_gray"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"Dict": "(*args, **kwargs)",
|
||||
"Line": "(text: 'str', left: 'int', top: 'int', width: 'int', height: 'int', score: 'float') -> None",
|
||||
"List": "(*args, **kwargs)",
|
||||
"Optional": "(*args, **kwds)",
|
||||
"Path": "(*args, **kwargs)",
|
||||
"Sequence": "(*args, **kwargs)",
|
||||
"Tuple": "(*args, **kwargs)",
|
||||
"View": "(name: 'str', image: 'np.ndarray', source: 'str', rect: 'Tuple[int, int, int, int]', lines: 'List[Line]' = <factory>, text: 'str' = '', kind: 'str' = 'unknown') -> None",
|
||||
"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]'",
|
||||
"analyze_image": "(path: 'str', expected_name: 'str' = '', mark_dir: 'Optional[str]' = None, extra_passes: 'bool' = True, fast: 'bool' = False) -> 'dict'",
|
||||
"apply_exif": "(img: 'np.ndarray', path: 'str') -> 'np.ndarray'",
|
||||
"bline": "(views: 'Sequence[View]', kind: 'str') -> 'List[Line]'",
|
||||
"card_candidates": "(text: 'Union[str, Sequence[str]]', want_lengths: 'Sequence[int]' = (16, 19, 18), limit: 'int' = 8, exclude: 'Sequence[str]' = ()) -> 'List[CardCandidate]'",
|
||||
"classify": "(text: 'str') -> 'str'",
|
||||
"dataclass": "(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)",
|
||||
"field": "(*, default=<dataclasses._MISSING_TYPE object at 0xADDR>, default_factory=<dataclasses._MISSING_TYPE object at 0xADDR>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object at 0xADDR>)",
|
||||
"find_cards": "(img: 'np.ndarray', max_cards: 'int' = 3, warp_width: 'int' = 0) -> 'List[CardRegion]'",
|
||||
"gray_variants": "(gray: 'np.ndarray', upscale: 'float' = 1.0) -> 'List[Tuple[str, np.ndarray]]'",
|
||||
"group_blocks": "(lines: 'Sequence[Line]', max_blocks: 'int' = 12) -> 'List[List[Line]]'",
|
||||
"id_candidates": "(text: 'Union[str, Sequence[str]]', limit: 'int' = 8) -> 'List[IdCandidate]'",
|
||||
"idline": "(views: 'Sequence[View]', kind: 'str') -> 'List[Line]'",
|
||||
"imread": "(path: 'str') -> 'np.ndarray'",
|
||||
"join_text": "(items: 'List[Line]') -> 'str'",
|
||||
"locate_bank_card": "(img: 'np.ndarray', warp_width: 'int' = 1712) -> 'Optional[np.ndarray]'",
|
||||
"normalize_text": "(text: 'str') -> 'str'",
|
||||
"number_runs": "(text: 'str', min_len: 'int' = 6) -> 'List[str]'",
|
||||
"ocr_lines": "(img: 'np.ndarray', min_score: 'float' = 0.0) -> 'List[Line]'",
|
||||
"resize_side": "(img: 'np.ndarray', max_side: 'int' = 0, min_side: 'int' = 0) -> 'np.ndarray'",
|
||||
"rotate90": "(img: 'np.ndarray', k: 'int') -> 'np.ndarray'",
|
||||
"row_texts": "(items: 'List[Line]', y_tol: 'float' = 0.75, gap_factor: 'float' = 1.6) -> 'List[str]'",
|
||||
"rows_of": "(views: 'Sequence[View]', kind: 'str' = '') -> 'List[str]'",
|
||||
"sha256_file": "(p: 'Path') -> 'str'",
|
||||
"summary_table": "(persons: 'Sequence[dict]') -> 'str'",
|
||||
"text_line": "(img: 'np.ndarray') -> 'str'",
|
||||
"to_gray": "(img: 'np.ndarray') -> 'np.ndarray'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.review": {
|
||||
"exports": [
|
||||
"Alignment",
|
||||
"BORDER",
|
||||
"Border",
|
||||
"Dict",
|
||||
"Font",
|
||||
"HEADER_FILL",
|
||||
"IMAGE_COLS",
|
||||
"INPUT_FILL",
|
||||
"List",
|
||||
"Optional",
|
||||
"PERSON_COLS",
|
||||
"PatternFill",
|
||||
"Sequence",
|
||||
"Side",
|
||||
"THIN",
|
||||
"Workbook",
|
||||
"annotations",
|
||||
"get_column_letter",
|
||||
"json",
|
||||
"load_persons",
|
||||
"load_truth_workbook",
|
||||
"load_workbook",
|
||||
"print_verify",
|
||||
"verify_workbook",
|
||||
"write_review_workbook"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"Alignment": "(horizontal=None, vertical=None, textRotation=0, wrapText=None, shrinkToFit=None, indent=0, relativeIndent=0, justifyLastLine=None, readingOrder=0, text_rotation=None, wrap_text=None, shrink_to_fit=None, mergeCell=None)",
|
||||
"Border": "(left=None, right=None, top=None, bottom=None, diagonal=None, diagonal_direction=None, vertical=None, horizontal=None, diagonalUp=False, diagonalDown=False, outline=True, start=None, end=None)",
|
||||
"Dict": "(*args, **kwargs)",
|
||||
"Font": "(name=None, sz=None, b=None, i=None, charset=None, u=None, strike=None, color=None, scheme=None, family=None, size=None, bold=None, italic=None, strikethrough=None, underline=None, vertAlign=None, outline=None, shadow=None, condense=None, extend=None)",
|
||||
"List": "(*args, **kwargs)",
|
||||
"Optional": "(*args, **kwds)",
|
||||
"PatternFill": "(patternType=None, fgColor=<openpyxl.styles.colors.Color object>\nParameters:\nrgb='00000000', indexed=None, auto=None, theme=None, tint=0.0, type='rgb', bgColor=<openpyxl.styles.colors.Color object>\nParameters:\nrgb='00000000', indexed=None, auto=None, theme=None, tint=0.0, type='rgb', fill_type=None, start_color=None, end_color=None)",
|
||||
"Sequence": "(*args, **kwargs)",
|
||||
"Side": "(style=None, color=None, border_style=None)",
|
||||
"Workbook": "(write_only=False, iso_dates=False)",
|
||||
"get_column_letter": "(col_idx)",
|
||||
"load_persons": "(json_path: 'str') -> 'List[dict]'",
|
||||
"load_truth_workbook": "(path: 'str') -> 'Dict[str, Dict[str, str]]'",
|
||||
"load_workbook": "(filename, read_only=False, keep_vba=False, data_only=False, keep_links=True, rich_text=False)",
|
||||
"print_verify": "(result: 'dict') -> 'None'",
|
||||
"verify_workbook": "(path: 'str') -> 'dict'",
|
||||
"write_review_workbook": "(persons: 'Sequence[dict]', path: 'str', source_root: 'str' = '') -> 'str'"
|
||||
}
|
||||
},
|
||||
"cardreader.cardocr.validators": {
|
||||
"exports": [
|
||||
"BIN_BANK",
|
||||
"CardCandidate",
|
||||
"Dict",
|
||||
"IdCandidate",
|
||||
"Iterable",
|
||||
"List",
|
||||
"Optional",
|
||||
"PRIMARY",
|
||||
"Sequence",
|
||||
"Tuple",
|
||||
"Union",
|
||||
"annotations",
|
||||
"bin_bank",
|
||||
"card_candidates",
|
||||
"consensus",
|
||||
"dataclass",
|
||||
"digit_runs",
|
||||
"digitize",
|
||||
"field",
|
||||
"id_birth",
|
||||
"id_candidates",
|
||||
"id_checksum_ok",
|
||||
"id_gender",
|
||||
"id_plausible",
|
||||
"id_region",
|
||||
"luhn_check_digit",
|
||||
"luhn_ok",
|
||||
"normalize_text",
|
||||
"prefix_ok",
|
||||
"re"
|
||||
],
|
||||
"all": [],
|
||||
"signatures": {
|
||||
"CardCandidate": "(number: 'str', digits: 'int', luhn_ok: 'bool', prefix: 'str' = '', bank: 'str' = '', origin: 'str' = 'raw', edits: 'int' = 0, votes: 'int' = 1, score: 'float' = 0.0) -> None",
|
||||
"Dict": "(*args, **kwargs)",
|
||||
"IdCandidate": "(number: 'str', checksum_ok: 'bool', origin: 'str' = 'raw', edits: 'int' = 0, score: 'float' = 0.0) -> None",
|
||||
"Iterable": "(*args, **kwargs)",
|
||||
"List": "(*args, **kwargs)",
|
||||
"Optional": "(*args, **kwds)",
|
||||
"Sequence": "(*args, **kwargs)",
|
||||
"Tuple": "(*args, **kwargs)",
|
||||
"Union": "(*args, **kwds)",
|
||||
"bin_bank": "(no: 'str') -> 'str'",
|
||||
"card_candidates": "(text: 'Union[str, Sequence[str]]', want_lengths: 'Sequence[int]' = (16, 19, 18), limit: 'int' = 8, exclude: 'Sequence[str]' = ()) -> 'List[CardCandidate]'",
|
||||
"consensus": "(numbers: 'Iterable[str]') -> 'List[str]'",
|
||||
"dataclass": "(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)",
|
||||
"digit_runs": "(text: 'str', min_len: 'int' = 13) -> 'List[str]'",
|
||||
"digitize": "(text: 'str') -> 'Tuple[str, List[int]]'",
|
||||
"field": "(*, default=<dataclasses._MISSING_TYPE object at 0xADDR>, default_factory=<dataclasses._MISSING_TYPE object at 0xADDR>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object at 0xADDR>)",
|
||||
"id_birth": "(no: 'str') -> 'str'",
|
||||
"id_candidates": "(text: 'Union[str, Sequence[str]]', limit: 'int' = 8) -> 'List[IdCandidate]'",
|
||||
"id_checksum_ok": "(no: 'str') -> 'bool'",
|
||||
"id_gender": "(no: 'str') -> 'str'",
|
||||
"id_plausible": "(no: 'str') -> 'bool'",
|
||||
"id_region": "(no: 'str') -> 'str'",
|
||||
"luhn_check_digit": "(prefix: 'str') -> 'str'",
|
||||
"luhn_ok": "(no: 'str') -> 'bool'",
|
||||
"normalize_text": "(text: 'str') -> 'str'",
|
||||
"prefix_ok": "(no: 'str') -> 'bool'"
|
||||
}
|
||||
},
|
||||
"cardreader.core": {
|
||||
"exports": [
|
||||
"Result",
|
||||
"read_card",
|
||||
"detect"
|
||||
],
|
||||
"all": [
|
||||
"Result",
|
||||
"read_card",
|
||||
"detect"
|
||||
],
|
||||
"signatures": {
|
||||
"Result": "(number: 'str' = '', luhn_ok: 'bool' = False, confidence: 'str' = 'low', needs_review: 'bool' = True, votes: 'int' = 0, source: 'str' = '', elapsed: 'float' = 0.0, boxes: 'list' = <factory>, kinds: 'list' = <factory>, views: 'dict' = <factory>) -> None",
|
||||
"read_card": "(path, mode: 'str' = 'balanced') -> 'Result'",
|
||||
"detect": "(img)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""cardreader:卡证识别 SDK(自包含)。
|
||||
|
||||
能力:
|
||||
- 身份证 / 银行卡照片分析:`analyze_image` / `analyze_folder`(别名 ocr_card / ocr_cards)
|
||||
- 银行卡号识别(YOLO 卡面定位 + 多视角投票 + 号带掩码,压印银字/反光):`read_card`
|
||||
- 浮雕增强兜底:`read_bank_card_number`
|
||||
- 卡面检测:`detect`;底层工具:`cardocr.match` / `cardocr.validators`
|
||||
|
||||
卡证识别代码与模型全部内置,不依赖其它 SDK。用法:
|
||||
|
||||
from cardreader import read_card
|
||||
r = read_card("photo.jpg")
|
||||
print(r.number, r.luhn_ok, r.confidence, r.needs_review)
|
||||
|
||||
from cardreader import analyze_image
|
||||
print(analyze_image("photo.jpg"))
|
||||
"""
|
||||
from . import cardocr # noqa: F401
|
||||
from .cardocr import analyze_folder, analyze_image
|
||||
from .cardocr.enhance import read_bank_card_number
|
||||
from .core import Result, detect, read_card
|
||||
|
||||
ocr_card = analyze_image
|
||||
ocr_cards = analyze_folder
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__all__ = [
|
||||
"Result", "read_card", "detect",
|
||||
"cardocr", "analyze_image", "analyze_folder",
|
||||
"read_bank_card_number", "ocr_card", "ocr_cards",
|
||||
]
|
||||
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""命令行入口:python -m cardreader <图片> 或 --batch <目录>。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from .core import read_card
|
||||
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(prog="cardreader", description="银行卡号识别")
|
||||
ap.add_argument("image", nargs="?", help="单张图片")
|
||||
ap.add_argument("--batch", help="目录,批量识别")
|
||||
ap.add_argument("--mode", default="balanced", choices=("fast", "balanced", "thorough"))
|
||||
ap.add_argument("--out", help="批量结果写 CSV")
|
||||
ap.add_argument("--json", action="store_true", help="单张时输出 JSON")
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.batch:
|
||||
files = sorted(p for p in Path(args.batch).rglob("*") if p.suffix.lower() in EXTS)
|
||||
rows = []
|
||||
for i, p in enumerate(files, 1):
|
||||
r = read_card(p, mode=args.mode)
|
||||
rows.append({"文件": p.name, "号码": r.number, "Luhn": int(r.luhn_ok),
|
||||
"置信度": r.confidence, "需复核": int(r.needs_review),
|
||||
"票数": r.votes, "耗时": round(r.elapsed, 2)})
|
||||
print(f"[{i}/{len(files)}] {p.name:<34} {r.number or '-':<20} "
|
||||
f"{r.confidence:<7} {'复核' if r.needs_review else ''}", flush=True)
|
||||
out = Path(args.out or "cardreader_result.csv")
|
||||
with open(out, "w", encoding="utf-8-sig", newline="") as f:
|
||||
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
|
||||
w.writeheader()
|
||||
w.writerows(rows)
|
||||
print(f"\n写出 {out}({len(rows)} 条)")
|
||||
return
|
||||
|
||||
if not args.image:
|
||||
ap.print_help()
|
||||
return
|
||||
r = read_card(args.image, mode=args.mode)
|
||||
if args.json:
|
||||
print(json.dumps(r.to_dict(), ensure_ascii=False, indent=2))
|
||||
else:
|
||||
print(f"号码 : {r.number or '-'}")
|
||||
print(f"Luhn : {'通过' if r.luhn_ok else '未通过'}")
|
||||
print(f"置信 : {r.confidence} 需复核: {'是' if r.needs_review else '否'}")
|
||||
print(f"来源 : {r.source or '-'} 票数: {r.votes}")
|
||||
print(f"耗时 : {r.elapsed:.2f}s")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,112 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""离线自测(不联网)。
|
||||
|
||||
覆盖:模型存在性、ONNX 会话可加载、空图不误检、Luhn 校验、合成卡读号、
|
||||
常规通道 analyze_image 可用。
|
||||
|
||||
python -m cardreader._selftest
|
||||
python -m cardreader._selftest -v
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
from . import core
|
||||
|
||||
CASES: list[tuple[str, callable]] = []
|
||||
|
||||
SAMPLE = "6214832377332379"
|
||||
|
||||
|
||||
def case(name: str):
|
||||
def deco(fn: callable):
|
||||
CASES.append((name, fn))
|
||||
return fn
|
||||
return deco
|
||||
|
||||
|
||||
@case("版本与模型:随包模型存在")
|
||||
def _model():
|
||||
assert core.MODEL.is_file(), f"缺少模型:{core.MODEL}"
|
||||
assert core.MODEL.stat().st_size > 1_000_000, core.MODEL.stat().st_size
|
||||
return f"{core.MODEL.stat().st_size / 1024 / 1024:.1f} MB"
|
||||
|
||||
|
||||
@case("ONNX:会话可加载且输入 512x512")
|
||||
def _session():
|
||||
sess = core._session()
|
||||
shape = sess.get_inputs()[0].shape
|
||||
assert list(shape[-2:]) == [core.N, core.N], shape
|
||||
return str(shape)
|
||||
|
||||
|
||||
@case("检测:空白图不误检")
|
||||
def _blank():
|
||||
import numpy as np
|
||||
blank = np.full((480, 640, 3), 200, np.uint8)
|
||||
assert core.detect(blank) == [], core.detect(blank)
|
||||
return "no boxes"
|
||||
|
||||
|
||||
@case("校验:Luhn 正负样本")
|
||||
def _luhn():
|
||||
assert core.luhn_ok(SAMPLE) is True
|
||||
assert core.luhn_ok(SAMPLE[:-1] + "8") is False
|
||||
return SAMPLE
|
||||
|
||||
|
||||
@case("常规通道:analyze_image 可调用")
|
||||
def _analyze_api():
|
||||
from . import analyze_image
|
||||
assert callable(analyze_image)
|
||||
return "ok"
|
||||
|
||||
|
||||
@case("读号:合成卡图识别正确")
|
||||
def _read():
|
||||
try:
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
except ImportError:
|
||||
return "skip(无 PIL)"
|
||||
img = Image.new("RGB", (1000, 640), (180, 185, 190))
|
||||
d = ImageDraw.Draw(img)
|
||||
d.rounded_rectangle([120, 210, 880, 500], radius=28,
|
||||
fill=(28, 70, 130), outline=(10, 30, 60), width=4)
|
||||
try:
|
||||
font = ImageFont.truetype(r"C:\Windows\Fonts\arial.ttf", 52)
|
||||
except OSError:
|
||||
font = ImageFont.load_default()
|
||||
text = " ".join(SAMPLE[i:i + 4] for i in range(0, len(SAMPLE), 4))
|
||||
d.text((160, 330), text, font=font, fill=(240, 240, 240))
|
||||
out = Path(tempfile.gettempdir()) / "cardreader_selftest_card.png"
|
||||
img.save(out)
|
||||
r = core.read_card(out, mode="fast")
|
||||
assert r.number == SAMPLE, (r.number, r.to_dict())
|
||||
assert r.luhn_ok is True
|
||||
return f"{r.number} / {r.confidence}"
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
verbose = "-v" in argv or "--verbose" in argv
|
||||
passed, failed = 0, []
|
||||
for name, fn in CASES:
|
||||
try:
|
||||
detail = fn()
|
||||
passed += 1
|
||||
print(f"[ok] {name}" + (f" ({detail})" if detail and verbose else ""))
|
||||
except Exception as e: # noqa: BLE001
|
||||
failed.append((name, e))
|
||||
print(f"[FAIL] {name}: {type(e).__name__}: {e}")
|
||||
if verbose:
|
||||
traceback.print_exc()
|
||||
print(f"\n{passed}/{len(CASES)} 通过" + (f",{len(failed)} 失败" if failed else ""))
|
||||
return 0 if not failed else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""身份证 / 银行卡照片识别(纯离线 OCR),供插件直接调用。
|
||||
|
||||
能力:
|
||||
照片 → 卡片定位/透视矫正 → 多遍 OCR → 字段提取 → 身份证校验码 / 银行卡 Luhn 纠错
|
||||
身份证:号码、姓名、性别、民族、出生、住址、签发机关、有效期
|
||||
银行卡:卡号、发卡行、有效期、卡类型
|
||||
批量:按「姓名/图片」目录跑,同人多图合并,自动去重(两列传同一张图)
|
||||
核对:导出带「待填正确答案」的 Excel;已知号码时做命中分析(一致/高度疑似/部分命中/读不出)
|
||||
|
||||
插件里最简单的用法:
|
||||
from cardreader import ocr_card, ocr_cards
|
||||
|
||||
res = ocr_card(r"D:\\照片\\张三\\银行卡.jpg", expected_name="张三")
|
||||
print(res["bank_card"]["number"], res["bank_card"]["luhn_ok"], res["flags"])
|
||||
|
||||
rows = ocr_cards(r"D:\\照片") # [{folder, id_card, bank_card, flags, ...}]
|
||||
|
||||
依赖:opencv-python / numpy / pillow(本库已有)+ rapidocr / onnxruntime(OCR 可选依赖)。
|
||||
模型随 rapidocr 包内置,纯离线,不联网。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .match import check_person, check_persons
|
||||
from .pipeline import analyze_folder, analyze_image
|
||||
|
||||
__version__ = "0.4.1"
|
||||
|
||||
__all__ = [
|
||||
"analyze_image", "analyze_folder",
|
||||
"check_person", "check_persons",
|
||||
"write_review_workbook", "verify_workbook",
|
||||
"__version__",
|
||||
]
|
||||
|
||||
|
||||
def write_review_workbook(persons, path, source_root: str = "") -> str:
|
||||
"""导出带「待填正确答案」列的核对工作簿(需要 openpyxl)。"""
|
||||
try:
|
||||
from .review import write_review_workbook as _impl # noqa: PLC0415
|
||||
except ImportError as e: # pragma: no cover
|
||||
raise RuntimeError("需要 openpyxl 才能导出核对工作簿:pip install openpyxl") from e
|
||||
return _impl(persons, path, source_root=source_root)
|
||||
|
||||
|
||||
def verify_workbook(path: str) -> dict:
|
||||
"""回读人工填好的核对工作簿,统计识别准确率(需要 openpyxl)。"""
|
||||
try:
|
||||
from .review import verify_workbook as _impl # noqa: PLC0415
|
||||
except ImportError as e: # pragma: no cover
|
||||
raise RuntimeError("需要 openpyxl 才能回读核对工作簿:pip install openpyxl") from e
|
||||
return _impl(path)
|
||||
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""python -m cardreader.cardocr scan <目录> [--json out.json] [--xlsx 核对表.xlsx]"""
|
||||
from .cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,138 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""银行卡字段抽取:卡号 / 发卡行 / 有效期 / 卡类型。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Sequence
|
||||
|
||||
from .engine import Line, join_text
|
||||
from .validators import (BIN_BANK, CardCandidate, bin_bank, card_candidates,
|
||||
luhn_ok, normalize_text)
|
||||
|
||||
BANK_KEYWORDS = ("银行", "银联", "UnionPay", "UNIONPAY", "Debit", "Credit", "借记卡",
|
||||
"信用卡", "储蓄卡", "一卡通", "招商", "农业", "工商", "建设", "民生",
|
||||
"兴业", "浦发", "交通", "邮政", "中信", "光大", "华夏", "广发", "平安")
|
||||
|
||||
BANK_NAMES = ("重庆农村商业银行", "重庆三峡银行", "中国工商银行", "中国农业银行",
|
||||
"中国建设银行", "中国银行", "招商银行", "中国民生银行", "兴业银行",
|
||||
"浦发银行", "交通银行", "中国邮政储蓄银行", "中信银行", "中国光大银行",
|
||||
"华夏银行", "广发银行", "平安银行")
|
||||
|
||||
_VALID_BANK_LEN = (16, 18, 19)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BankCardResult:
|
||||
number: str = ""
|
||||
luhn_ok: bool = False
|
||||
length: int = 0
|
||||
bank: str = ""
|
||||
bank_source: str = "" # bin / face / ""
|
||||
expiry: str = ""
|
||||
card_type: str = ""
|
||||
found: bool = False
|
||||
confidence: str = "low"
|
||||
evidence: List[str] = field(default_factory=list)
|
||||
candidates: List[dict] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"found": self.found,
|
||||
"number": self.number,
|
||||
"luhn_ok": self.luhn_ok,
|
||||
"length": self.length,
|
||||
"bank": self.bank,
|
||||
"bank_source": self.bank_source,
|
||||
"expiry": self.expiry,
|
||||
"card_type": self.card_type,
|
||||
"confidence": self.confidence,
|
||||
"evidence": self.evidence,
|
||||
"candidates": self.candidates,
|
||||
}
|
||||
|
||||
|
||||
def looks_like_bank_card(text: str) -> bool:
|
||||
return any(k.lower() in text.lower() for k in BANK_KEYWORDS)
|
||||
|
||||
|
||||
def _bank_from_face(text: str) -> str:
|
||||
for name in BANK_NAMES:
|
||||
if name in text:
|
||||
return name
|
||||
# OCR 常见残缺写法
|
||||
short = {"工商": "中国工商银行", "农业": "中国农业银行", "建设": "中国建设银行",
|
||||
"招商": "招商银行", "民生": "中国民生银行", "兴业": "兴业银行",
|
||||
"浦发": "浦发银行", "交通": "交通银行", "邮政": "中国邮政储蓄银行",
|
||||
"中信": "中信银行", "光大": "中国光大银行", "华夏": "华夏银行",
|
||||
"广发": "广发银行", "平安": "平安银行",
|
||||
"重庆农商": "重庆农村商业银行", "重庆农村商业": "重庆农村商业银行",
|
||||
"三峡": "重庆三峡银行"}
|
||||
for k, v in short.items():
|
||||
if k + "银行" in text or k in text:
|
||||
return v
|
||||
return ""
|
||||
|
||||
|
||||
def _expiry(text: str) -> str:
|
||||
m = re.search(r"(0[1-9]|1[0-2])/(2\d{1,2}|9\d)", text)
|
||||
return m.group(0) if m else ""
|
||||
|
||||
|
||||
def _card_type(text: str) -> str:
|
||||
if "Credit" in text or "信用卡" in text:
|
||||
return "信用卡"
|
||||
if "Debit" in text or "借记卡" in text or "储蓄卡" in text:
|
||||
return "借记卡"
|
||||
return ""
|
||||
|
||||
|
||||
def parse(lines: Sequence[Line], full_text: str = "",
|
||||
exclude: Sequence[str] = (), rows: Optional[Sequence[str]] = None) -> BankCardResult:
|
||||
"""从银行卡那一面的 OCR 结果里抽字段。
|
||||
|
||||
rows 是「行文本」(推荐),没有时退回 full_text。
|
||||
"""
|
||||
res = BankCardResult()
|
||||
text = full_text or join_text(lines)
|
||||
if not text:
|
||||
return res
|
||||
|
||||
cands: List[CardCandidate] = card_candidates(rows if rows else text, exclude=exclude)
|
||||
if cands:
|
||||
top = cands[0]
|
||||
res.number = top.number
|
||||
res.luhn_ok = top.luhn_ok
|
||||
res.length = top.digits
|
||||
res.found = True
|
||||
res.bank = top.bank
|
||||
res.bank_source = "bin" if top.bank else ""
|
||||
res.candidates = [{"number": c.number, "luhn_ok": c.luhn_ok,
|
||||
"length": c.digits, "bank": c.bank,
|
||||
"origin": c.origin, "edits": c.edits,
|
||||
"votes": c.votes, "score": round(c.score, 2)}
|
||||
for c in cands]
|
||||
if top.origin == "repaired":
|
||||
res.evidence.append(f"卡号经 {top.edits} 位纠错后通过 Luhn 校验")
|
||||
if not top.luhn_ok:
|
||||
res.evidence.append("⚠ 卡号未通过 Luhn 校验")
|
||||
if not res.bank:
|
||||
b = _bank_from_face(text)
|
||||
if b:
|
||||
res.bank, res.bank_source = b, "face"
|
||||
res.expiry = _expiry(text)
|
||||
res.card_type = _card_type(text)
|
||||
|
||||
if not res.found:
|
||||
res.confidence = "low"
|
||||
return res
|
||||
clean_len = res.length in _VALID_BANK_LEN
|
||||
if res.luhn_ok and clean_len and res.bank:
|
||||
res.confidence = "high"
|
||||
elif res.luhn_ok and clean_len:
|
||||
res.confidence = "medium"
|
||||
else:
|
||||
res.confidence = "low"
|
||||
if not clean_len:
|
||||
res.evidence.append(f"⚠ 卡号位数 {res.length} 不在 16/18/19")
|
||||
return res
|
||||
@@ -0,0 +1,266 @@
|
||||
# -*- 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))
|
||||
@@ -0,0 +1,110 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""命令行:scan / image / review / verify"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from .match import check_persons, print_report
|
||||
from .pipeline import analyze_folder, analyze_image, summary_table
|
||||
from .review import (load_persons, load_truth_workbook, print_verify, verify_workbook,
|
||||
write_review_workbook)
|
||||
|
||||
|
||||
def _setup_stdout() -> None:
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
_setup_stdout()
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
|
||||
ap = argparse.ArgumentParser(prog="cardocr", description="身份证 / 银行卡照片识别")
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
def common(sp):
|
||||
sp.add_argument("--json", default="", help="结果写入 JSON 文件")
|
||||
sp.add_argument("--xlsx", default="", help="结果写成核对工作簿(含待填列)")
|
||||
sp.add_argument("--mark", default="", help="标注图输出目录")
|
||||
sp.add_argument("--no-extra", action="store_true", help="关闭卡号多遍增强识别(更快)")
|
||||
sp.add_argument("--fast", action="store_true", help="只跑粗识别(最快,精度下降)")
|
||||
sp.add_argument("--limit", type=int, default=0, help="每个目录最多取几张图(0=全部)")
|
||||
|
||||
sp_scan = sub.add_parser("scan", help="按「姓名/图片」目录批量识别")
|
||||
sp_scan.add_argument("root", help="照片根目录")
|
||||
common(sp_scan)
|
||||
|
||||
sp_one = sub.add_parser("image", help="识别单张图片")
|
||||
sp_one.add_argument("path", help="图片路径")
|
||||
sp_one.add_argument("--name", default="", help="预期姓名(用于校验身份证姓名)")
|
||||
common(sp_one)
|
||||
|
||||
sp_rev = sub.add_parser("review", help="把 JSON 结果导出成核对工作簿")
|
||||
sp_rev.add_argument("--json", required=True, help="scan 输出的 JSON")
|
||||
sp_rev.add_argument("--out", required=True, help="输出的 xlsx 路径")
|
||||
|
||||
sp_ver = sub.add_parser("verify", help="回读填好的核对工作簿,算准确率")
|
||||
sp_ver.add_argument("xlsx", help="核对工作簿路径")
|
||||
|
||||
sp_chk = sub.add_parser("check", help="用人工填写的正确值做「命中分析」")
|
||||
sp_chk.add_argument("--json", required=True, help="scan 输出的 JSON")
|
||||
sp_chk.add_argument("--truth", required=True, help="填好的核对工作簿 xlsx")
|
||||
sp_chk.add_argument("--out", default="", help="命中分析结果写入 JSON")
|
||||
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
if args.cmd == "scan":
|
||||
persons = analyze_folder(args.root, mark_dir=args.mark or None,
|
||||
extra_passes=not args.no_extra, fast=args.fast,
|
||||
limit=args.limit)
|
||||
print(summary_table(persons))
|
||||
payload = {"root": str(Path(args.root).resolve()), "persons": persons}
|
||||
if args.json:
|
||||
Path(args.json).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.json).write_text(json.dumps(payload, ensure_ascii=False, indent=1),
|
||||
encoding="utf-8")
|
||||
print(f"\n已写入 {args.json}")
|
||||
if args.xlsx:
|
||||
write_review_workbook(persons, args.xlsx, source_root=payload["root"])
|
||||
print(f"\n核对工作簿已写入 {args.xlsx}")
|
||||
return 0
|
||||
|
||||
if args.cmd == "image":
|
||||
res = analyze_image(args.path, expected_name=args.name, mark_dir=args.mark or None,
|
||||
extra_passes=not args.no_extra, fast=args.fast)
|
||||
print(json.dumps(res, ensure_ascii=False, indent=1))
|
||||
if args.json:
|
||||
Path(args.json).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.json).write_text(json.dumps({"images": [res]}, ensure_ascii=False,
|
||||
indent=1), encoding="utf-8")
|
||||
return 0
|
||||
|
||||
if args.cmd == "review":
|
||||
persons = load_persons(args.json)
|
||||
write_review_workbook(persons, args.out)
|
||||
print(f"核对工作簿已写入 {args.out}({len(persons)} 行)")
|
||||
return 0
|
||||
|
||||
if args.cmd == "check":
|
||||
persons = load_persons(args.json)
|
||||
truth = load_truth_workbook(args.truth)
|
||||
rows = check_persons(persons, truth)
|
||||
print(print_report(rows))
|
||||
if args.out:
|
||||
Path(args.out).write_text(json.dumps(rows, ensure_ascii=False, indent=1),
|
||||
encoding="utf-8")
|
||||
print(f"\n命中分析已写入 {args.out}")
|
||||
return 0
|
||||
|
||||
result = verify_workbook(args.xlsx)
|
||||
print_verify(result)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,206 @@
|
||||
# -*- 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)
|
||||
@@ -0,0 +1,520 @@
|
||||
# -*- 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)
|
||||
@@ -0,0 +1,186 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""身份证字段抽取:号码 / 姓名 / 性别 / 民族 / 出生 / 住址。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Sequence
|
||||
|
||||
from .engine import Line, join_text
|
||||
from .validators import (IdCandidate, id_birth, id_candidates, id_checksum_ok,
|
||||
id_gender, id_plausible, id_region, normalize_text)
|
||||
|
||||
ID_KEYWORDS = ("公民身份号码", "身份号码", "姓名", "性别", "民族", "出生", "住址",
|
||||
"签发机关", "有效期限", "中华人民共和国", "居民身份证")
|
||||
|
||||
# 这些词不能当姓名
|
||||
_NOT_NAME = set(ID_KEYWORDS) | {"男", "女", "汉", "回", "苗", "彝", "壮", "藏", "维吾尔",
|
||||
"身份证", "公民", "号码", "地址", "出生日期"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class IdCardResult:
|
||||
number: str = ""
|
||||
checksum_ok: bool = False
|
||||
birth: str = ""
|
||||
gender: str = ""
|
||||
name: str = ""
|
||||
ethnicity: str = ""
|
||||
address: str = ""
|
||||
issue: str = ""
|
||||
valid_to: str = ""
|
||||
confidence: str = "low" # high / medium / low
|
||||
evidence: List[str] = field(default_factory=list)
|
||||
candidates: List[dict] = field(default_factory=list)
|
||||
found: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"found": self.found,
|
||||
"number": self.number,
|
||||
"checksum_ok": self.checksum_ok,
|
||||
"birth": self.birth,
|
||||
"gender": self.gender,
|
||||
"name": self.name,
|
||||
"ethnicity": self.ethnicity,
|
||||
"address": self.address,
|
||||
"issue": self.issue,
|
||||
"valid_to": self.valid_to,
|
||||
"confidence": self.confidence,
|
||||
"evidence": self.evidence,
|
||||
"candidates": self.candidates,
|
||||
}
|
||||
|
||||
|
||||
def looks_like_id(text: str) -> bool:
|
||||
hits = sum(1 for k in ID_KEYWORDS if k in text)
|
||||
return hits >= 2 or "公民身份号码" in text or "居民身份证" in text
|
||||
|
||||
|
||||
def _norm_name(s: str) -> str:
|
||||
s = normalize_text(s)
|
||||
s = re.sub(r"^姓名", "", s)
|
||||
s = re.sub(r"[·•.\s]", "", s)
|
||||
return s
|
||||
|
||||
|
||||
# 这些词长得像姓名,绝不能当姓名
|
||||
_BANK_WORDS = ("银行", "银联", "UNIONPAY", "信用卡", "借记卡", "储蓄卡", "一卡通",
|
||||
"有限公司", "保险", "支行", "分行")
|
||||
|
||||
|
||||
def _name_candidate(text: str) -> str:
|
||||
t = _norm_name(text)
|
||||
if not (2 <= len(t) <= 4 and re.fullmatch(r"[一-龥]+", t)):
|
||||
return ""
|
||||
if t in _NOT_NAME or any(w in t.upper() for w in _BANK_WORDS):
|
||||
return ""
|
||||
return t
|
||||
|
||||
|
||||
def _pick_name(lines: Sequence[Line], expected: str, full_text: str) -> str:
|
||||
"""姓名优先用外部给的姓名做交叉验证,其次取「姓名」标签旁边那一段 2~4 字中文。"""
|
||||
if expected:
|
||||
exp = _norm_name(expected)
|
||||
if exp and exp in normalize_text(full_text):
|
||||
return exp
|
||||
# 情况一:OCR 把标签和名字连成一段(「姓名李诗灿」)
|
||||
for ln in lines:
|
||||
m = re.match(r"姓名([一-龥]{2,4})$", normalize_text(ln.text))
|
||||
if m and _name_candidate(m.group(1)):
|
||||
return _name_candidate(m.group(1))
|
||||
# 情况二:标签和名字是两段,取离「姓名」标签最近的那段中文
|
||||
labels = [ln for ln in lines if "姓名" in normalize_text(ln.text)]
|
||||
cands = []
|
||||
for ln in lines:
|
||||
c = _name_candidate(ln.text)
|
||||
if not c:
|
||||
continue
|
||||
for lab in labels:
|
||||
d = abs(ln.y_mid - lab.y_mid) * 2.0 + abs(ln.left - lab.right)
|
||||
cands.append((d, c))
|
||||
if cands:
|
||||
cands.sort(key=lambda x: x[0])
|
||||
return cands[0][1]
|
||||
return ""
|
||||
|
||||
|
||||
def _pick_field(text: str, patterns: Sequence[str]) -> str:
|
||||
for pat in patterns:
|
||||
m = re.search(pat, text)
|
||||
if m:
|
||||
return m.group(1)
|
||||
return ""
|
||||
|
||||
|
||||
def parse(lines: Sequence[Line], expected_name: str = "",
|
||||
full_text: str = "", rows: Optional[Sequence[str]] = None) -> IdCardResult:
|
||||
"""从身份证那一面的 OCR 结果里抽字段。"""
|
||||
res = IdCardResult()
|
||||
text = normalize_text(full_text) if full_text else normalize_text(join_text(lines))
|
||||
if not text:
|
||||
return res
|
||||
|
||||
cands: List[IdCandidate] = id_candidates(rows if rows else text)
|
||||
if not cands:
|
||||
# 逐行再试(号码被拆成两段时)
|
||||
for ln in lines:
|
||||
cands.extend(id_candidates(ln.text))
|
||||
cands = sorted(cands, key=lambda c: -c.score)[:8]
|
||||
|
||||
if cands:
|
||||
top = cands[0]
|
||||
res.candidates = [{"number": c.number, "checksum_ok": c.checksum_ok,
|
||||
"origin": c.origin, "edits": c.edits,
|
||||
"score": round(c.score, 2)} for c in cands]
|
||||
res.number = top.number
|
||||
res.checksum_ok = top.checksum_ok
|
||||
res.birth = id_birth(top.number)
|
||||
res.gender = id_gender(top.number)
|
||||
res.found = True
|
||||
if top.origin == "repaired":
|
||||
res.evidence.append(f"号码经 {top.edits} 位纠错后通过校验码(原始识别有误)")
|
||||
|
||||
# 与 OCR 文字里的「出生 / 性别」交叉核对,不一致时优先相信 OCR 文字并打标注
|
||||
birth_txt = _pick_field(text, (r"出生(\d{4}年\d{1,2}月\d{1,2}日)",
|
||||
r"出生(\d{4}[.\-/]\d{1,2}[.\-/]\d{1,2})"))
|
||||
if birth_txt:
|
||||
res.evidence.append(f"卡面出生:{birth_txt}")
|
||||
|
||||
gender_txt = ""
|
||||
m = re.search(r"性别[男女]", text) or re.search(r"(男|女)", text)
|
||||
if m:
|
||||
gender_txt = "女" if "女" in m.group(0) else "男"
|
||||
if gender_txt:
|
||||
res.evidence.append(f"卡面性别:{gender_txt}")
|
||||
if res.gender and res.gender != gender_txt:
|
||||
res.evidence.append(f"⚠ 号码推导性别({res.gender})与卡面({gender_txt})不一致")
|
||||
|
||||
eth = _pick_field(text, (r"民族([\u4e00-\u9fa5]{1,4}?)(?=出生|性别|姓名|住址|公|$)",))
|
||||
res.ethnicity = eth
|
||||
|
||||
res.name = _pick_name(lines, expected_name, text)
|
||||
|
||||
# 住址:从「住址」开始到号码/签发机关之前
|
||||
m = re.search(r"住址(.+?)(公民身份号码|签发机关|有效期限|$)", text)
|
||||
addr = m.group(1) if m else ""
|
||||
res.address = re.sub(r"[。,,]", "", addr)[:60]
|
||||
|
||||
res.issue = _pick_field(text, (r"签发机关([^有效]+?)(?:有效|$)",))
|
||||
vt = re.search(r"有效期限?(\d{4}[.\-/年]\d{1,2}[.\-/月]\d{1,2}[日]?(?:[-—~至]\d{4}[.\-/年]\d{1,2}[.\-/月]\d{1,2}[日]?|长期))", text)
|
||||
res.valid_to = vt.group(1) if vt else ""
|
||||
|
||||
# 置信度
|
||||
high = res.checksum_ok and bool(res.name) and bool(res.birth)
|
||||
if (expected_name and res.name and _norm_name(res.name) != _norm_name(expected_name)):
|
||||
high = False
|
||||
res.evidence.append(f"⚠ 姓名({res.name})与表格姓名({expected_name})不一致")
|
||||
if not res.checksum_ok:
|
||||
res.confidence = "low" if not cands else "medium"
|
||||
elif high and (top.origin == "raw" if cands else False):
|
||||
res.confidence = "high"
|
||||
else:
|
||||
res.confidence = "medium"
|
||||
if res.birth and not id_plausible(res.number or ""):
|
||||
res.evidence.append("⚠ 号码生日不合法")
|
||||
return res
|
||||
@@ -0,0 +1,174 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""图像基础操作:中文路径读取、缩放、增强、旋转、透视矫正。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Iterable, List, Optional, Sequence, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# 身份证 / 银行卡物理尺寸 85.6 x 54 mm,长宽比 ≈ 1.585
|
||||
CARD_ASPECT = 85.6 / 54.0
|
||||
|
||||
|
||||
def imread(path: str) -> np.ndarray:
|
||||
"""读取图片(支持中文路径 / 空格,cv2.imread 在 Windows 下会失败)。"""
|
||||
p = str(path)
|
||||
if not os.path.isfile(p):
|
||||
raise FileNotFoundError(f"图片不存在:{p}")
|
||||
data = np.fromfile(p, dtype=np.uint8)
|
||||
if data.size == 0:
|
||||
raise ValueError(f"图片为空:{p}")
|
||||
img = cv2.imdecode(data, cv2.IMREAD_COLOR)
|
||||
if img is None:
|
||||
# 部分手机的 JPEG(CMYK / 特殊 EXIF)cv2 解不出,退 Pillow
|
||||
from PIL import Image, ImageOps # noqa: PLC0415
|
||||
|
||||
with Image.open(p) as im:
|
||||
im = ImageOps.exif_transpose(im).convert("RGB")
|
||||
img = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)
|
||||
return img
|
||||
|
||||
|
||||
def apply_exif(img: np.ndarray, path: str) -> np.ndarray:
|
||||
"""按 EXIF Orientation 摆正(手机竖拍常带 90/180/270 标记)。"""
|
||||
try:
|
||||
from PIL import Image, ImageOps # noqa: PLC0415
|
||||
|
||||
with Image.open(path) as im:
|
||||
exif = im.getexif()
|
||||
o = int(exif.get(274, 1) or 1)
|
||||
if o in (1, 0):
|
||||
return img
|
||||
im2 = ImageOps.exif_transpose(im).convert("RGB")
|
||||
return cv2.cvtColor(np.array(im2), cv2.COLOR_RGB2BGR)
|
||||
except Exception: # noqa: BLE001 EXIF 不可用不算错
|
||||
return img
|
||||
|
||||
|
||||
def resize_side(img: np.ndarray, max_side: int = 0, min_side: int = 0) -> np.ndarray:
|
||||
"""按长边上限缩小 / 短边下限放大(等比)。"""
|
||||
h, w = img.shape[:2]
|
||||
scale = 1.0
|
||||
if max_side and max(h, w) > max_side:
|
||||
scale = max_side / float(max(h, w))
|
||||
elif min_side and min(h, w) < min_side:
|
||||
scale = min_side / float(min(h, w))
|
||||
if abs(scale - 1.0) < 1e-3:
|
||||
return img
|
||||
interp = cv2.INTER_AREA if scale < 1 else cv2.INTER_CUBIC
|
||||
return cv2.resize(img, (max(1, int(round(w * scale))), max(1, int(round(h * scale)))),
|
||||
interpolation=interp)
|
||||
|
||||
|
||||
def to_gray(img: np.ndarray) -> np.ndarray:
|
||||
if img.ndim == 2:
|
||||
return img
|
||||
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
|
||||
|
||||
def rotate90(img: np.ndarray, k: int) -> np.ndarray:
|
||||
"""逆时针旋转 k*90 度。"""
|
||||
return np.ascontiguousarray(np.rot90(img, k % 4))
|
||||
|
||||
|
||||
def gray_variants(gray: np.ndarray, upscale: float = 1.0) -> List[Tuple[str, np.ndarray]]:
|
||||
"""生成多路灰度增强图(浮雕卡号、反光、低对比度各有用),供多遍 OCR 投票。"""
|
||||
g = gray
|
||||
if upscale > 1.0:
|
||||
g = cv2.resize(g, None, fx=upscale, fy=upscale, interpolation=cv2.INTER_CUBIC)
|
||||
out: List[Tuple[str, np.ndarray]] = [("gray", g)]
|
||||
try:
|
||||
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(g)
|
||||
out.append(("clahe", clahe))
|
||||
except Exception: # noqa: BLE001
|
||||
clahe = g
|
||||
# 反光/低对比:白顶帽 + 黑底帽 强调字迹
|
||||
k = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 5))
|
||||
try:
|
||||
tophat = cv2.morphologyEx(g, cv2.MORPH_TOPHAT, k)
|
||||
blackhat = cv2.morphologyEx(g, cv2.MORPH_BLACKHAT, k)
|
||||
out.append(("tophat", cv2.normalize(tophat, None, 0, 255, cv2.NORM_MINMAX)))
|
||||
out.append(("blackhat", cv2.normalize(blackhat, None, 0, 255, cv2.NORM_MINMAX)))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# 二值化(Otsu / 自适应),深色卡面反相后号码变白底黑字
|
||||
try:
|
||||
_, otsu = cv2.threshold(g, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
||||
out.append(("otsu", otsu))
|
||||
out.append(("otsu_inv", cv2.bitwise_not(otsu)))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
adap = cv2.adaptiveThreshold(g, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||
cv2.THRESH_BINARY, 31, 9)
|
||||
out.append(("adaptive", adap))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# 锐化(浮雕数字边缘)
|
||||
try:
|
||||
blur = cv2.GaussianBlur(g, (0, 0), 1.2)
|
||||
out.append(("sharp", cv2.addWeighted(g, 1.6, blur, -0.6, 0)))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def order_points(pts: Sequence[Sequence[float]]) -> np.ndarray:
|
||||
"""四个点按 左上/右上/右下/左下 排序。"""
|
||||
pts = np.asarray(pts, dtype=np.float32).reshape(4, 2)
|
||||
s = pts.sum(axis=1)
|
||||
d = np.diff(pts, axis=1).reshape(-1)
|
||||
out = np.zeros((4, 2), dtype=np.float32)
|
||||
out[0] = pts[np.argmin(s)]
|
||||
out[2] = pts[np.argmax(s)]
|
||||
out[1] = pts[np.argmin(d)]
|
||||
out[3] = pts[np.argmax(d)]
|
||||
return out
|
||||
|
||||
|
||||
def four_point_warp(img: np.ndarray, pts: Sequence[Sequence[float]],
|
||||
width: int = 0, height: int = 0) -> Tuple[np.ndarray, np.ndarray]:
|
||||
"""把四边形透视矫正成矩形(宽度默认按目标长宽比 1.585 推算)。"""
|
||||
src = order_points(pts)
|
||||
tl, tr, br, bl = src
|
||||
w_top = float(np.linalg.norm(tr - tl))
|
||||
w_bot = float(np.linalg.norm(br - bl))
|
||||
h_lef = float(np.linalg.norm(bl - tl))
|
||||
h_rig = float(np.linalg.norm(br - tr))
|
||||
w = (w_top + w_bot) / 2.0
|
||||
h = (h_lef + h_rig) / 2.0
|
||||
if width and height:
|
||||
w, h = float(width), float(height)
|
||||
elif width:
|
||||
h = width / CARD_ASPECT
|
||||
elif height:
|
||||
w = height * CARD_ASPECT
|
||||
elif w > 0 and h > 0:
|
||||
# 拉正成标准卡比例,避免斜拍把字压扁
|
||||
if w / h > CARD_ASPECT * 1.12:
|
||||
h = w / CARD_ASPECT
|
||||
elif h / w > 1.0 / CARD_ASPECT * 1.12:
|
||||
w = h * CARD_ASPECT
|
||||
dst = np.array([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]], dtype=np.float32)
|
||||
m = cv2.getPerspectiveTransform(src, dst)
|
||||
out = cv2.warpPerspective(img, m, (max(1, int(round(w))), max(1, int(round(h)))),
|
||||
flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
|
||||
return out, m
|
||||
|
||||
|
||||
def quad_area(pts: np.ndarray) -> float:
|
||||
return float(abs(cv2.contourArea(np.asarray(pts, dtype=np.float32).reshape(-1, 1, 2))))
|
||||
|
||||
|
||||
def iou_rect(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int]) -> 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)
|
||||
union = aw * ah + bw * bh - inter
|
||||
return inter / float(union) if union > 0 else 0.0
|
||||
@@ -0,0 +1,153 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""命中分析:拿「已知正确号码」去比对识别结果,回答「这张照片能不能证明是这张卡」。
|
||||
|
||||
识别精确率是 100%(认出来的都对),但召回受照片质量限制(有的卡号只读到一半)。
|
||||
和业务上已有的工资卡数据比对时,不需要「完整读出」才有价值——读到前缀 + 后缀、
|
||||
或者除 1 位外全对,就已经能判定「照片与登记号码一致」。
|
||||
|
||||
状态定义:
|
||||
exact 完整命中(识别结果逐位一致)
|
||||
strong 高度一致(≥85% 位命中,通常只差 1 位且是 Luhn 歧义)
|
||||
partial 部分命中(30%~85% 位命中,能看到前缀/后缀)
|
||||
weak 基本读不出(<30%)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
from typing import Dict, Iterable, List, Sequence, Tuple
|
||||
|
||||
from .validators import PRIMARY, bin_bank, normalize_text
|
||||
|
||||
EXACT, STRONG, PARTIAL, WEAK = "exact", "strong", "partial", "weak"
|
||||
LABEL = {EXACT: "一致", STRONG: "高度疑似", PARTIAL: "部分命中", WEAK: "读不出"}
|
||||
|
||||
|
||||
def digits(text: str) -> str:
|
||||
s = normalize_text(text)
|
||||
return "".join(ch if ch.isdigit() else PRIMARY.get(ch, "") for ch in s)
|
||||
|
||||
|
||||
def _keep(run: str, exp: str, card_mode: bool, id_digits: str) -> bool:
|
||||
"""只有「像卡号片段」的游程才参与卡号比对,否则身份证号/日期会把命中率抬虚。"""
|
||||
if len(run) < 8:
|
||||
return False
|
||||
if not card_mode:
|
||||
return True
|
||||
if id_digits and (run == id_digits or id_digits in run or run in id_digits):
|
||||
return False
|
||||
return run.startswith("62") or bool(bin_bank(run)) or run in exp or exp.find(run) >= 0
|
||||
|
||||
|
||||
def coverage(expected: str, runs: Iterable[str], card_mode: bool = True,
|
||||
id_digits: str = "") -> Tuple[float, str, str]:
|
||||
"""返回 (命中率 0~1, 状态, 命中最多的片段)。"""
|
||||
exp = digits(expected)
|
||||
if not exp:
|
||||
return 0.0, WEAK, ""
|
||||
best_cov, best_run, best_status = 0.0, "", WEAK
|
||||
for raw in runs:
|
||||
run = digits(raw)
|
||||
if not _keep(run, exp, card_mode, id_digits):
|
||||
continue
|
||||
if run == exp:
|
||||
return 1.0, EXACT, run
|
||||
covered: set[int] = set()
|
||||
pos = 0
|
||||
while True:
|
||||
i = exp.find(run, pos)
|
||||
if i < 0:
|
||||
break
|
||||
covered.update(range(i, i + len(run)))
|
||||
pos = i + 1
|
||||
pos_cov = len(covered) / len(exp) if covered else 0.0
|
||||
# 只有够长的片段才用模糊相似度,避免 8~10 位噪声凑出虚高命中率
|
||||
ratio = difflib.SequenceMatcher(None, exp, run, autojunk=False).ratio() \
|
||||
if len(run) >= 14 else 0.0
|
||||
cov = max(pos_cov, ratio)
|
||||
if cov > best_cov:
|
||||
best_cov, best_run = cov, run
|
||||
best_status = STRONG if cov >= 0.85 else (PARTIAL if cov >= 0.30 else WEAK)
|
||||
return best_cov, best_status, best_run
|
||||
|
||||
|
||||
def _runs_of(person: dict) -> List[str]:
|
||||
out: List[str] = []
|
||||
for r in (person.get("raw") or []):
|
||||
out.extend(r.get("digit_runs") or [])
|
||||
return out
|
||||
|
||||
|
||||
def check_person(person: dict, truth: Dict[str, str]) -> dict:
|
||||
"""比对一个人的识别结果和人工填写的正确值。"""
|
||||
idc = person.get("id_card") or {}
|
||||
bk = person.get("bank_card") or {}
|
||||
runs = _runs_of(person)
|
||||
|
||||
t_id = digits(truth.get("id") or "")
|
||||
t_card = digits(truth.get("card") or "")
|
||||
t_name = (truth.get("name") or "").strip()
|
||||
|
||||
got_id = digits(idc.get("number") or "")
|
||||
if t_id:
|
||||
if got_id == t_id:
|
||||
id_status, id_cov = EXACT, 1.0
|
||||
else:
|
||||
id_cov, id_status, _ = coverage(t_id, runs, card_mode=False)
|
||||
else:
|
||||
id_status, id_cov = WEAK, 0.0
|
||||
|
||||
if t_card:
|
||||
if digits(bk.get("number") or "") == t_card:
|
||||
card_status, card_cov = EXACT, 1.0
|
||||
else:
|
||||
card_cov, card_status, _ = coverage(t_card, runs, card_mode=True,
|
||||
id_digits=got_id or t_id)
|
||||
else:
|
||||
card_cov, card_status = 0.0, WEAK
|
||||
|
||||
got_name = (idc.get("name") or "").strip()
|
||||
if t_name:
|
||||
name_status = EXACT if got_name == t_name else (PARTIAL if not got_name else WEAK)
|
||||
else:
|
||||
name_status = WEAK
|
||||
|
||||
return {
|
||||
"folder": person.get("folder", ""),
|
||||
"truth_name": t_name,
|
||||
"id_recognized": got_id or "",
|
||||
"id_status": id_status,
|
||||
"id_coverage": round(id_cov, 3),
|
||||
"card_recognized": digits(bk.get("number") or ""),
|
||||
"card_status": card_status,
|
||||
"card_coverage": round(card_cov, 3),
|
||||
"name_recognized": got_name,
|
||||
"name_status": name_status,
|
||||
"runs": runs[:12],
|
||||
}
|
||||
|
||||
|
||||
def check_persons(persons: Sequence[dict], truth_map: Dict[str, Dict[str, str]]) -> List[dict]:
|
||||
rows = []
|
||||
for p in persons:
|
||||
t = truth_map.get(p.get("folder", "")) or {}
|
||||
if not t:
|
||||
continue
|
||||
rows.append(check_person(p, t))
|
||||
return rows
|
||||
|
||||
|
||||
def print_report(rows: Sequence[dict]) -> str:
|
||||
lines = [f"{'姓名':<9}{'身份证识别':<20}{'状态':<9}{'卡号识别':<20}{'卡号状态':<9}"
|
||||
f"{'命中率':<8}姓名"]
|
||||
lines.append("-" * 100)
|
||||
for r in rows:
|
||||
lines.append(
|
||||
f"{r['folder']:<9}"
|
||||
f"{(r['id_recognized'] or '-'):<20}"
|
||||
f"{LABEL.get(r['id_status'], r['id_status']):<9}"
|
||||
f"{(r['card_recognized'] or '-'):<20}"
|
||||
f"{LABEL.get(r['card_status'], r['card_status']):<9}"
|
||||
f"{r['card_coverage']:<8.2f}"
|
||||
f"{'一致' if r['name_status'] == EXACT else ('未识别' if not r['name_recognized'] else '不一致')}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,652 @@
|
||||
# -*- 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)
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""核对工作簿:把识别结果导出成 Excel,留出「正确答案」列给人工填写,并可回读算准确率。
|
||||
|
||||
用法(代码):
|
||||
from cardocr.review import write_review_workbook, verify_workbook
|
||||
write_review_workbook(persons, "识别核对表.xlsx")
|
||||
print(verify_workbook("识别核对表.xlsx"))
|
||||
|
||||
命令行:
|
||||
python -m cardocr review --json result.json --out 识别核对表.xlsx
|
||||
python -m cardocr verify 识别核对表.xlsx
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Dict, List, Optional, Sequence
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
HEADER_FILL = PatternFill("solid", fgColor="1F4E79")
|
||||
INPUT_FILL = PatternFill("solid", fgColor="FFF2CC")
|
||||
THIN = Side(style="thin", color="BFBFBF")
|
||||
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
||||
|
||||
# 逐人核对表列定义:(key, 列名, 宽度)
|
||||
PERSON_COLS = [
|
||||
("pid", "ID", 8),
|
||||
("folder", "姓名(文件夹)", 12),
|
||||
("id_number", "身份证号(识别)", 22),
|
||||
("id_ok", "身份证校验", 10),
|
||||
("id_name", "身份证姓名(识别)", 14),
|
||||
("card_number", "银行卡号(识别)", 22),
|
||||
("card_ok", "Luhn", 7),
|
||||
("bank", "发卡行", 16),
|
||||
("id_conf", "身份证置信度", 12),
|
||||
("card_conf", "卡号置信度", 11),
|
||||
("photos", "图片数", 8),
|
||||
("files", "照片文件", 40),
|
||||
("dup", "重复图片", 9),
|
||||
("flags", "标记", 34),
|
||||
("evidence", "识别说明", 34),
|
||||
("truth_id", "【待填】正确身份证号", 22),
|
||||
("truth_name", "【待填】正确姓名", 14),
|
||||
("truth_card", "【待填】正确银行卡号", 22),
|
||||
("verdict", "【待填】判定", 10),
|
||||
("note", "【待填】说明", 26),
|
||||
]
|
||||
|
||||
IMAGE_COLS = [
|
||||
("iid", "图片ID", 10),
|
||||
("folder", "姓名(文件夹)", 12),
|
||||
("filename", "文件名", 34),
|
||||
("size", "分辨率", 14),
|
||||
("kb", "大小KB", 9),
|
||||
("layout", "布局", 10),
|
||||
("id_number", "身份证号(识别)", 22),
|
||||
("id_ok", "身份证校验", 10),
|
||||
("id_name", "姓名(识别)", 12),
|
||||
("card_number", "卡号(识别)", 22),
|
||||
("card_ok", "Luhn", 7),
|
||||
("bank", "发卡行", 16),
|
||||
("conf", "置信度", 10),
|
||||
("elapsed", "用时s", 8),
|
||||
("sha", "SHA256前12", 15),
|
||||
("flags", "标记", 30),
|
||||
("cands", "卡号候选", 30),
|
||||
("path", "路径", 55),
|
||||
]
|
||||
|
||||
|
||||
def _style_sheet(ws, cols: Sequence[tuple], truth_from: int = 0) -> None:
|
||||
for i, (_key, title, width) in enumerate(cols, 1):
|
||||
c = ws.cell(row=1, column=i, value=title)
|
||||
c.font = Font(bold=True, color="FFFFFF", size=10)
|
||||
c.fill = HEADER_FILL
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = BORDER
|
||||
ws.column_dimensions[get_column_letter(i)].width = width
|
||||
ws.row_dimensions[1].height = 30
|
||||
ws.freeze_panes = "A2"
|
||||
if truth_from:
|
||||
for i in range(truth_from, len(cols) + 1):
|
||||
ws.cell(row=1, column=i).fill = PatternFill("solid", fgColor="C00000")
|
||||
|
||||
|
||||
def _fmt_id(p: dict) -> Dict[str, object]:
|
||||
idc = p.get("id_card") or {}
|
||||
bk = p.get("bank_card") or {}
|
||||
flags = p.get("flags", [])
|
||||
notes = list(idc.get("evidence") or [])
|
||||
if "low_resolution" in flags and bk.get("number"):
|
||||
notes.append("⚠ 原图是缩略图,卡号建议人工复核")
|
||||
if bk.get("number") and not bk.get("luhn_ok"):
|
||||
notes.append("⚠ 卡号未过 Luhn")
|
||||
return {
|
||||
"pid": "",
|
||||
"folder": p.get("folder", ""),
|
||||
"id_number": idc.get("number") or "未识别",
|
||||
"id_ok": "✓" if idc.get("checksum_ok") else ("✗" if idc.get("number") else ""),
|
||||
"id_name": idc.get("name") or "未识别",
|
||||
"card_number": bk.get("number") or "未识别",
|
||||
"card_ok": "✓" if bk.get("luhn_ok") else ("✗" if bk.get("number") else ""),
|
||||
"bank": bk.get("bank") or "-",
|
||||
"id_conf": idc.get("confidence", "") or "-",
|
||||
"card_conf": bk.get("confidence", "") or "-",
|
||||
"photos": len(p.get("files") or []),
|
||||
"files": ";".join(f.get("filename") or "" for f in (p.get("files") or [])),
|
||||
"dup": "是" if p.get("duplicate_photo") else "否",
|
||||
"flags": ",".join(p.get("flags", [])),
|
||||
"evidence": ";".join(notes) or "",
|
||||
}
|
||||
|
||||
|
||||
def _fmt_image(p: dict, r: dict, iid: str) -> Dict[str, object]:
|
||||
idc = r.get("id_card") or {}
|
||||
bk = r.get("bank_card") or {}
|
||||
cands = bk.get("candidates") or []
|
||||
top = [c.get("number", "") for c in cands[:2]]
|
||||
return {
|
||||
"iid": iid,
|
||||
"folder": p.get("folder", ""),
|
||||
"filename": r.get("filename", ""),
|
||||
"size": f"{r.get('width', '')}x{r.get('height', '')}",
|
||||
"kb": round((r.get("bytes") or 0) / 1024),
|
||||
"layout": r.get("layout", ""),
|
||||
"id_number": idc.get("number") or "未识别",
|
||||
"id_ok": "✓" if idc.get("checksum_ok") else ("✗" if idc.get("number") else ""),
|
||||
"id_name": idc.get("name") or "未识别",
|
||||
"card_number": bk.get("number") or "未识别",
|
||||
"card_ok": "✓" if bk.get("luhn_ok") else ("✗" if bk.get("number") else ""),
|
||||
"bank": bk.get("bank") or "-",
|
||||
"conf": f"身份证:{idc.get('confidence', '') or '-'} 卡:{bk.get('confidence', '') or '-'}",
|
||||
"elapsed": r.get("elapsed_s", ""),
|
||||
"sha": (r.get("sha256") or "")[:12],
|
||||
"flags": ",".join(r.get("flags", [])),
|
||||
"cands": " / ".join(top),
|
||||
"path": r.get("file", ""),
|
||||
}
|
||||
|
||||
|
||||
def write_review_workbook(persons: Sequence[dict], path: str,
|
||||
source_root: str = "") -> str:
|
||||
"""导出核对工作簿(3 个 sheet:逐人核对 / 逐图明细 / 填写说明)。"""
|
||||
wb = Workbook()
|
||||
ws1 = wb.active
|
||||
ws1.title = "逐人核对"
|
||||
ws2 = wb.create_sheet("逐图明细")
|
||||
ws3 = wb.create_sheet("填写说明")
|
||||
|
||||
truth_from = next((i for i, (_k, _t, _w) in enumerate(PERSON_COLS, 1)
|
||||
if _k.startswith("truth")), 0)
|
||||
_style_sheet(ws1, PERSON_COLS, truth_from=truth_from)
|
||||
_style_sheet(ws2, IMAGE_COLS)
|
||||
|
||||
stats = {"persons": len(persons), "photos": 0}
|
||||
id_ok = id_bad = 0
|
||||
card_ok = card_bad = 0
|
||||
r1 = 2
|
||||
r2 = 2
|
||||
for idx, p in enumerate(persons, 1):
|
||||
pid = f"P{idx:03d}"
|
||||
row = _fmt_id(p)
|
||||
row["pid"] = pid
|
||||
for col, (_key, _title, _w) in enumerate(PERSON_COLS, 1):
|
||||
c = ws1.cell(row=r1, column=col, value=row.get(_key, ""))
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
if col >= 15:
|
||||
c.fill = INPUT_FILL
|
||||
ws1.row_dimensions[r1].height = 22
|
||||
if row["id_ok"] == "✓":
|
||||
id_ok += 1
|
||||
elif row["id_ok"] == "✗":
|
||||
id_bad += 1
|
||||
if row["card_ok"] == "✓":
|
||||
card_ok += 1
|
||||
elif row["card_ok"] == "✗":
|
||||
card_bad += 1
|
||||
|
||||
imgs = [r for r in (p.get("raw") or []) if r.get("id_card") or r.get("bank_card")]
|
||||
for j, r in enumerate(imgs, 1):
|
||||
row2 = _fmt_image(p, r, f"{pid}-{'AB'[min(j - 1, 1)]}")
|
||||
for col, (_key, _title, _w) in enumerate(IMAGE_COLS, 1):
|
||||
c = ws2.cell(row=r2, column=col, value=row2.get(_key, ""))
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
ws2.row_dimensions[r2].height = 22
|
||||
r2 += 1
|
||||
stats["photos"] += 1
|
||||
r1 += 1
|
||||
|
||||
ws1.auto_filter.ref = f"A1:{get_column_letter(len(PERSON_COLS))}{r1 - 1}"
|
||||
ws2.auto_filter.ref = f"A1:{get_column_letter(len(IMAGE_COLS))}{r2 - 1}"
|
||||
ws3.column_dimensions["A"].width = 90
|
||||
lines = [
|
||||
"填写说明",
|
||||
"",
|
||||
"1. 只需要填「逐人核对」里黄色底的 5 列:正确身份证号 / 正确姓名 / 正确银行卡号 / 判定 / 说明。",
|
||||
"2. 判定填 对 / 错 / 部分:整行都识别对了填 对;哪里错了填 错,并在说明里写清楚(例如「卡号错 2 位」)。",
|
||||
"3. 识别为空但实际有值的,正确列请照实填写(这是最有价值的样本)。",
|
||||
"4. 身份证校验 / Luhn 是识别结果自带的数学校验,不代表业务上一定对;以你填的为准。",
|
||||
"5. 填好后运行:python -m cardocr verify 本文件.xlsx,会自动算准确率。",
|
||||
"",
|
||||
"标记含义",
|
||||
" duplicate_photo 同一个人两列上传了同一张图(数据录入问题)",
|
||||
" missing_one_photo 只找到一张照片",
|
||||
" id_not_found 没有识别到身份证号",
|
||||
" id_checksum_fail 识别到 18 位号码但校验码不通过",
|
||||
" id_name_mismatch 身份证姓名与文件夹姓名不一致",
|
||||
" card_not_found 没有识别到银行卡号",
|
||||
" card_luhn_fail 识别到候选卡号但 Luhn 不通过",
|
||||
" card_length_odd 卡号位数不是 16/18/19",
|
||||
" low_resolution 原图短边 < 400px(多为缩略图)",
|
||||
" rotated_90 / rotated_270 照片是横拍的,已自动转正后识别",
|
||||
" multiple_cards_in_photo 一张照片里有不止一张卡",
|
||||
" card_not_located 没定位到卡片轮廓,按整图识别",
|
||||
"",
|
||||
f"本次统计:{stats['persons']} 人 / {stats['photos']} 张图;"
|
||||
f"身份证号有号码且校验通过 {id_ok} 人、有号码但校验失败 {id_bad} 人;"
|
||||
f"卡号 Luhn 通过 {card_ok} 人、有候选但未通过 {card_bad} 人。",
|
||||
f"图片根目录:{source_root}" if source_root else "",
|
||||
]
|
||||
for i, text in enumerate(lines, 1):
|
||||
c = ws3.cell(row=i, column=1, value=text)
|
||||
c.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
if i == 1:
|
||||
c.font = Font(bold=True, size=14)
|
||||
else:
|
||||
c.font = Font(size=10.5)
|
||||
|
||||
wb.save(path)
|
||||
return path
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 回读核对
|
||||
def verify_workbook(path: str) -> dict:
|
||||
"""读回填好的核对表,统计身份证号 / 卡号 / 姓名三项准确率。"""
|
||||
wb = load_workbook(path, data_only=True)
|
||||
ws = wb["逐人核对"]
|
||||
idx = {c.value: i for i, c in enumerate(ws[1], 1) if c.value}
|
||||
|
||||
def cell(row, name: str) -> str:
|
||||
i = idx.get(name)
|
||||
if not i:
|
||||
return ""
|
||||
v = row[i - 1].value
|
||||
return "" if v is None else str(v).strip()
|
||||
|
||||
res = {"rows": 0, "id": [0, 0, 0], "name": [0, 0, 0], "card": [0, 0, 0],
|
||||
"skipped": []}
|
||||
errors: List[dict] = []
|
||||
|
||||
def is_truth(v: str) -> bool:
|
||||
"""「人工也无法识别 / 无 / -」这类填写不算真值,跳过统计。"""
|
||||
return bool(v) and v not in ("无", "-", "/") and "无法识别" not in v
|
||||
|
||||
for row in ws.iter_rows(min_row=2):
|
||||
pid = cell(row, "ID")
|
||||
if not pid:
|
||||
continue
|
||||
t_id = cell(row, "【待填】正确身份证号")
|
||||
t_name = cell(row, "【待填】正确姓名")
|
||||
t_card = cell(row, "【待填】正确银行卡号")
|
||||
if not (t_id or t_name or t_card):
|
||||
continue
|
||||
res["rows"] += 1
|
||||
for label, v in (("身份证号", t_id), ("姓名", t_name), ("银行卡号", t_card)):
|
||||
if v and not is_truth(v):
|
||||
res["skipped"].append({"ID": pid, "字段": label, "填写": v})
|
||||
|
||||
def cmp(truth: str, got_key: str, bucket: List[int], label: str) -> None:
|
||||
if not is_truth(truth):
|
||||
return
|
||||
got = cell(row, got_key)
|
||||
if got == "未识别":
|
||||
got = ""
|
||||
ok = got.upper() == truth.upper()
|
||||
bucket[0] += 1
|
||||
bucket[1 if ok else 2] += 1
|
||||
if not ok:
|
||||
errors.append({"ID": pid, "姓名": cell(row, "姓名(文件夹)"), "字段": label,
|
||||
"识别": got, "正确": truth})
|
||||
|
||||
cmp(t_id, "身份证号(识别)", res["id"], "身份证号")
|
||||
cmp(t_name, "身份证姓名(识别)", res["name"], "姓名")
|
||||
cmp(t_card, "银行卡号(识别)", res["card"], "银行卡号")
|
||||
|
||||
out = {"核对行数": res["rows"], "明细": {}, "错误": errors,
|
||||
"跳过": res["skipped"]}
|
||||
for key, label in (("id", "身份证号"), ("name", "姓名"), ("card", "银行卡号")):
|
||||
total, right, wrong = res[key]
|
||||
out["明细"][label] = {
|
||||
"有真值": total, "正确": right, "错误": wrong,
|
||||
"准确率": f"{(right / total * 100 if total else 0):.1f}%",
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def print_verify(result: dict) -> None:
|
||||
print(f"核对行数:{result['核对行数']}")
|
||||
for label, d in result["明细"].items():
|
||||
print(f" {label}: 有真值 {d['有真值']},正确 {d['正确']},错误 {d['错误']},准确率 {d['准确率']}")
|
||||
if result["错误"]:
|
||||
print("\n错误明细:")
|
||||
for e in result["错误"]:
|
||||
print(f" {e['ID']} {e['姓名']} {e['字段']}:识别「{e['识别']}」 → 正确「{e['正确']}」")
|
||||
|
||||
|
||||
def load_persons(json_path: str) -> List[dict]:
|
||||
with open(json_path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data.get("persons") or data.get("images") or []
|
||||
|
||||
|
||||
def load_truth_workbook(path: str) -> Dict[str, Dict[str, str]]:
|
||||
"""读回人工填好的核对表:文件夹姓名 → {id, name, card}。"""
|
||||
wb = load_workbook(path, data_only=True)
|
||||
ws = wb["逐人核对"]
|
||||
idx = {c.value: i for i, c in enumerate(ws[1], 1) if c.value}
|
||||
out: Dict[str, Dict[str, str]] = {}
|
||||
for row in ws.iter_rows(min_row=2, values_only=True):
|
||||
def cell(name: str) -> str:
|
||||
i = idx.get(name)
|
||||
if not i:
|
||||
return ""
|
||||
v = row[i - 1]
|
||||
return "" if v is None else str(v).strip()
|
||||
|
||||
folder = cell("姓名(文件夹)")
|
||||
if not folder:
|
||||
continue
|
||||
out[folder] = {"id": cell("【待填】正确身份证号"),
|
||||
"name": cell("【待填】正确姓名"),
|
||||
"card": cell("【待填】正确银行卡号"),
|
||||
"note": cell("【待填】说明")}
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""号码校验与纠错:身份证 18 位校验码、银行卡 Luhn、OCR 易混字符还原。
|
||||
|
||||
两种号码都自带数学校验位,这让我们能把 OCR 出来的「b214 8338 3071 20bb」
|
||||
这类文本,在有限候选里反推出唯一合法号码——这是本模块敢离线跑的关键。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
|
||||
|
||||
# ---------------------------------------------------------------- 字符归一
|
||||
# OCR 把数字认成字母(或反过来)的常见映射;值是「可能对应的数字」
|
||||
_CONFUSABLE: Dict[str, Tuple[str, ...]] = {
|
||||
"O": ("0",), "o": ("0",), "D": ("0",),
|
||||
"I": ("1",), "l": ("1",), "|": ("1",), "!": ("1",),
|
||||
"L": ("1",), "Z": ("2",), "z": ("2",),
|
||||
"S": ("5",), "s": ("5",), "$": ("5",),
|
||||
"B": ("6", "8"), "b": ("6", "8"),
|
||||
"G": ("9", "6"), "g": ("9", "6"), "q": ("9", "6"),
|
||||
"A": ("4",), "a": ("4",), "E": ("8",), "e": ("8",),
|
||||
"T": ("7",), "t": ("7",), "C": ("0", "6"),
|
||||
"X": ("X",), "x": ("X",),
|
||||
}
|
||||
|
||||
PRIMARY: Dict[str, str] = {k: v[0] for k, v in _CONFUSABLE.items()}
|
||||
|
||||
|
||||
def normalize_text(text: str) -> str:
|
||||
"""全角转半角、去空白(OCR 常在数字间插空格)。"""
|
||||
out = []
|
||||
for ch in str(text or ""):
|
||||
o = ord(ch)
|
||||
if 0xFF01 <= o <= 0xFF5E: # 全角 ASCII
|
||||
ch = chr(o - 0xFEE0)
|
||||
elif o == 0x3000: # 全角空格
|
||||
ch = " "
|
||||
out.append(ch)
|
||||
return re.sub(r"\s+", "", "".join(out))
|
||||
|
||||
|
||||
def digitize(text: str) -> Tuple[str, List[int]]:
|
||||
"""把文本压成数字串(字母按首选映射),并返回「有歧义」的位置下标。"""
|
||||
s = normalize_text(text)
|
||||
digits, ambiguous = [], []
|
||||
for ch in s:
|
||||
if ch.isdigit():
|
||||
digits.append(ch)
|
||||
elif ch in _CONFUSABLE:
|
||||
digits.append(PRIMARY[ch])
|
||||
if len(_CONFUSABLE[ch]) > 1:
|
||||
ambiguous.append(len(digits) - 1)
|
||||
return "".join(digits), ambiguous
|
||||
|
||||
|
||||
def digit_runs(text: str, min_len: int = 13) -> List[str]:
|
||||
"""从一段文本里抽出连续数字串(允许中间夹易混字母)。"""
|
||||
s = normalize_text(text)
|
||||
# 把易混字母当数字,再做游程切分
|
||||
norm = "".join(PRIMARY.get(c, c) if not c.isdigit() else c for c in s)
|
||||
runs = re.findall(r"[0-9]{%d,}" % min_len, norm)
|
||||
return runs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 身份证
|
||||
# 18 位:6 位地址 + 8 位生日 + 3 位顺序 + 1 位校验
|
||||
_ID_WEIGHTS = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
|
||||
_ID_CHECK = "10X98765432"
|
||||
|
||||
|
||||
def id_checksum_ok(no: str) -> bool:
|
||||
if len(no) != 18:
|
||||
return False
|
||||
if not re.fullmatch(r"\d{17}[\dXx]", no):
|
||||
return False
|
||||
total = sum(int(no[i]) * _ID_WEIGHTS[i] for i in range(17))
|
||||
return _ID_CHECK[total % 11] == no[17].upper()
|
||||
|
||||
|
||||
def id_birth(no: str) -> str:
|
||||
"""从身份证号取生日 YYYY-MM-DD(含合法性检查,不合法返回空)。"""
|
||||
if len(no) != 18:
|
||||
return ""
|
||||
y, m, d = int(no[6:10]), int(no[10:12]), int(no[12:14])
|
||||
if not (1900 <= y <= 2020) or not (1 <= m <= 12) or not (1 <= d <= 31):
|
||||
return ""
|
||||
return f"{y:04d}-{m:02d}-{d:02d}"
|
||||
|
||||
|
||||
def id_gender(no: str) -> str:
|
||||
if len(no) != 18:
|
||||
return ""
|
||||
return "男" if int(no[16]) % 2 == 1 else "女"
|
||||
|
||||
|
||||
def id_region(no: str) -> str:
|
||||
return no[:2] if len(no) == 18 else ""
|
||||
|
||||
|
||||
_VALID_PROVINCE = {f"{i:02d}" for i in range(11, 66)}
|
||||
|
||||
|
||||
def id_plausible(no: str) -> bool:
|
||||
return (len(no) == 18
|
||||
and id_region(no) in _VALID_PROVINCE
|
||||
and bool(id_birth(no)))
|
||||
|
||||
|
||||
@dataclass
|
||||
class IdCandidate:
|
||||
number: str
|
||||
checksum_ok: bool
|
||||
origin: str = "raw" # raw / repaired
|
||||
edits: int = 0
|
||||
score: float = 0.0
|
||||
|
||||
|
||||
def id_candidates(text: Union[str, Sequence[str]], limit: int = 8) -> List[IdCandidate]:
|
||||
"""从 OCR 文本里找身份证号候选,并做 1~2 位纠错。
|
||||
|
||||
text 可以是单段文本,也可以是「行文本列表」(推荐:按行抓,避免跨行串号)。
|
||||
"""
|
||||
rows = [text] if isinstance(text, str) else list(text)
|
||||
seen: Dict[str, IdCandidate] = {}
|
||||
|
||||
def add(no: str, origin: str, edits: int) -> None:
|
||||
no = no.upper()
|
||||
if len(no) != 18:
|
||||
return
|
||||
c = seen.get(no)
|
||||
ok = id_checksum_ok(no)
|
||||
if c is None or (ok and not c.checksum_ok):
|
||||
seen[no] = IdCandidate(no, ok, origin, edits, score=0.0)
|
||||
|
||||
for row in rows:
|
||||
s = normalize_text(row)
|
||||
# 原始文本里的 18 位窗口(允许 X 结尾、允许混入易混字母)
|
||||
for raw in re.findall(r"[0-9OoIlLZzSBbGgqAaEeTtCc|!]{17}[0-9XxOoIl]", s):
|
||||
d, amb = digitize(raw)
|
||||
if len(d) == 18:
|
||||
add(d, "raw", 0)
|
||||
if len(amb) <= 4 and not id_checksum_ok(d):
|
||||
for combo in _enumerate_ambiguous(d, amb, limit=200):
|
||||
add(combo, "repaired", sum(1 for x, y in zip(d, combo) if x != y))
|
||||
# 纯数字窗口(含标签粘连)
|
||||
for m in re.finditer(r"\d{17}[\dXx]", s):
|
||||
add(m.group(0), "raw", 0)
|
||||
if not id_checksum_ok(m.group(0)):
|
||||
for combo in _one_digit_sub(m.group(0), limit=200):
|
||||
add(combo, "repaired", 1)
|
||||
|
||||
for c in seen.values():
|
||||
c.score = (3.0 if c.checksum_ok else 0.0) + (2.0 if id_plausible(c.number) else 0.0) \
|
||||
- 0.5 * c.edits
|
||||
return sorted(seen.values(), key=lambda x: -x.score)[:limit]
|
||||
|
||||
|
||||
def _enumerate_ambiguous(digits: str, positions: Sequence[int],
|
||||
limit: int = 200) -> List[str]:
|
||||
"""在歧义位置枚举替代数字。"""
|
||||
out = [digits]
|
||||
for pos in positions:
|
||||
ch = digits[pos]
|
||||
alts = [x for x in _CONFUSABLE.get(ch, ()) if x.isdigit()]
|
||||
if len(alts) <= 1:
|
||||
continue
|
||||
new = []
|
||||
for base in out:
|
||||
for a in alts:
|
||||
new.append(base[:pos] + a + base[pos + 1:])
|
||||
out = new[:limit]
|
||||
return out
|
||||
|
||||
|
||||
def _one_digit_sub(no: str, limit: int = 200) -> List[str]:
|
||||
out = []
|
||||
for i in range(len(no)):
|
||||
cur = no[i]
|
||||
for d in "0123456789":
|
||||
if d == cur:
|
||||
continue
|
||||
cand = no[:i] + d + no[i + 1:]
|
||||
if id_checksum_ok(cand) and id_plausible(cand):
|
||||
out.append(cand)
|
||||
if len(out) >= limit:
|
||||
return out
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 银行卡
|
||||
def luhn_ok(no: str) -> bool:
|
||||
if not no or not no.isdigit() or not (13 <= len(no) <= 19):
|
||||
return False
|
||||
total, alt = 0, False
|
||||
for ch in reversed(no):
|
||||
d = int(ch)
|
||||
if alt:
|
||||
d *= 2
|
||||
if d > 9:
|
||||
d -= 9
|
||||
total += d
|
||||
alt = not alt
|
||||
return total % 10 == 0
|
||||
|
||||
|
||||
def luhn_check_digit(prefix: str) -> str:
|
||||
"""给前 n-1 位算 Luhn 校验位。"""
|
||||
total, alt = 0, True
|
||||
for ch in reversed(prefix):
|
||||
d = int(ch)
|
||||
if alt:
|
||||
d *= 2
|
||||
if d > 9:
|
||||
d -= 9
|
||||
total += d
|
||||
alt = not alt
|
||||
return str((10 - total % 10) % 10)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CardCandidate:
|
||||
number: str
|
||||
digits: int
|
||||
luhn_ok: bool
|
||||
prefix: str = ""
|
||||
bank: str = ""
|
||||
origin: str = "raw" # raw / consensus / repaired
|
||||
edits: int = 0
|
||||
votes: int = 1
|
||||
score: float = 0.0
|
||||
|
||||
|
||||
# 常见储蓄卡 BIN(6 位)→ 银行;只收录能确认的,其余留给卡面文字判断。
|
||||
# 与插件 XQ0005「银行卡检查」的已核验工资卡 BIN 对齐(重庆农商/三峡等本地卡种),
|
||||
# 同一 BIN 只能对应一家银行,勿重复登记(Python dict 重复键会静默覆盖)。
|
||||
BIN_BANK: Dict[str, str] = {
|
||||
# 工商银行
|
||||
"622200": "中国工商银行", "622202": "中国工商银行", "622203": "中国工商银行",
|
||||
"622208": "中国工商银行", "621225": "中国工商银行", "621226": "中国工商银行",
|
||||
"955880": "中国工商银行", "955882": "中国工商银行",
|
||||
# 农业银行
|
||||
"621336": "中国农业银行", "622841": "中国农业银行", "622845": "中国农业银行",
|
||||
"622846": "中国农业银行", "622848": "中国农业银行", "622849": "中国农业银行",
|
||||
# 建设银行
|
||||
"621081": "中国建设银行", "621499": "中国建设银行", "621700": "中国建设银行",
|
||||
"622280": "中国建设银行", "622700": "中国建设银行", "436742": "中国建设银行",
|
||||
# 中国银行
|
||||
"456351": "中国银行", "601382": "中国银行", "621660": "中国银行",
|
||||
"621661": "中国银行", "621662": "中国银行", "621663": "中国银行",
|
||||
"621665": "中国银行", "621785": "中国银行", "621786": "中国银行",
|
||||
"621787": "中国银行", "621788": "中国银行", "621789": "中国银行",
|
||||
# 招商银行
|
||||
"621286": "招商银行", "621483": "招商银行", "621485": "招商银行",
|
||||
"621486": "招商银行", "622575": "招商银行", "622576": "招商银行",
|
||||
"622577": "招商银行", "622578": "招商银行", "622579": "招商银行",
|
||||
"622588": "招商银行", "622609": "招商银行",
|
||||
# 民生银行
|
||||
"421393": "中国民生银行", "621691": "中国民生银行", "622600": "中国民生银行",
|
||||
"622601": "中国民生银行", "622602": "中国民生银行", "622603": "中国民生银行",
|
||||
"622615": "中国民生银行", "622617": "中国民生银行", "622619": "中国民生银行",
|
||||
"622620": "中国民生银行", "622621": "中国民生银行", "622622": "中国民生银行",
|
||||
"622623": "中国民生银行",
|
||||
# 兴业银行
|
||||
"621084": "兴业银行", "622908": "兴业银行", "622909": "兴业银行",
|
||||
# 浦发银行
|
||||
"621792": "浦发银行", "621793": "浦发银行", "622516": "浦发银行",
|
||||
"622517": "浦发银行", "622518": "浦发银行", "622521": "浦发银行",
|
||||
"622522": "浦发银行", "622523": "浦发银行", "622525": "浦发银行",
|
||||
"622526": "浦发银行",
|
||||
# 交通银行
|
||||
"622250": "交通银行", "622251": "交通银行", "622252": "交通银行",
|
||||
"622253": "交通银行", "622254": "交通银行", "622255": "交通银行",
|
||||
"622260": "交通银行", "622262": "交通银行",
|
||||
# 邮储银行
|
||||
"620062": "中国邮政储蓄银行", "621095": "中国邮政储蓄银行",
|
||||
"622188": "中国邮政储蓄银行", "622199": "中国邮政储蓄银行",
|
||||
"955100": "中国邮政储蓄银行",
|
||||
# 中信 / 光大 / 华夏 / 广发 / 平安
|
||||
"622690": "中信银行", "622691": "中信银行", "622692": "中信银行",
|
||||
"622660": "中国光大银行", "622661": "中国光大银行", "622662": "中国光大银行",
|
||||
"622630": "华夏银行", "622631": "华夏银行", "622632": "华夏银行",
|
||||
"623020": "华夏银行",
|
||||
"622568": "广发银行",
|
||||
"622155": "平安银行", "622156": "平安银行", "622157": "平安银行",
|
||||
# 重庆本地(工资卡主力卡种,XQ0005 实际数据核验)
|
||||
"621258": "重庆农村商业银行", "621465": "重庆农村商业银行",
|
||||
"621528": "重庆农村商业银行", "622867": "重庆农村商业银行",
|
||||
"621755": "重庆三峡银行",
|
||||
}
|
||||
|
||||
|
||||
def bin_bank(no: str) -> str:
|
||||
return BIN_BANK.get(no[:6], "") if len(no) >= 6 else ""
|
||||
|
||||
|
||||
def prefix_ok(no: str) -> bool:
|
||||
"""前缀是否像一张国内借记卡:62 开头,或命中已知 BIN(含 4/6/9 开头的老卡)。"""
|
||||
return bool(bin_bank(no)) or no.startswith("62")
|
||||
|
||||
|
||||
def _id_like(no: str) -> bool:
|
||||
"""18 位且通过身份证校验码、又不是 62 开头 → 基本可判定是身份证号,不是卡号。"""
|
||||
return len(no) == 18 and id_checksum_ok(no) and not no.startswith("62")
|
||||
|
||||
|
||||
def card_candidates(text: Union[str, Sequence[str]], want_lengths: Sequence[int] = (16, 19, 18),
|
||||
limit: int = 8, exclude: Sequence[str] = ()) -> List[CardCandidate]:
|
||||
"""从 OCR 文本里找卡号候选:游程 + 歧义枚举 + Luhn 校验。
|
||||
|
||||
Args:
|
||||
text: 单段文本或「行文本列表」(推荐按行传,避免跨行把两行数字连起来)。
|
||||
exclude: 已知的身份证号等「长得像卡号」的号码,直接排除。
|
||||
"""
|
||||
excludes = {normalize_text(x).upper() for x in exclude if x}
|
||||
rows = [text] if isinstance(text, str) else list(text)
|
||||
runs: List[str] = []
|
||||
for row in rows:
|
||||
norm = normalize_text(row)
|
||||
cur: List[str] = []
|
||||
for ch in norm:
|
||||
if ch.isdigit():
|
||||
cur.append(ch)
|
||||
elif ch in _CONFUSABLE:
|
||||
cur.append(PRIMARY[ch])
|
||||
else:
|
||||
if len(cur) >= 13:
|
||||
runs.append("".join(cur))
|
||||
cur = []
|
||||
if len(cur) >= 13:
|
||||
runs.append("".join(cur))
|
||||
|
||||
seen: Dict[str, CardCandidate] = {}
|
||||
|
||||
def add(no: str, origin: str, edits: int, votes: int = 1) -> None:
|
||||
if no in excludes or _id_like(no) or not prefix_ok(no):
|
||||
return
|
||||
ok = luhn_ok(no)
|
||||
if not ok and origin == "raw":
|
||||
return
|
||||
c = seen.get(no)
|
||||
if c is None:
|
||||
seen[no] = CardCandidate(number=no, digits=len(no), luhn_ok=ok,
|
||||
prefix=no[:6], bank=bin_bank(no),
|
||||
origin=origin, edits=edits, votes=votes)
|
||||
else:
|
||||
c.votes += votes
|
||||
c.luhn_ok = c.luhn_ok or ok
|
||||
|
||||
for run in runs:
|
||||
if run in excludes or _id_like(run) or not prefix_ok(run):
|
||||
continue
|
||||
add(run, "raw", 0)
|
||||
if luhn_ok(run):
|
||||
continue
|
||||
# 歧义位置枚举;只有唯一解才敢认定(多个解 = 不知道错在哪,宁可标人工)
|
||||
if 13 <= len(run) <= 19:
|
||||
solutions = _luhn_repair(run, max_edits=1)
|
||||
for s in solutions:
|
||||
add(s, "repaired", 1)
|
||||
# 多遍 OCR 的「共识」由上层合并;这里只保证数量
|
||||
cands = [c for c in seen.values() if c.luhn_ok]
|
||||
for c in cands:
|
||||
c.score = (4.0 if c.luhn_ok else 0.0) \
|
||||
+ (2.0 if c.digits in want_lengths else 0.0) \
|
||||
+ (1.0 if c.bank else 0.0) \
|
||||
+ 0.5 * min(c.votes, 4) - 0.5 * c.edits
|
||||
return sorted(cands, key=lambda x: -x.score)[:limit]
|
||||
|
||||
|
||||
def _luhn_repair(no: str, max_edits: int = 1) -> List[str]:
|
||||
"""返回「能通过 Luhn 的最少改动解」;多于一个解视为歧义,返回空。
|
||||
|
||||
卡号错一位时,Luhn 往往还能匹配出 5~9 种改法。若无其它证据(例如另一处
|
||||
小字印的同一卡号、卡面 BIN),宁可不认,避免把身份证号「纠」成合法卡号。
|
||||
"""
|
||||
if luhn_ok(no):
|
||||
return [no]
|
||||
found: List[str] = []
|
||||
if max_edits >= 1:
|
||||
for i in range(len(no)):
|
||||
for d in "0123456789":
|
||||
if d == no[i]:
|
||||
continue
|
||||
cand = no[:i] + d + no[i + 1:]
|
||||
if luhn_ok(cand):
|
||||
found.append(cand)
|
||||
if len(found) > 1:
|
||||
return []
|
||||
if max_edits >= 2 and not found:
|
||||
for i in range(len(no)):
|
||||
for j in range(i + 1, len(no)):
|
||||
for d1 in "0123456789":
|
||||
for d2 in "0123456789":
|
||||
cand = no[:i] + d1 + no[i + 1:j] + d2 + no[j + 1:]
|
||||
if luhn_ok(cand):
|
||||
found.append(cand)
|
||||
if len(found) > 1:
|
||||
return []
|
||||
return found
|
||||
|
||||
|
||||
def consensus(numbers: Iterable[str]) -> List[str]:
|
||||
"""多数投票:同长度、逐位取众数(用于多遍 OCR 结果合并)。"""
|
||||
groups: Dict[int, List[str]] = {}
|
||||
for n in numbers:
|
||||
if n.isdigit():
|
||||
groups.setdefault(len(n), []).append(n)
|
||||
out = []
|
||||
for length, items in groups.items():
|
||||
if not items:
|
||||
continue
|
||||
votes = []
|
||||
for i in range(length):
|
||||
counts: Dict[str, int] = {}
|
||||
for it in items:
|
||||
counts[it[i]] = counts.get(it[i], 0) + 1
|
||||
votes.append(max(counts.items(), key=lambda kv: kv[1])[0])
|
||||
cand = "".join(votes)
|
||||
score = sum(1 for it in items if it == cand)
|
||||
if score >= max(2, len(items) // 2 + 1):
|
||||
out.append(cand)
|
||||
return out
|
||||
@@ -0,0 +1,283 @@
|
||||
# -*- 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
|
||||
Binary file not shown.
@@ -0,0 +1,24 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=64"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "cardreader"
|
||||
version = "0.1.0"
|
||||
description = "卡证识别 SDK(自包含):身份证/银行卡照片分析 + 卡号读取,YOLO 卡面定位 + 多视角投票 + 号带掩码"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
"opencv-python>=4.5",
|
||||
"numpy>=1.20",
|
||||
"pillow>=9.0",
|
||||
"onnxruntime>=1.16",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/37du/37duAutomation"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["cardreader", "cardreader.cardocr"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
cardreader = ["models/*.onnx"]
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "cardreader",
|
||||
"name": "卡证识别 SDK",
|
||||
"version": "0.1.0",
|
||||
"description": "卡证识别 SDK(自包含):身份证/银行卡照片分析、银行卡号读取(YOLO 卡面定位 + 多视角 OCR 投票 + 号带掩码密集搜索,压印银字/反光),自带检测模型",
|
||||
"provides": [
|
||||
"cardreader"
|
||||
],
|
||||
"deps": [
|
||||
"cv2",
|
||||
"numpy",
|
||||
"PIL",
|
||||
"onnxruntime"
|
||||
],
|
||||
"python": ">=3.9",
|
||||
"minRuntimeVersion": "",
|
||||
"selftest": "cardreader._selftest:main",
|
||||
"api": "api.json"
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
流程编排:
|
||||
1) 读取 AI 表格「银行卡-变更收集表」,只取「是否更新HR系统」为空或「否」的记录;
|
||||
2) 下载银行卡卡号面照片、持卡人身份证照片;
|
||||
3) desktopauto.cardocr 识别卡号/身份证号/姓名/开户银行,与表格登记值比对;
|
||||
3) cardreader 识别卡号/身份证号/姓名/开户银行,与表格登记值比对;
|
||||
4) 关闭试算模式时,核对通过的记录导入 HR「工资管理-工资卡管理」,成功后在 AI 表格回写
|
||||
「是否更新HR系统=是」;开启试算模式 = 只核对出表(不写 HR、不回写台账);
|
||||
5) 输出核对工作簿(核对结果 + 异常名单),识别不出或不一致的推送钉钉群提醒人事手动处理。
|
||||
@@ -31,7 +31,7 @@ class BankCardEhrUpdatePlugin(ScenePlugin):
|
||||
|
||||
id = "xq0084"
|
||||
name = "银行卡更新EHR系统"
|
||||
version = "0.1.8"
|
||||
version = "0.2.0"
|
||||
description = ("读取人资 AI 表格「银行卡变更收集表」中「是否更新HR系统」为空或「否」的记录,"
|
||||
"下载银行卡与身份证照片识别卡号、身份证号、姓名、开户银行,"
|
||||
"与表格登记值比对;核对通过自动导入 HR 工资卡并回写「是否更新HR系统=是」,"
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
"""XQ0084 银行卡更新EHR系统 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖 Python 标准库 / 第三方库 / 执行机挂载的 SDK
|
||||
(desktopauto、dingtalk_sdk),不 import 任何插件包之外的业务代码。
|
||||
(cardreader、dingtalk_sdk、hr_sdk),不 import 任何插件包之外的业务代码。
|
||||
|
||||
当前实现范围(第一阶段):
|
||||
1) 从 AI 表格「37°人资领域相关工作台账-银行卡变更收集表」拉取待处理行;
|
||||
2) 下载员工上传的银行卡卡号面照片、持卡人身份证照片;
|
||||
3) 用 desktopauto.cardocr 识别卡号/身份证号/姓名/开户银行,与表格登记值比对;
|
||||
3) 用 cardreader 识别卡号/身份证号/姓名/开户银行,与表格登记值比对;
|
||||
4) 输出核对工作簿;识别不出或不一致的进异常名单,推送钉钉群提醒人事手动处理。
|
||||
HR 系统「薪资管理-工资数据-工资卡管理」的写入留到后续阶段。
|
||||
"""
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0084 识别层:调用 desktopauto 的银行卡/身份证识别能力。"""
|
||||
"""XQ0084 识别层:cardreader 常规识别 + 卡面检测补读银行卡号。
|
||||
|
||||
常规通道(cardreader 的 analyze_image)负责身份证与银行卡的整体识别;
|
||||
银行卡号读不出 Luhn 合法值时,再用 cardreader 的 read_card(YOLO 找卡 +
|
||||
多视角投票)兜底,仍不行才走浮雕增强候选,最终交人工核对。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from .. import config
|
||||
|
||||
_CONF_RANK = {"high": 3, "medium": 2, "low": 1}
|
||||
|
||||
#: 卡面检测模块探测结果:None=未探测,False=不可用(依赖缺失,后续不再重试)
|
||||
_reader = None
|
||||
_reader_failed = False
|
||||
|
||||
|
||||
def _digit_runs(results):
|
||||
runs = []
|
||||
@@ -22,11 +35,57 @@ def _best(results, kind, prefer):
|
||||
len(str(c.get("number") or ""))))
|
||||
|
||||
|
||||
def _read_card():
|
||||
"""懒加载卡面识别 SDK;未挂载或依赖缺失时降级为只用常规通道。"""
|
||||
global _reader, _reader_failed
|
||||
if _reader is None and not _reader_failed:
|
||||
try:
|
||||
from cardreader import read_card
|
||||
_reader = read_card
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_reader_failed = True
|
||||
config.logger.warning("卡面识别 SDK(cardreader)不可用,卡号只走常规通道:%s", exc)
|
||||
return _reader
|
||||
|
||||
|
||||
def _rank(result):
|
||||
return (1 if result.luhn_ok else 0, _CONF_RANK.get(result.confidence, 0),
|
||||
int(result.votes or 0))
|
||||
|
||||
|
||||
def _cardreader(paths, prefer=()):
|
||||
"""卡面检测补读卡号,返回最优 Result;模块不可用或全部失败返回 None。
|
||||
|
||||
先 balanced;若检测到银行卡但仍未读出合法卡号,再用 thorough
|
||||
(号带掩码密集搜索,专治压印银字/反光)。优先读常规通道已有银行卡痕迹的照片。
|
||||
"""
|
||||
read_card = _read_card()
|
||||
if read_card is None:
|
||||
return None
|
||||
order = [p for p in paths if p in prefer] + [p for p in paths if p not in prefer]
|
||||
best = None
|
||||
for path in order:
|
||||
try:
|
||||
cur = read_card(path, mode="balanced")
|
||||
if not cur.luhn_ok and "bank_card" in (cur.kinds or []):
|
||||
deep = read_card(path, mode="thorough")
|
||||
if _rank(deep) > _rank(cur):
|
||||
cur = deep
|
||||
except Exception as exc: # noqa: BLE001
|
||||
config.logger.warning("卡面检测失败(%s):%s", os.path.basename(str(path)), exc)
|
||||
continue
|
||||
if best is None or _rank(cur) > _rank(best):
|
||||
best = cur
|
||||
if cur.luhn_ok and cur.confidence == "high":
|
||||
break
|
||||
return best
|
||||
|
||||
|
||||
def _enhance(paths, bank_hint):
|
||||
"""常规识别读不出卡号时,用浮雕增强接口兜底(只采信 Luhn 自身合法的高置信结果)。"""
|
||||
try:
|
||||
from desktopauto import read_bank_card_number
|
||||
except Exception: # noqa: BLE001 老版本 SDK 没有该接口
|
||||
from cardreader import read_bank_card_number
|
||||
except Exception: # noqa: BLE001 依赖缺失时只用常规通道
|
||||
return None
|
||||
best = None
|
||||
for path in paths:
|
||||
@@ -52,7 +111,7 @@ def recognize(paths, expected_name=""):
|
||||
Returns:
|
||||
{"id": {...}, "bank": {...}, "runs": [...], "errors": [...], "files": [...]}
|
||||
"""
|
||||
from desktopauto.cardocr.pipeline import analyze_image
|
||||
from cardreader import analyze_image
|
||||
|
||||
results, errors = [], []
|
||||
for path in paths:
|
||||
@@ -68,17 +127,31 @@ def recognize(paths, expected_name=""):
|
||||
"bank": str(bk.get("bank") or ""),
|
||||
"luhn_ok": bool(bk.get("luhn_ok")),
|
||||
}
|
||||
# 常规通道没读到可信卡号:浮雕/反光增强兜底;仍不合法则只留候选,交人工
|
||||
# 常规通道没读到可信卡号:先用内置卡面检测补读
|
||||
if not bank["luhn_ok"]:
|
||||
enh = _enhance(paths, bank["bank"])
|
||||
if enh is not None and enh.status == "ok":
|
||||
bank.update(number=enh.number, bank=enh.bank or bank["bank"],
|
||||
luhn_ok=True, confidence=enh.confidence, source="enhance")
|
||||
elif enh is not None:
|
||||
bank["confidence"] = enh.confidence
|
||||
# 只有「差 1~2 位就能通过校验」的候选才值得给人看;差太多的是噪声
|
||||
if enh.candidates and enh.candidates[0].get("cost", 9) <= 2:
|
||||
bank["candidates"] = [c["number"] for c in enh.candidates]
|
||||
prefer = [p for p, r in zip(paths, results)
|
||||
if (r.get("bank_card") or {}).get("number")
|
||||
or (r.get("bank_card") or {}).get("bank")]
|
||||
extra = _cardreader(paths, prefer)
|
||||
if extra is not None and extra.luhn_ok:
|
||||
bank.update(number=extra.number, luhn_ok=True,
|
||||
confidence=extra.confidence,
|
||||
source=f"卡面检测({extra.source or 'detect'},票数 {extra.votes})")
|
||||
config.logger.info("卡面检测补读卡号成功:%s(%s,票数 %d)",
|
||||
extra.number, extra.confidence, extra.votes)
|
||||
else:
|
||||
if extra is not None and "bank_card" in (extra.kinds or []):
|
||||
bank["confidence"] = "low" # 检测到卡但没读准,交人工对照影像
|
||||
# 卡面检测也没读准:再走浮雕增强兜底,仍不合法则只留候选
|
||||
enh = _enhance(paths, bank["bank"])
|
||||
if enh is not None and enh.status == "ok":
|
||||
bank.update(number=enh.number, bank=enh.bank or bank["bank"],
|
||||
luhn_ok=True, confidence=enh.confidence, source="enhance")
|
||||
elif enh is not None:
|
||||
bank["confidence"] = enh.confidence
|
||||
# 只有「差 1~2 位就能通过校验」的候选才值得给人看;差太多的是噪声
|
||||
if enh.candidates and enh.candidates[0].get("cost", 9) <= 2:
|
||||
bank["candidates"] = [c["number"] for c in enh.candidates]
|
||||
return {
|
||||
"id": {
|
||||
"number": str(idc.get("number") or ""),
|
||||
|
||||
@@ -10,8 +10,8 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from desktopauto.cardocr.match import EXACT, PARTIAL, STRONG, WEAK, coverage, digits
|
||||
from desktopauto.cardocr.validators import bin_bank, id_checksum_ok, luhn_ok
|
||||
from cardreader.cardocr.match import EXACT, PARTIAL, STRONG, WEAK, coverage, digits
|
||||
from cardreader.cardocr.validators import bin_bank, id_checksum_ok, luhn_ok
|
||||
|
||||
from .. import config
|
||||
|
||||
@@ -157,7 +157,7 @@ def verify(item, ocr):
|
||||
base["name_status"] = "一致" if ocr_name.replace(" ", "") == holder.replace(" ", "") else "不一致"
|
||||
bank_status = compare_bank(table_bank, ocr_bank)
|
||||
bank_note = ""
|
||||
# 影像没读出银行名时,用卡号 BIN 兜底判定(BIN 表见 desktopauto validators.BIN_BANK)
|
||||
# 影像没读出银行名时,用卡号 BIN 兜底判定(BIN 表见 cardreader validators.BIN_BANK)
|
||||
bin_guess = bin_bank(ocr_card) or bin_bank(table_card)
|
||||
if bank_status == "无法识别" and bin_guess and config.text(table_bank):
|
||||
if compare_bank(table_bank, bin_guess) == "一致":
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0084",
|
||||
"name": "银行卡更新EHR系统",
|
||||
"version": "0.1.8",
|
||||
"version": "0.2.0",
|
||||
"description": "读取人资 AI 表格「银行卡变更收集表」中「是否更新HR系统」为空或「否」的记录,下载银行卡与身份证照片识别卡号、身份证号、姓名、开户银行并比对;支持「试算模式」(默认开启):只核对并输出核对表(结论 + 说明),不写 HR、不回写台账;关闭后核对通过自动导入 HR 工资卡管理并回写「是否更新HR系统=是」,不一致或识别不出进异常名单提醒人事手动处理。",
|
||||
"category": "人事薪酬",
|
||||
"icon": "",
|
||||
@@ -15,8 +15,8 @@
|
||||
},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"desktopauto": {
|
||||
"compat": "^0.5"
|
||||
"cardreader": {
|
||||
"compat": "^0.1"
|
||||
},
|
||||
"dingtalk_sdk": {
|
||||
"compat": "^0.1.3"
|
||||
|
||||
Reference in New Issue
Block a user