import re from dataclasses import dataclass from enum import Enum from typing import Tuple, List import cv2 import numpy as np from paddleocr import PaddleOCR from core.line_parser import LineParser class Direction(Enum): TOP = 0 RIGHT = 1 BOTTOM = 2 LEFT = 3 # 父类 class OcrAnchor(object): # 输入识别anchor的名字, 如身份证号 def __init__(self, name: str, d: List[Direction]): self.name = name # anchor位置 self.direction = d def t_func(anchor, c, is_horizontal): if is_horizontal: return 0 if anchor[1] < c[1] else 2 else: return 1 if anchor[0] > c[0] else 3 def l_func(anchor, c, is_horizontal): if is_horizontal: return 0 if anchor[0] < c[0] else 2 else: return 1 if anchor[1] < c[1] else 3 def b_func(anchor, c, is_horizontal): if is_horizontal: return 0 if anchor[1] > c[1] else 2 else: return 1 if anchor[0] < c[0] else 3 def r_func(anchor, c, is_horizontal): if is_horizontal: return 0 if anchor[0] > c[0] else 2 else: return 1 if anchor[1] > c[1] else 3 self.direction_funcs = { Direction.TOP: t_func, Direction.BOTTOM: b_func, Direction.LEFT: l_func, Direction.RIGHT: r_func, } # 获取中心区域坐标 -> (x, y) def get_rec_area(self, res) -> Tuple[float, float]: """获得整张身份证的识别区域, 返回识别区域的中心点""" boxes = [] for row in res: for r in row: boxes.extend(r.box) boxes = np.stack(boxes) l, t = np.min(boxes, 0) r, b = np.max(boxes, 0) return (l + r) / 2, (t + b) / 2 def is_anchor(self, txt, box) -> bool: pass def find_anchor(self, res) -> Tuple[bool, float, float]: """ 寻找锚点 中心点坐标 """ for row in res: for r in row: txt = r.txt.replace('-', '').replace(' ', '') box = r.box if self.is_anchor(txt, box): l, t = np.min(box, 0) r, b = np.max(box, 0) return True, (l + r) / 2, (t + b) / 2 return False, 0., 0. # 定位 锚点 -> 角度 def locate_anchor(self, res, is_horizontal) -> int: found, id_cx, id_cy = self.find_anchor(res) # 如果识别不到身份证号 if not found: raise Exception(f'识别不到anchor{self.name}') cx, cy = self.get_rec_area(res) # print(f'id_cx: {id_cx}, id_cy: {id_cy}') # print(f'cx: {cx}, cy: {cy}') pre = None for d in self.direction: f = self.direction_funcs.get(d, None) angle = f((id_cx, id_cy), (cx, cy), is_horizontal) if pre is None: pre = angle else: if angle != pre: raise Exception('angle is not compatiable') return pre # 子类1 人像面 class FrontSideAnchor(OcrAnchor): def __init__(self, name: str, d: List[Direction]): super(FrontSideAnchor, self).__init__(name, d) def is_anchor(self, txt, box) -> bool: txts = re.findall('\d{10,18}', txt) if len(txts) > 0: return True return False def locate_anchor(self, res, is_horizontal) -> int: return super(FrontSideAnchor, self).locate_anchor(res, is_horizontal) # 子类2 国徽面 class BackSideAnchor(OcrAnchor): def __init__(self, name: str, d: List[Direction]): super(BackSideAnchor, self).__init__(name, d) def is_anchor(self, txt, box) -> bool: txt = txt.replace('.', '') txts = re.findall('有效期', txt) if len(txts) > 0: return True return False def locate_anchor(self, res, is_horizontal) -> int: return super(BackSideAnchor, self).locate_anchor(res, is_horizontal) def detect_angle(result, ocr_anchor: OcrAnchor): filters = [lambda x: x.is_slope, lambda x: x.txt.replace(' ', '').encode('utf-8').isalpha()] lp = LineParser(result, filters) res = lp.parse() print('------ angle ocr -------') print(res) print('------ angle ocr -------') is_horizontal = lp.is_horizontal return ocr_anchor.locate_anchor(res, is_horizontal) @dataclass class AngleDetector(object): """ 角度检测器 """ ocr: PaddleOCR def detect_angle(self, img, image_type): image_type = int(image_type) ocr_anchor = BackSideAnchor('有效期', [Direction.BOTTOM]) if image_type != 0 else FrontSideAnchor('身份证号', [ Direction.BOTTOM]) result = self.ocr.ocr(img, cls=True) if not result: raise Exception("对不起,未识别到有效区域,请检查后上传,谢谢") try: angle = detect_angle(result, ocr_anchor) return angle, result except Exception as e: print(e) # 如果第一次识别不到,旋转90度再识别 img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) result = self.ocr.ocr(img, cls=True) angle = detect_angle(result, ocr_anchor) # 旋转90度之后要重新计算角度 return (angle - 1 + 4) % 4, result