Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

postprocess.py 13KB

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