You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import copy
  17. import re
  18. import numpy as np
  19. import cv2
  20. from shapely.geometry import Polygon
  21. import pyclipper
  22. def build_post_process(config, global_config=None):
  23. support_dict = {'DBPostProcess': DBPostProcess, 'CTCLabelDecode': CTCLabelDecode}
  24. config = copy.deepcopy(config)
  25. module_name = config.pop('name')
  26. if module_name == "None":
  27. return
  28. if global_config is not None:
  29. config.update(global_config)
  30. module_class = support_dict.get(module_name)
  31. if module_class is None:
  32. raise ValueError(
  33. 'post process only support {}'.format(list(support_dict)))
  34. return module_class(**config)
  35. class DBPostProcess:
  36. """
  37. The post process for Differentiable Binarization (DB).
  38. """
  39. def __init__(self,
  40. thresh=0.3,
  41. box_thresh=0.7,
  42. max_candidates=1000,
  43. unclip_ratio=2.0,
  44. use_dilation=False,
  45. score_mode="fast",
  46. box_type='quad',
  47. **kwargs):
  48. self.thresh = thresh
  49. self.box_thresh = box_thresh
  50. self.max_candidates = max_candidates
  51. self.unclip_ratio = unclip_ratio
  52. self.min_size = 3
  53. self.score_mode = score_mode
  54. self.box_type = box_type
  55. assert score_mode in [
  56. "slow", "fast"
  57. ], "Score mode must be in [slow, fast] but got: {}".format(score_mode)
  58. self.dilation_kernel = None if not use_dilation else np.array(
  59. [[1, 1], [1, 1]])
  60. def polygons_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
  61. '''
  62. _bitmap: single map with shape (1, H, W),
  63. whose values are binarized as {0, 1}
  64. '''
  65. bitmap = _bitmap
  66. height, width = bitmap.shape
  67. boxes = []
  68. scores = []
  69. contours, _ = cv2.findContours((bitmap * 255).astype(np.uint8),
  70. cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
  71. for contour in contours[:self.max_candidates]:
  72. epsilon = 0.002 * cv2.arcLength(contour, True)
  73. approx = cv2.approxPolyDP(contour, epsilon, True)
  74. points = approx.reshape((-1, 2))
  75. if points.shape[0] < 4:
  76. continue
  77. score = self.box_score_fast(pred, points.reshape(-1, 2))
  78. if self.box_thresh > score:
  79. continue
  80. if points.shape[0] > 2:
  81. box = self.unclip(points, self.unclip_ratio)
  82. if len(box) > 1:
  83. continue
  84. else:
  85. continue
  86. box = box.reshape(-1, 2)
  87. _, sside = self.get_mini_boxes(box.reshape((-1, 1, 2)))
  88. if sside < self.min_size + 2:
  89. continue
  90. box = np.array(box)
  91. box[:, 0] = np.clip(
  92. np.round(box[:, 0] / width * dest_width), 0, dest_width)
  93. box[:, 1] = np.clip(
  94. np.round(box[:, 1] / height * dest_height), 0, dest_height)
  95. boxes.append(box.tolist())
  96. scores.append(score)
  97. return boxes, scores
  98. def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
  99. '''
  100. _bitmap: single map with shape (1, H, W),
  101. whose values are binarized as {0, 1}
  102. '''
  103. bitmap = _bitmap
  104. height, width = bitmap.shape
  105. outs = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST,
  106. cv2.CHAIN_APPROX_SIMPLE)
  107. if len(outs) == 3:
  108. _img, contours, _ = outs[0], outs[1], outs[2]
  109. elif len(outs) == 2:
  110. contours, _ = outs[0], outs[1]
  111. num_contours = min(len(contours), self.max_candidates)
  112. boxes = []
  113. scores = []
  114. for index in range(num_contours):
  115. contour = contours[index]
  116. points, sside = self.get_mini_boxes(contour)
  117. if sside < self.min_size:
  118. continue
  119. points = np.array(points)
  120. if self.score_mode == "fast":
  121. score = self.box_score_fast(pred, points.reshape(-1, 2))
  122. else:
  123. score = self.box_score_slow(pred, contour)
  124. if self.box_thresh > score:
  125. continue
  126. box = self.unclip(points, self.unclip_ratio).reshape(-1, 1, 2)
  127. box, sside = self.get_mini_boxes(box)
  128. if sside < self.min_size + 2:
  129. continue
  130. box = np.array(box)
  131. box[:, 0] = np.clip(
  132. np.round(box[:, 0] / width * dest_width), 0, dest_width)
  133. box[:, 1] = np.clip(
  134. np.round(box[:, 1] / height * dest_height), 0, dest_height)
  135. boxes.append(box.astype("int32"))
  136. scores.append(score)
  137. return np.array(boxes, dtype="int32"), scores
  138. def unclip(self, box, unclip_ratio):
  139. poly = Polygon(box)
  140. distance = poly.area * unclip_ratio / poly.length
  141. offset = pyclipper.PyclipperOffset()
  142. offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
  143. expanded = np.array(offset.Execute(distance))
  144. return expanded
  145. def get_mini_boxes(self, contour):
  146. bounding_box = cv2.minAreaRect(contour)
  147. points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
  148. index_1, index_2, index_3, index_4 = 0, 1, 2, 3
  149. if points[1][1] > points[0][1]:
  150. index_1 = 0
  151. index_4 = 1
  152. else:
  153. index_1 = 1
  154. index_4 = 0
  155. if points[3][1] > points[2][1]:
  156. index_2 = 2
  157. index_3 = 3
  158. else:
  159. index_2 = 3
  160. index_3 = 2
  161. box = [
  162. points[index_1], points[index_2], points[index_3], points[index_4]
  163. ]
  164. return box, min(bounding_box[1])
  165. def box_score_fast(self, bitmap, _box):
  166. '''
  167. box_score_fast: use bbox mean score as the mean score
  168. '''
  169. h, w = bitmap.shape[:2]
  170. box = _box.copy()
  171. xmin = np.clip(np.floor(box[:, 0].min()).astype("int32"), 0, w - 1)
  172. xmax = np.clip(np.ceil(box[:, 0].max()).astype("int32"), 0, w - 1)
  173. ymin = np.clip(np.floor(box[:, 1].min()).astype("int32"), 0, h - 1)
  174. ymax = np.clip(np.ceil(box[:, 1].max()).astype("int32"), 0, h - 1)
  175. mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
  176. box[:, 0] = box[:, 0] - xmin
  177. box[:, 1] = box[:, 1] - ymin
  178. cv2.fillPoly(mask, box.reshape(1, -1, 2).astype("int32"), 1)
  179. return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]
  180. def box_score_slow(self, bitmap, contour):
  181. '''
  182. box_score_slow: use polyon mean score as the mean score
  183. '''
  184. h, w = bitmap.shape[:2]
  185. contour = contour.copy()
  186. contour = np.reshape(contour, (-1, 2))
  187. xmin = np.clip(np.min(contour[:, 0]), 0, w - 1)
  188. xmax = np.clip(np.max(contour[:, 0]), 0, w - 1)
  189. ymin = np.clip(np.min(contour[:, 1]), 0, h - 1)
  190. ymax = np.clip(np.max(contour[:, 1]), 0, h - 1)
  191. mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
  192. contour[:, 0] = contour[:, 0] - xmin
  193. contour[:, 1] = contour[:, 1] - ymin
  194. cv2.fillPoly(mask, contour.reshape(1, -1, 2).astype("int32"), 1)
  195. return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]
  196. def __call__(self, outs_dict, shape_list):
  197. pred = outs_dict['maps']
  198. if not isinstance(pred, np.ndarray):
  199. pred = pred.numpy()
  200. pred = pred[:, 0, :, :]
  201. segmentation = pred > self.thresh
  202. boxes_batch = []
  203. for batch_index in range(pred.shape[0]):
  204. src_h, src_w, ratio_h, ratio_w = shape_list[batch_index]
  205. if self.dilation_kernel is not None:
  206. mask = cv2.dilate(
  207. np.array(segmentation[batch_index]).astype(np.uint8),
  208. self.dilation_kernel)
  209. else:
  210. mask = segmentation[batch_index]
  211. if self.box_type == 'poly':
  212. boxes, scores = self.polygons_from_bitmap(pred[batch_index],
  213. mask, src_w, src_h)
  214. elif self.box_type == 'quad':
  215. boxes, scores = self.boxes_from_bitmap(pred[batch_index], mask,
  216. src_w, src_h)
  217. else:
  218. raise ValueError(
  219. "box_type can only be one of ['quad', 'poly']")
  220. boxes_batch.append({'points': boxes})
  221. return boxes_batch
  222. class BaseRecLabelDecode:
  223. """ Convert between text-label and text-index """
  224. def __init__(self, character_dict_path=None, use_space_char=False):
  225. self.beg_str = "sos"
  226. self.end_str = "eos"
  227. self.reverse = False
  228. self.character_str = []
  229. if character_dict_path is None:
  230. self.character_str = "0123456789abcdefghijklmnopqrstuvwxyz"
  231. dict_character = list(self.character_str)
  232. else:
  233. with open(character_dict_path, "rb") as fin:
  234. lines = fin.readlines()
  235. for line in lines:
  236. line = line.decode('utf-8').strip("\n").strip("\r\n")
  237. self.character_str.append(line)
  238. if use_space_char:
  239. self.character_str.append(" ")
  240. dict_character = list(self.character_str)
  241. if 'arabic' in character_dict_path:
  242. self.reverse = True
  243. dict_character = self.add_special_char(dict_character)
  244. self.dict = {}
  245. for i, char in enumerate(dict_character):
  246. self.dict[char] = i
  247. self.character = dict_character
  248. def pred_reverse(self, pred):
  249. pred_re = []
  250. c_current = ''
  251. for c in pred:
  252. if not bool(re.search('[a-zA-Z0-9 :*./%+-]', c)):
  253. if c_current != '':
  254. pred_re.append(c_current)
  255. pred_re.append(c)
  256. c_current = ''
  257. else:
  258. c_current += c
  259. if c_current != '':
  260. pred_re.append(c_current)
  261. return ''.join(pred_re[::-1])
  262. def add_special_char(self, dict_character):
  263. return dict_character
  264. def decode(self, text_index, text_prob=None, is_remove_duplicate=False):
  265. """ convert text-index into text-label. """
  266. result_list = []
  267. ignored_tokens = self.get_ignored_tokens()
  268. batch_size = len(text_index)
  269. for batch_idx in range(batch_size):
  270. selection = np.ones(len(text_index[batch_idx]), dtype=bool)
  271. if is_remove_duplicate:
  272. selection[1:] = text_index[batch_idx][1:] != text_index[
  273. batch_idx][:-1]
  274. for ignored_token in ignored_tokens:
  275. selection &= text_index[batch_idx] != ignored_token
  276. char_list = [
  277. self.character[text_id]
  278. for text_id in text_index[batch_idx][selection]
  279. ]
  280. if text_prob is not None:
  281. conf_list = text_prob[batch_idx][selection]
  282. else:
  283. conf_list = [1] * len(selection)
  284. if len(conf_list) == 0:
  285. conf_list = [0]
  286. text = ''.join(char_list)
  287. if self.reverse: # for arabic rec
  288. text = self.pred_reverse(text)
  289. result_list.append((text, np.mean(conf_list).tolist()))
  290. return result_list
  291. def get_ignored_tokens(self):
  292. return [0] # for ctc blank
  293. class CTCLabelDecode(BaseRecLabelDecode):
  294. """ Convert between text-label and text-index """
  295. def __init__(self, character_dict_path=None, use_space_char=False,
  296. **kwargs):
  297. super(CTCLabelDecode, self).__init__(character_dict_path,
  298. use_space_char)
  299. def __call__(self, preds, label=None, *args, **kwargs):
  300. if isinstance(preds, tuple) or isinstance(preds, list):
  301. preds = preds[-1]
  302. if not isinstance(preds, np.ndarray):
  303. preds = preds.numpy()
  304. preds_idx = preds.argmax(axis=2)
  305. preds_prob = preds.max(axis=2)
  306. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  307. if label is None:
  308. return text
  309. label = self.decode(label)
  310. return text, label
  311. def add_special_char(self, dict_character):
  312. dict_character = ['blank'] + dict_character
  313. return dict_character