ocr.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from dataclasses import dataclass
  2. from core.parser import *
  3. from core.direction import *
  4. import numpy as np
  5. from paddleocr import PaddleOCR
  6. @dataclass
  7. class IdCardOcr:
  8. ocr: PaddleOCR
  9. angle_detector: AngleDetector
  10. def predict(self, image: np.ndarray, image_type: str = '0'):
  11. # image, angle = self._pre_process(image)
  12. txts, confs, result = self._ocr(image)
  13. angle = self.angle_detector.detect_angle(image, result)
  14. if int(image_type) == 0:
  15. parser = FrontParser(txts, confs)
  16. elif int(image_type) == 1:
  17. parser = BackParser(txts, confs)
  18. else:
  19. raise Exception('无法识别')
  20. return self._post_process(angle, parser, image_type)
  21. def _pre_process(self, image) -> (np.ndarray, int):
  22. angle = detect_angle(image)
  23. print(angle) # 逆时针
  24. if angle == 180:
  25. image = cv2.rotate(image, cv2.ROTATE_180)
  26. if angle == 90:
  27. image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
  28. if angle == 270:
  29. image = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
  30. return image, angle
  31. def _ocr(self, image):
  32. # 获取模型检测结果
  33. result = self.ocr.ocr(image, cls=True)
  34. print("------------------")
  35. print(result)
  36. if not result:
  37. raise Exception('无法识别')
  38. confs = [line[1][1] for line in result]
  39. # 将检测到的文字放到一个列表中
  40. txts = [line[1][0] for line in result]
  41. # print("......................................")
  42. # print(txts)
  43. # print("......................................")
  44. return txts, confs, result
  45. def _post_process(self, angle: int, parser: Parser, image_type: str):
  46. ocr_res = parser.parse()
  47. conf = parser.confidence
  48. res = {
  49. "confidence": conf,
  50. "card_type": image_type,
  51. "orientation": angle // 90, # 原angle是逆时针,转成顺时针
  52. **ocr_res
  53. }
  54. print(res)
  55. return res