Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

postprocess.py 13KB

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