db_postprocess.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. This code is referred from:
  16. https://github.com/WenmuZhou/DBNet.pytorch/blob/master/post_processing/seg_detector_representer.py
  17. """
  18. from __future__ import absolute_import
  19. from __future__ import division
  20. from __future__ import print_function
  21. import numpy as np
  22. import cv2
  23. import paddle
  24. from shapely.geometry import Polygon
  25. import pyclipper
  26. class DBPostProcess(object):
  27. """
  28. The post process for Differentiable Binarization (DB).
  29. """
  30. def __init__(
  31. self,
  32. thresh=0.3,
  33. box_thresh=0.7,
  34. max_candidates=1000,
  35. unclip_ratio=2.0,
  36. use_dilation=False,
  37. score_mode="fast",
  38. box_type="quad",
  39. **kwargs,
  40. ):
  41. self.thresh = thresh
  42. self.box_thresh = box_thresh
  43. self.max_candidates = max_candidates
  44. self.unclip_ratio = unclip_ratio
  45. self.min_size = 3
  46. self.score_mode = score_mode
  47. self.box_type = box_type
  48. assert score_mode in [
  49. "slow",
  50. "fast",
  51. ], "Score mode must be in [slow, fast] but got: {}".format(score_mode)
  52. self.dilation_kernel = None if not use_dilation else np.array([[1, 1], [1, 1]])
  53. def polygons_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
  54. """
  55. _bitmap: single map with shape (1, H, W),
  56. whose values are binarized as {0, 1}
  57. """
  58. bitmap = _bitmap
  59. height, width = bitmap.shape
  60. boxes = []
  61. scores = []
  62. contours, _ = cv2.findContours(
  63. (bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE
  64. )
  65. for contour in contours[: self.max_candidates]:
  66. epsilon = 0.002 * cv2.arcLength(contour, True)
  67. approx = cv2.approxPolyDP(contour, epsilon, True)
  68. points = approx.reshape((-1, 2))
  69. if points.shape[0] < 4:
  70. continue
  71. score = self.box_score_fast(pred, points.reshape(-1, 2))
  72. if self.box_thresh > score:
  73. continue
  74. if points.shape[0] > 2:
  75. box = self.unclip(points, self.unclip_ratio)
  76. if len(box) > 1:
  77. continue
  78. else:
  79. continue
  80. box = np.array(box).reshape(-1, 2)
  81. if len(box) == 0:
  82. continue
  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(np.round(box[:, 0] / width * dest_width), 0, dest_width)
  88. box[:, 1] = np.clip(
  89. np.round(box[:, 1] / height * dest_height), 0, dest_height
  90. )
  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(
  102. (bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE
  103. )
  104. if len(outs) == 3:
  105. img, contours, _ = outs[0], outs[1], outs[2]
  106. elif len(outs) == 2:
  107. contours, _ = outs[0], outs[1]
  108. num_contours = min(len(contours), self.max_candidates)
  109. boxes = []
  110. scores = []
  111. for index in range(num_contours):
  112. contour = contours[index]
  113. points, sside = self.get_mini_boxes(contour)
  114. if sside < self.min_size:
  115. continue
  116. points = np.array(points)
  117. if self.score_mode == "fast":
  118. score = self.box_score_fast(pred, points.reshape(-1, 2))
  119. else:
  120. score = self.box_score_slow(pred, contour)
  121. if self.box_thresh > score:
  122. continue
  123. box = self.unclip(points, self.unclip_ratio)
  124. if len(box) > 1:
  125. continue
  126. box = np.array(box).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(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. )
  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 = 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 = [points[index_1], points[index_2], points[index_3], points[index_4]]
  162. return box, min(bounding_box[1])
  163. def box_score_fast(self, bitmap, _box):
  164. """
  165. box_score_fast: use bbox mean score as the mean score
  166. """
  167. h, w = bitmap.shape[:2]
  168. box = _box.copy()
  169. xmin = np.clip(np.floor(box[:, 0].min()).astype("int32"), 0, w - 1)
  170. xmax = np.clip(np.ceil(box[:, 0].max()).astype("int32"), 0, w - 1)
  171. ymin = np.clip(np.floor(box[:, 1].min()).astype("int32"), 0, h - 1)
  172. ymax = np.clip(np.ceil(box[:, 1].max()).astype("int32"), 0, h - 1)
  173. mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
  174. box[:, 0] = box[:, 0] - xmin
  175. box[:, 1] = box[:, 1] - ymin
  176. cv2.fillPoly(mask, box.reshape(1, -1, 2).astype("int32"), 1)
  177. return cv2.mean(bitmap[ymin : ymax + 1, xmin : xmax + 1], mask)[0]
  178. def box_score_slow(self, bitmap, contour):
  179. """
  180. box_score_slow: use polyon mean score as the mean score
  181. """
  182. h, w = bitmap.shape[:2]
  183. contour = contour.copy()
  184. contour = np.reshape(contour, (-1, 2))
  185. xmin = np.clip(np.min(contour[:, 0]), 0, w - 1)
  186. xmax = np.clip(np.max(contour[:, 0]), 0, w - 1)
  187. ymin = np.clip(np.min(contour[:, 1]), 0, h - 1)
  188. ymax = np.clip(np.max(contour[:, 1]), 0, h - 1)
  189. mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
  190. contour[:, 0] = contour[:, 0] - xmin
  191. contour[:, 1] = contour[:, 1] - ymin
  192. cv2.fillPoly(mask, contour.reshape(1, -1, 2).astype("int32"), 1)
  193. return cv2.mean(bitmap[ymin : ymax + 1, xmin : xmax + 1], mask)[0]
  194. def __call__(self, outs_dict, shape_list):
  195. pred = outs_dict["maps"]
  196. if isinstance(pred, paddle.Tensor):
  197. pred = pred.numpy()
  198. pred = pred[:, 0, :, :]
  199. segmentation = pred > self.thresh
  200. boxes_batch = []
  201. for batch_index in range(pred.shape[0]):
  202. src_h, src_w, ratio_h, ratio_w = shape_list[batch_index]
  203. if self.dilation_kernel is not None:
  204. mask = cv2.dilate(
  205. np.array(segmentation[batch_index]).astype(np.uint8),
  206. self.dilation_kernel,
  207. )
  208. else:
  209. mask = segmentation[batch_index]
  210. if self.box_type == "poly":
  211. boxes, scores = self.polygons_from_bitmap(
  212. pred[batch_index], mask, src_w, src_h
  213. )
  214. elif self.box_type == "quad":
  215. boxes, scores = self.boxes_from_bitmap(
  216. pred[batch_index], mask, src_w, src_h
  217. )
  218. else:
  219. raise ValueError("box_type can only be one of ['quad', 'poly']")
  220. boxes_batch.append({"points": boxes})
  221. return boxes_batch
  222. class DistillationDBPostProcess(object):
  223. def __init__(
  224. self,
  225. model_name=["student"],
  226. key=None,
  227. thresh=0.3,
  228. box_thresh=0.6,
  229. max_candidates=1000,
  230. unclip_ratio=1.5,
  231. use_dilation=False,
  232. score_mode="fast",
  233. box_type="quad",
  234. **kwargs,
  235. ):
  236. self.model_name = model_name
  237. self.key = key
  238. self.post_process = DBPostProcess(
  239. thresh=thresh,
  240. box_thresh=box_thresh,
  241. max_candidates=max_candidates,
  242. unclip_ratio=unclip_ratio,
  243. use_dilation=use_dilation,
  244. score_mode=score_mode,
  245. box_type=box_type,
  246. )
  247. def __call__(self, predicts, shape_list):
  248. results = {}
  249. for k in self.model_name:
  250. results[k] = self.post_process(predicts[k], shape_list=shape_list)
  251. return results