line_parser.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import numpy as np
  2. from dataclasses import dataclass
  3. # result 对象
  4. from utils.time import timeit
  5. @dataclass
  6. class OcrResult(object):
  7. box: np.ndarray
  8. txt: str
  9. conf: float
  10. def __hash__(self):
  11. return hash(repr(self))
  12. def __repr__(self):
  13. return f'txt: {self.txt}, box: {self.box.tolist()}, conf: {self.conf}'
  14. @property
  15. def lt(self):
  16. l, t = np.min(self.box, 0)
  17. return [l, t]
  18. @property
  19. def rb(self):
  20. r, b = np.max(self.box, 0)
  21. return [r, b]
  22. @property
  23. def wh(self):
  24. l, t = self.lt
  25. r, b = self.rb
  26. return [r - l, b - t]
  27. @property
  28. def area(self):
  29. w, h = self.wh
  30. return w * h
  31. @property
  32. def is_slope(self):
  33. p0 = self.box[0]
  34. p1 = self.box[1]
  35. if p0[0] == p1[0]:
  36. return False
  37. slope = abs(1. * (p0[1] - p1[1]) / (p0[0] - p1[0]))
  38. return 0.4 < slope < 2.5
  39. @property
  40. def center(self):
  41. l, t = self.lt
  42. r, b = self.rb
  43. return [(r + l) / 2, (b + t) / 2]
  44. def one_line(self, b, is_horizontal, eps: float = 20.0) -> bool:
  45. y_idx = 0 + is_horizontal
  46. x_idx = 1 - y_idx
  47. if b.lt[x_idx] < self.lt[x_idx] < self.rb[x_idx] < b.rb[x_idx]: return False
  48. if self.lt[x_idx] < b.lt[x_idx] < b.rb[x_idx] < self.rb[x_idx]: return False
  49. eps = 0.45 * (self.wh[y_idx] + b.wh[y_idx])
  50. dist = abs(self.center[y_idx] - b.center[y_idx])
  51. return dist < eps
  52. def one_row(self, b, spacing_num):
  53. # 进来图片已为正向
  54. eps = 10.
  55. if abs(self.lt[0] - b.lt[0]) > eps: return False
  56. if abs(self.lt[1] - b.lt[1]) > (eps + self.wh[1]) * spacing_num: return False
  57. return True
  58. # 行处理器
  59. class LineParser(object):
  60. def __init__(self, ocr_raw_result, filters=None):
  61. if filters is None:
  62. filters = [lambda x: x.is_slope]
  63. self.ocr_res = []
  64. for re in ocr_raw_result:
  65. o = OcrResult(np.array(re[0]), re[1][0], re[1][1])
  66. if any([f(o) for f in filters]): continue
  67. self.ocr_res.append(o)
  68. # for f in filters:
  69. # self.ocr_res = list(filter(f, self.ocr_res))
  70. self.ocr_res = sorted(self.ocr_res, key=lambda x: x.area, reverse=True)
  71. self.eps = self.avg_height * 0.86
  72. @property
  73. def is_horizontal(self):
  74. res = self.ocr_res
  75. wh = np.stack([np.abs(np.array(r.lt) - np.array(r.rb)) for r in res])
  76. return np.sum(wh[:, 0] > wh[:, 1]) > np.sum(wh[:, 0] < wh[:, 1])
  77. @property
  78. def avg_height(self):
  79. idx = self.is_horizontal + 0
  80. return np.mean(np.array([r.wh[idx] for r in self.ocr_res]))
  81. # 整体置信度
  82. @property
  83. def confidence(self):
  84. return np.mean([r.conf for r in self.ocr_res])
  85. # 处理器函数
  86. @timeit
  87. def parse(self, eps=40.0):
  88. # 存返回值
  89. res = []
  90. # 需要 处理的 OcrResult 对象 的长度
  91. length = len(self.ocr_res)
  92. # 如果字段数 小于等于1 就抛出异常
  93. if length <= 1:
  94. raise Exception('无法识别')
  95. # 遍历数组 并处理他
  96. for i in range(length):
  97. # 拿出 OcrResult对象的 第i值 -暂存-
  98. res_i = self.ocr_res[i]
  99. # 这次的 res_i 之前已经在结果集中,就继续下一个
  100. if any(map(lambda x: res_i in x, res)): continue
  101. # set() -> {}
  102. # 初始化一个集合 即-输出-
  103. res_row = set()
  104. for j in range(i, length):
  105. res_j = self.ocr_res[j]
  106. # 这次的 res_i 之前已经在结果集中,就继续下一个
  107. if any(map(lambda x: res_j in x, res)): continue
  108. if res_i.one_line(res_j, self.is_horizontal, self.eps):
  109. # LineParser 对象 不可以直接加入字典
  110. res_row.add(res_j)
  111. if j >= i and res_i.one_row(res_j, j):
  112. res_row.add(res_j)
  113. res.append(res_row)
  114. idx = self.is_horizontal + 0
  115. res = sorted([sorted(list(r), key=lambda x: x.lt[1 - idx]) for r in res], key=lambda x: x[0].lt[idx])
  116. for row in res:
  117. print('---')
  118. print(''.join([r.txt for r in row]))
  119. return res