123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- import time
- from dataclasses import dataclass
- from typing import Any
- from core.line_parser import LineParser
- from core.parser import *
- from core.direction import *
- import numpy as np
- from paddleocr import PaddleOCR
- @dataclass
- class CetOcr:
- ocr: PaddleOCR
- # 角度探测器
- angle_detector: AngleDetector
- # 检测
- def predict(self, image: np.ndarray) -> ():
- image, angle, result, image_type = self._pre_process(image)
- cv2.imwrite('dd.jpg', image)
- print(f'---------- detect angle: {angle} 角度 --------')
- if angle != 0:
- _, _, result = self._ocr(image)
- return self._post_process(result, angle, image_type)
- def _pre_process(self, image) -> (np.ndarray, int, Any):
- # pic角度 result(ocr生)
- angle, result, image_type = self.angle_detector.detect_angle(image)
- if angle == 1:
- image = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
- if angle == 2:
- image = cv2.rotate(image, cv2.ROTATE_180)
- if angle == 3:
- image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
- return image, angle, result, image_type
- def _ocr(self, image):
- result = self.ocr.ocr(image, cls=True)
- if not result:
- raise Exception('无法识别')
- confs = [line[1][1] for line in result]
- # 将检测到的文字放到一个列表中
- txts = [line[1][0] for line in result]
- return txts, confs, result
- def _post_process(self, result, angle: int, image_type):
- filters = [lambda x: x.is_slope, lambda x: x.txt.replace(' ', '').encode('utf-8').isalpha()]
- line_parser = LineParser(result, filters)
- line_result = line_parser.parse()
- print('-------------')
- print(line_result)
- print('-------------')
- conf = line_parser.confidence
- if int(image_type) == 0:
- parser = CETParser(line_result)
- elif int(image_type) == 1:
- parser = TEMParser(line_result)
- else:
- raise Exception('无法识别')
- ocr_res = parser.parse()
- res = {
- "confidence": conf,
- "orientation": angle, # 原angle是逆时针,转成顺时针
- **ocr_res
- }
- print(res)
- return res
|