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.

postprocess.py 13KB

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