ocr_utils.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import numpy as np
  2. from loguru import logger
  3. from magic_pdf.libs.boxbase import __is_overlaps_y_exceeds_threshold
  4. from magic_pdf.pre_proc.ocr_dict_merge import merge_spans_to_line
  5. def bbox_to_points(bbox):
  6. """ 将bbox格式转换为四个顶点的数组 """
  7. x0, y0, x1, y1 = bbox
  8. return np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]).astype('float32')
  9. def points_to_bbox(points):
  10. """ 将四个顶点的数组转换为bbox格式 """
  11. x0, y0 = points[0]
  12. x1, _ = points[1]
  13. _, y1 = points[2]
  14. return [x0, y0, x1, y1]
  15. def merge_intervals(intervals):
  16. # Sort the intervals based on the start value
  17. intervals.sort(key=lambda x: x[0])
  18. merged = []
  19. for interval in intervals:
  20. # If the list of merged intervals is empty or if the current
  21. # interval does not overlap with the previous, simply append it.
  22. if not merged or merged[-1][1] < interval[0]:
  23. merged.append(interval)
  24. else:
  25. # Otherwise, there is overlap, so we merge the current and previous intervals.
  26. merged[-1][1] = max(merged[-1][1], interval[1])
  27. return merged
  28. def remove_intervals(original, masks):
  29. # Merge all mask intervals
  30. merged_masks = merge_intervals(masks)
  31. result = []
  32. original_start, original_end = original
  33. for mask in merged_masks:
  34. mask_start, mask_end = mask
  35. # If the mask starts after the original range, ignore it
  36. if mask_start > original_end:
  37. continue
  38. # If the mask ends before the original range starts, ignore it
  39. if mask_end < original_start:
  40. continue
  41. # Remove the masked part from the original range
  42. if original_start < mask_start:
  43. result.append([original_start, mask_start - 1])
  44. original_start = max(mask_end + 1, original_start)
  45. # Add the remaining part of the original range, if any
  46. if original_start <= original_end:
  47. result.append([original_start, original_end])
  48. return result
  49. def update_det_boxes(dt_boxes, mfd_res):
  50. new_dt_boxes = []
  51. angle_boxes_list = []
  52. for text_box in dt_boxes:
  53. if calculate_is_angle(text_box):
  54. angle_boxes_list.append(text_box)
  55. continue
  56. text_bbox = points_to_bbox(text_box)
  57. masks_list = []
  58. for mf_box in mfd_res:
  59. mf_bbox = mf_box['bbox']
  60. if __is_overlaps_y_exceeds_threshold(text_bbox, mf_bbox):
  61. masks_list.append([mf_bbox[0], mf_bbox[2]])
  62. text_x_range = [text_bbox[0], text_bbox[2]]
  63. text_remove_mask_range = remove_intervals(text_x_range, masks_list)
  64. temp_dt_box = []
  65. for text_remove_mask in text_remove_mask_range:
  66. temp_dt_box.append(bbox_to_points([text_remove_mask[0], text_bbox[1], text_remove_mask[1], text_bbox[3]]))
  67. if len(temp_dt_box) > 0:
  68. new_dt_boxes.extend(temp_dt_box)
  69. new_dt_boxes.extend(angle_boxes_list)
  70. return new_dt_boxes
  71. def merge_overlapping_spans(spans):
  72. """
  73. Merges overlapping spans on the same line.
  74. :param spans: A list of span coordinates [(x1, y1, x2, y2), ...]
  75. :return: A list of merged spans
  76. """
  77. # Return an empty list if the input spans list is empty
  78. if not spans:
  79. return []
  80. # Sort spans by their starting x-coordinate
  81. spans.sort(key=lambda x: x[0])
  82. # Initialize the list of merged spans
  83. merged = []
  84. for span in spans:
  85. # Unpack span coordinates
  86. x1, y1, x2, y2 = span
  87. # If the merged list is empty or there's no horizontal overlap, add the span directly
  88. if not merged or merged[-1][2] < x1:
  89. merged.append(span)
  90. else:
  91. # If there is horizontal overlap, merge the current span with the previous one
  92. last_span = merged.pop()
  93. # Update the merged span's top-left corner to the smaller (x1, y1) and bottom-right to the larger (x2, y2)
  94. x1 = min(last_span[0], x1)
  95. y1 = min(last_span[1], y1)
  96. x2 = max(last_span[2], x2)
  97. y2 = max(last_span[3], y2)
  98. # Add the merged span back to the list
  99. merged.append((x1, y1, x2, y2))
  100. # Return the list of merged spans
  101. return merged
  102. def merge_det_boxes(dt_boxes):
  103. """
  104. Merge detection boxes.
  105. This function takes a list of detected bounding boxes, each represented by four corner points.
  106. The goal is to merge these bounding boxes into larger text regions.
  107. Parameters:
  108. dt_boxes (list): A list containing multiple text detection boxes, where each box is defined by four corner points.
  109. Returns:
  110. list: A list containing the merged text regions, where each region is represented by four corner points.
  111. """
  112. # Convert the detection boxes into a dictionary format with bounding boxes and type
  113. dt_boxes_dict_list = []
  114. angle_boxes_list = []
  115. for text_box in dt_boxes:
  116. text_bbox = points_to_bbox(text_box)
  117. if calculate_is_angle(text_box):
  118. angle_boxes_list.append(text_box)
  119. continue
  120. text_box_dict = {
  121. 'bbox': text_bbox,
  122. 'type': 'text',
  123. }
  124. dt_boxes_dict_list.append(text_box_dict)
  125. # Merge adjacent text regions into lines
  126. lines = merge_spans_to_line(dt_boxes_dict_list)
  127. # Initialize a new list for storing the merged text regions
  128. new_dt_boxes = []
  129. for line in lines:
  130. line_bbox_list = []
  131. for span in line:
  132. line_bbox_list.append(span['bbox'])
  133. # Merge overlapping text regions within the same line
  134. merged_spans = merge_overlapping_spans(line_bbox_list)
  135. # Convert the merged text regions back to point format and add them to the new detection box list
  136. for span in merged_spans:
  137. new_dt_boxes.append(bbox_to_points(span))
  138. new_dt_boxes.extend(angle_boxes_list)
  139. return new_dt_boxes
  140. def get_adjusted_mfdetrec_res(single_page_mfdetrec_res, useful_list):
  141. paste_x, paste_y, xmin, ymin, xmax, ymax, new_width, new_height = useful_list
  142. # Adjust the coordinates of the formula area
  143. adjusted_mfdetrec_res = []
  144. for mf_res in single_page_mfdetrec_res:
  145. mf_xmin, mf_ymin, mf_xmax, mf_ymax = mf_res["bbox"]
  146. # Adjust the coordinates of the formula area to the coordinates relative to the cropping area
  147. x0 = mf_xmin - xmin + paste_x
  148. y0 = mf_ymin - ymin + paste_y
  149. x1 = mf_xmax - xmin + paste_x
  150. y1 = mf_ymax - ymin + paste_y
  151. # Filter formula blocks outside the graph
  152. if any([x1 < 0, y1 < 0]) or any([x0 > new_width, y0 > new_height]):
  153. continue
  154. else:
  155. adjusted_mfdetrec_res.append({
  156. "bbox": [x0, y0, x1, y1],
  157. })
  158. return adjusted_mfdetrec_res
  159. def get_ocr_result_list(ocr_res, useful_list):
  160. paste_x, paste_y, xmin, ymin, xmax, ymax, new_width, new_height = useful_list
  161. ocr_result_list = []
  162. for box_ocr_res in ocr_res:
  163. if len(box_ocr_res) == 2:
  164. p1, p2, p3, p4 = box_ocr_res[0]
  165. text, score = box_ocr_res[1]
  166. # logger.info(f"text: {text}, score: {score}")
  167. if score < 0.6: # 过滤低置信度的结果
  168. continue
  169. else:
  170. p1, p2, p3, p4 = box_ocr_res
  171. text, score = "", 1
  172. # average_angle_degrees = calculate_angle_degrees(box_ocr_res[0])
  173. # if average_angle_degrees > 0.5:
  174. poly = [p1, p2, p3, p4]
  175. if calculate_is_angle(poly):
  176. # logger.info(f"average_angle_degrees: {average_angle_degrees}, text: {text}")
  177. # 与x轴的夹角超过0.5度,对边界做一下矫正
  178. # 计算几何中心
  179. x_center = sum(point[0] for point in poly) / 4
  180. y_center = sum(point[1] for point in poly) / 4
  181. new_height = ((p4[1] - p1[1]) + (p3[1] - p2[1])) / 2
  182. new_width = p3[0] - p1[0]
  183. p1 = [x_center - new_width / 2, y_center - new_height / 2]
  184. p2 = [x_center + new_width / 2, y_center - new_height / 2]
  185. p3 = [x_center + new_width / 2, y_center + new_height / 2]
  186. p4 = [x_center - new_width / 2, y_center + new_height / 2]
  187. # Convert the coordinates back to the original coordinate system
  188. p1 = [p1[0] - paste_x + xmin, p1[1] - paste_y + ymin]
  189. p2 = [p2[0] - paste_x + xmin, p2[1] - paste_y + ymin]
  190. p3 = [p3[0] - paste_x + xmin, p3[1] - paste_y + ymin]
  191. p4 = [p4[0] - paste_x + xmin, p4[1] - paste_y + ymin]
  192. ocr_result_list.append({
  193. 'category_id': 15,
  194. 'poly': p1 + p2 + p3 + p4,
  195. 'score': float(round(score, 2)),
  196. 'text': text,
  197. })
  198. return ocr_result_list
  199. def calculate_is_angle(poly):
  200. p1, p2, p3, p4 = poly
  201. height = ((p4[1] - p1[1]) + (p3[1] - p2[1])) / 2
  202. if 0.8 * height <= (p3[1] - p1[1]) <= 1.2 * height:
  203. return False
  204. else:
  205. # logger.info((p3[1] - p1[1])/height)
  206. return True