ocr_utils.py 14 KB

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