ocr_utils.py 15 KB

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