ocr_utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. import copy
  3. import cv2
  4. import numpy as np
  5. def merge_spans_to_line(spans, threshold=0.6):
  6. if len(spans) == 0:
  7. return []
  8. else:
  9. # 按照y0坐标排序
  10. spans.sort(key=lambda span: span['bbox'][1])
  11. lines = []
  12. current_line = [spans[0]]
  13. for span in spans[1:]:
  14. # 如果当前的span与当前行的最后一个span在y轴上重叠,则添加到当前行
  15. if __is_overlaps_y_exceeds_threshold(span['bbox'], current_line[-1]['bbox'], threshold):
  16. current_line.append(span)
  17. else:
  18. # 否则,开始新行
  19. lines.append(current_line)
  20. current_line = [span]
  21. # 添加最后一行
  22. if current_line:
  23. lines.append(current_line)
  24. return lines
  25. def __is_overlaps_y_exceeds_threshold(bbox1,
  26. bbox2,
  27. overlap_ratio_threshold=0.8):
  28. """检查两个bbox在y轴上是否有重叠,并且该重叠区域的高度占两个bbox高度更低的那个超过80%"""
  29. _, y0_1, _, y1_1 = bbox1
  30. _, y0_2, _, y1_2 = bbox2
  31. overlap = max(0, min(y1_1, y1_2) - max(y0_1, y0_2))
  32. height1, height2 = y1_1 - y0_1, y1_2 - y0_2
  33. # max_height = max(height1, height2)
  34. min_height = min(height1, height2)
  35. return (overlap / min_height) > overlap_ratio_threshold
  36. def img_decode(content: bytes):
  37. np_arr = np.frombuffer(content, dtype=np.uint8)
  38. return cv2.imdecode(np_arr, cv2.IMREAD_UNCHANGED)
  39. def check_img(img):
  40. if isinstance(img, bytes):
  41. img = img_decode(img)
  42. if isinstance(img, np.ndarray) and len(img.shape) == 2:
  43. img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  44. return img
  45. def alpha_to_color(img, alpha_color=(255, 255, 255)):
  46. if len(img.shape) == 3 and img.shape[2] == 4:
  47. B, G, R, A = cv2.split(img)
  48. alpha = A / 255
  49. R = (alpha_color[0] * (1 - alpha) + R * alpha).astype(np.uint8)
  50. G = (alpha_color[1] * (1 - alpha) + G * alpha).astype(np.uint8)
  51. B = (alpha_color[2] * (1 - alpha) + B * alpha).astype(np.uint8)
  52. img = cv2.merge((B, G, R))
  53. return img
  54. def preprocess_image(_image):
  55. alpha_color = (255, 255, 255)
  56. _image = alpha_to_color(_image, alpha_color)
  57. return _image
  58. def sorted_boxes(dt_boxes):
  59. """
  60. Sort text boxes in order from top to bottom, left to right
  61. args:
  62. dt_boxes(array):detected text boxes with shape [4, 2]
  63. return:
  64. sorted boxes(array) with shape [4, 2]
  65. """
  66. num_boxes = dt_boxes.shape[0]
  67. sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
  68. _boxes = list(sorted_boxes)
  69. for i in range(num_boxes - 1):
  70. for j in range(i, -1, -1):
  71. if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \
  72. (_boxes[j + 1][0][0] < _boxes[j][0][0]):
  73. tmp = _boxes[j]
  74. _boxes[j] = _boxes[j + 1]
  75. _boxes[j + 1] = tmp
  76. else:
  77. break
  78. return _boxes
  79. def bbox_to_points(bbox):
  80. """ 将bbox格式转换为四个顶点的数组 """
  81. x0, y0, x1, y1 = bbox
  82. return np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]).astype('float32')
  83. def points_to_bbox(points):
  84. """ 将四个顶点的数组转换为bbox格式 """
  85. x0, y0 = points[0]
  86. x1, _ = points[1]
  87. _, y1 = points[2]
  88. return [x0, y0, x1, y1]
  89. def merge_intervals(intervals):
  90. # Sort the intervals based on the start value
  91. intervals.sort(key=lambda x: x[0])
  92. merged = []
  93. for interval in intervals:
  94. # If the list of merged intervals is empty or if the current
  95. # interval does not overlap with the previous, simply append it.
  96. if not merged or merged[-1][1] < interval[0]:
  97. merged.append(interval)
  98. else:
  99. # Otherwise, there is overlap, so we merge the current and previous intervals.
  100. merged[-1][1] = max(merged[-1][1], interval[1])
  101. return merged
  102. def remove_intervals(original, masks):
  103. # Merge all mask intervals
  104. merged_masks = merge_intervals(masks)
  105. result = []
  106. original_start, original_end = original
  107. for mask in merged_masks:
  108. mask_start, mask_end = mask
  109. # If the mask starts after the original range, ignore it
  110. if mask_start > original_end:
  111. continue
  112. # If the mask ends before the original range starts, ignore it
  113. if mask_end < original_start:
  114. continue
  115. # Remove the masked part from the original range
  116. if original_start < mask_start:
  117. result.append([original_start, mask_start - 1])
  118. original_start = max(mask_end + 1, original_start)
  119. # Add the remaining part of the original range, if any
  120. if original_start <= original_end:
  121. result.append([original_start, original_end])
  122. return result
  123. def update_det_boxes(dt_boxes, mfd_res):
  124. new_dt_boxes = []
  125. angle_boxes_list = []
  126. for text_box in dt_boxes:
  127. if calculate_is_angle(text_box):
  128. angle_boxes_list.append(text_box)
  129. continue
  130. text_bbox = points_to_bbox(text_box)
  131. masks_list = []
  132. for mf_box in mfd_res:
  133. mf_bbox = mf_box['bbox']
  134. if __is_overlaps_y_exceeds_threshold(text_bbox, mf_bbox):
  135. masks_list.append([mf_bbox[0], mf_bbox[2]])
  136. text_x_range = [text_bbox[0], text_bbox[2]]
  137. text_remove_mask_range = remove_intervals(text_x_range, masks_list)
  138. temp_dt_box = []
  139. for text_remove_mask in text_remove_mask_range:
  140. temp_dt_box.append(bbox_to_points([text_remove_mask[0], text_bbox[1], text_remove_mask[1], text_bbox[3]]))
  141. if len(temp_dt_box) > 0:
  142. new_dt_boxes.extend(temp_dt_box)
  143. new_dt_boxes.extend(angle_boxes_list)
  144. return new_dt_boxes
  145. def merge_overlapping_spans(spans):
  146. """
  147. Merges overlapping spans on the same line.
  148. :param spans: A list of span coordinates [(x1, y1, x2, y2), ...]
  149. :return: A list of merged spans
  150. """
  151. # Return an empty list if the input spans list is empty
  152. if not spans:
  153. return []
  154. # Sort spans by their starting x-coordinate
  155. spans.sort(key=lambda x: x[0])
  156. # Initialize the list of merged spans
  157. merged = []
  158. for span in spans:
  159. # Unpack span coordinates
  160. x1, y1, x2, y2 = span
  161. # If the merged list is empty or there's no horizontal overlap, add the span directly
  162. if not merged or merged[-1][2] < x1:
  163. merged.append(span)
  164. else:
  165. # If there is horizontal overlap, merge the current span with the previous one
  166. last_span = merged.pop()
  167. # Update the merged span's top-left corner to the smaller (x1, y1) and bottom-right to the larger (x2, y2)
  168. x1 = min(last_span[0], x1)
  169. y1 = min(last_span[1], y1)
  170. x2 = max(last_span[2], x2)
  171. y2 = max(last_span[3], y2)
  172. # Add the merged span back to the list
  173. merged.append((x1, y1, x2, y2))
  174. # Return the list of merged spans
  175. return merged
  176. def merge_det_boxes(dt_boxes):
  177. """
  178. Merge detection boxes.
  179. This function takes a list of detected bounding boxes, each represented by four corner points.
  180. The goal is to merge these bounding boxes into larger text regions.
  181. Parameters:
  182. dt_boxes (list): A list containing multiple text detection boxes, where each box is defined by four corner points.
  183. Returns:
  184. list: A list containing the merged text regions, where each region is represented by four corner points.
  185. """
  186. # Convert the detection boxes into a dictionary format with bounding boxes and type
  187. dt_boxes_dict_list = []
  188. angle_boxes_list = []
  189. for text_box in dt_boxes:
  190. text_bbox = points_to_bbox(text_box)
  191. if calculate_is_angle(text_box):
  192. angle_boxes_list.append(text_box)
  193. continue
  194. text_box_dict = {'bbox': text_bbox}
  195. dt_boxes_dict_list.append(text_box_dict)
  196. # Merge adjacent text regions into lines
  197. lines = merge_spans_to_line(dt_boxes_dict_list)
  198. # Initialize a new list for storing the merged text regions
  199. new_dt_boxes = []
  200. for line in lines:
  201. line_bbox_list = []
  202. for span in line:
  203. line_bbox_list.append(span['bbox'])
  204. # Merge overlapping text regions within the same line
  205. merged_spans = merge_overlapping_spans(line_bbox_list)
  206. # Convert the merged text regions back to point format and add them to the new detection box list
  207. for span in merged_spans:
  208. new_dt_boxes.append(bbox_to_points(span))
  209. new_dt_boxes.extend(angle_boxes_list)
  210. return new_dt_boxes
  211. def get_adjusted_mfdetrec_res(single_page_mfdetrec_res, useful_list):
  212. paste_x, paste_y, xmin, ymin, xmax, ymax, new_width, new_height = useful_list
  213. # Adjust the coordinates of the formula area
  214. adjusted_mfdetrec_res = []
  215. for mf_res in single_page_mfdetrec_res:
  216. mf_xmin, mf_ymin, mf_xmax, mf_ymax = mf_res["bbox"]
  217. # Adjust the coordinates of the formula area to the coordinates relative to the cropping area
  218. x0 = mf_xmin - xmin + paste_x
  219. y0 = mf_ymin - ymin + paste_y
  220. x1 = mf_xmax - xmin + paste_x
  221. y1 = mf_ymax - ymin + paste_y
  222. # Filter formula blocks outside the graph
  223. if any([x1 < 0, y1 < 0]) or any([x0 > new_width, y0 > new_height]):
  224. continue
  225. else:
  226. adjusted_mfdetrec_res.append({
  227. "bbox": [x0, y0, x1, y1],
  228. })
  229. return adjusted_mfdetrec_res
  230. def get_ocr_result_list(ocr_res, useful_list, ocr_enable, new_image, lang):
  231. paste_x, paste_y, xmin, ymin, xmax, ymax, new_width, new_height = useful_list
  232. ocr_result_list = []
  233. ori_im = new_image.copy()
  234. for box_ocr_res in ocr_res:
  235. if len(box_ocr_res) == 2:
  236. p1, p2, p3, p4 = box_ocr_res[0]
  237. text, score = box_ocr_res[1]
  238. # logger.info(f"text: {text}, score: {score}")
  239. if score < 0.6: # 过滤低置信度的结果
  240. continue
  241. else:
  242. p1, p2, p3, p4 = box_ocr_res
  243. text, score = "", 1
  244. if ocr_enable:
  245. tmp_box = copy.deepcopy(np.array([p1, p2, p3, p4]).astype('float32'))
  246. img_crop = get_rotate_crop_image(ori_im, tmp_box)
  247. # average_angle_degrees = calculate_angle_degrees(box_ocr_res[0])
  248. # if average_angle_degrees > 0.5:
  249. poly = [p1, p2, p3, p4]
  250. if calculate_is_angle(poly):
  251. # logger.info(f"average_angle_degrees: {average_angle_degrees}, text: {text}")
  252. # 与x轴的夹角超过0.5度,对边界做一下矫正
  253. # 计算几何中心
  254. x_center = sum(point[0] for point in poly) / 4
  255. y_center = sum(point[1] for point in poly) / 4
  256. new_height = ((p4[1] - p1[1]) + (p3[1] - p2[1])) / 2
  257. new_width = p3[0] - p1[0]
  258. p1 = [x_center - new_width / 2, y_center - new_height / 2]
  259. p2 = [x_center + new_width / 2, y_center - new_height / 2]
  260. p3 = [x_center + new_width / 2, y_center + new_height / 2]
  261. p4 = [x_center - new_width / 2, y_center + new_height / 2]
  262. # Convert the coordinates back to the original coordinate system
  263. p1 = [p1[0] - paste_x + xmin, p1[1] - paste_y + ymin]
  264. p2 = [p2[0] - paste_x + xmin, p2[1] - paste_y + ymin]
  265. p3 = [p3[0] - paste_x + xmin, p3[1] - paste_y + ymin]
  266. p4 = [p4[0] - paste_x + xmin, p4[1] - paste_y + ymin]
  267. if ocr_enable:
  268. ocr_result_list.append({
  269. 'category_id': 15,
  270. 'poly': p1 + p2 + p3 + p4,
  271. 'score': 1,
  272. 'text': text,
  273. 'np_img': img_crop,
  274. 'lang': lang,
  275. })
  276. else:
  277. ocr_result_list.append({
  278. 'category_id': 15,
  279. 'poly': p1 + p2 + p3 + p4,
  280. 'score': float(round(score, 2)),
  281. 'text': text,
  282. })
  283. return ocr_result_list
  284. def calculate_is_angle(poly):
  285. p1, p2, p3, p4 = poly
  286. height = ((p4[1] - p1[1]) + (p3[1] - p2[1])) / 2
  287. if 0.8 * height <= (p3[1] - p1[1]) <= 1.2 * height:
  288. return False
  289. else:
  290. # logger.info((p3[1] - p1[1])/height)
  291. return True
  292. def get_rotate_crop_image(img, points):
  293. '''
  294. img_height, img_width = img.shape[0:2]
  295. left = int(np.min(points[:, 0]))
  296. right = int(np.max(points[:, 0]))
  297. top = int(np.min(points[:, 1]))
  298. bottom = int(np.max(points[:, 1]))
  299. img_crop = img[top:bottom, left:right, :].copy()
  300. points[:, 0] = points[:, 0] - left
  301. points[:, 1] = points[:, 1] - top
  302. '''
  303. assert len(points) == 4, "shape of points must be 4*2"
  304. img_crop_width = int(
  305. max(
  306. np.linalg.norm(points[0] - points[1]),
  307. np.linalg.norm(points[2] - points[3])))
  308. img_crop_height = int(
  309. max(
  310. np.linalg.norm(points[0] - points[3]),
  311. np.linalg.norm(points[1] - points[2])))
  312. pts_std = np.float32([[0, 0], [img_crop_width, 0],
  313. [img_crop_width, img_crop_height],
  314. [0, img_crop_height]])
  315. M = cv2.getPerspectiveTransform(points, pts_std)
  316. dst_img = cv2.warpPerspective(
  317. img,
  318. M, (img_crop_width, img_crop_height),
  319. borderMode=cv2.BORDER_REPLICATE,
  320. flags=cv2.INTER_CUBIC)
  321. dst_img_height, dst_img_width = dst_img.shape[0:2]
  322. if dst_img_height * 1.0 / dst_img_width >= 1.5:
  323. dst_img = np.rot90(dst_img)
  324. return dst_img