picodet_postprocess.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # Copyright (c) 2021 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. import numpy as np
  15. from scipy.special import softmax
  16. def hard_nms(box_scores, iou_threshold, top_k=-1, candidate_size=200):
  17. """
  18. Args:
  19. box_scores (N, 5): boxes in corner-form and probabilities.
  20. iou_threshold: intersection over union threshold.
  21. top_k: keep top_k results. If k <= 0, keep all the results.
  22. candidate_size: only consider the candidates with the highest scores.
  23. Returns:
  24. picked: a list of indexes of the kept boxes
  25. """
  26. scores = box_scores[:, -1]
  27. boxes = box_scores[:, :-1]
  28. picked = []
  29. indexes = np.argsort(scores)
  30. indexes = indexes[-candidate_size:]
  31. while len(indexes) > 0:
  32. current = indexes[-1]
  33. picked.append(current)
  34. if 0 < top_k == len(picked) or len(indexes) == 1:
  35. break
  36. current_box = boxes[current, :]
  37. indexes = indexes[:-1]
  38. rest_boxes = boxes[indexes, :]
  39. iou = iou_of(
  40. rest_boxes,
  41. np.expand_dims(
  42. current_box, axis=0), )
  43. indexes = indexes[iou <= iou_threshold]
  44. return box_scores[picked, :]
  45. def iou_of(boxes0, boxes1, eps=1e-5):
  46. """Return intersection-over-union (Jaccard index) of boxes.
  47. Args:
  48. boxes0 (N, 4): ground truth boxes.
  49. boxes1 (N or 1, 4): predicted boxes.
  50. eps: a small number to avoid 0 as denominator.
  51. Returns:
  52. iou (N): IoU values.
  53. """
  54. overlap_left_top = np.maximum(boxes0[..., :2], boxes1[..., :2])
  55. overlap_right_bottom = np.minimum(boxes0[..., 2:], boxes1[..., 2:])
  56. overlap_area = area_of(overlap_left_top, overlap_right_bottom)
  57. area0 = area_of(boxes0[..., :2], boxes0[..., 2:])
  58. area1 = area_of(boxes1[..., :2], boxes1[..., 2:])
  59. return overlap_area / (area0 + area1 - overlap_area + eps)
  60. def area_of(left_top, right_bottom):
  61. """Compute the areas of rectangles given two corners.
  62. Args:
  63. left_top (N, 2): left top corner.
  64. right_bottom (N, 2): right bottom corner.
  65. Returns:
  66. area (N): return the area.
  67. """
  68. hw = np.clip(right_bottom - left_top, 0.0, None)
  69. return hw[..., 0] * hw[..., 1]
  70. class PicoDetPostProcess(object):
  71. """
  72. Args:
  73. input_shape (int): network input image size
  74. ori_shape (int): ori image shape of before padding
  75. scale_factor (float): scale factor of ori image
  76. enable_mkldnn (bool): whether to open MKLDNN
  77. """
  78. def __init__(self,
  79. input_shape,
  80. ori_shape,
  81. scale_factor,
  82. strides=[8, 16, 32, 64],
  83. score_threshold=0.4,
  84. nms_threshold=0.5,
  85. nms_top_k=1000,
  86. keep_top_k=100):
  87. self.ori_shape = ori_shape
  88. self.input_shape = input_shape
  89. self.scale_factor = scale_factor
  90. self.strides = strides
  91. self.score_threshold = score_threshold
  92. self.nms_threshold = nms_threshold
  93. self.nms_top_k = nms_top_k
  94. self.keep_top_k = keep_top_k
  95. def warp_boxes(self, boxes, ori_shape):
  96. """Apply transform to boxes
  97. """
  98. width, height = ori_shape[1], ori_shape[0]
  99. n = len(boxes)
  100. if n:
  101. # warp points
  102. xy = np.ones((n * 4, 3))
  103. xy[:, :2] = boxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(
  104. n * 4, 2) # x1y1, x2y2, x1y2, x2y1
  105. # xy = xy @ M.T # transform
  106. xy = (xy[:, :2] / xy[:, 2:3]).reshape(n, 8) # rescale
  107. # create new boxes
  108. x = xy[:, [0, 2, 4, 6]]
  109. y = xy[:, [1, 3, 5, 7]]
  110. xy = np.concatenate(
  111. (x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
  112. # clip boxes
  113. xy[:, [0, 2]] = xy[:, [0, 2]].clip(0, width)
  114. xy[:, [1, 3]] = xy[:, [1, 3]].clip(0, height)
  115. return xy.astype(np.float32)
  116. else:
  117. return boxes
  118. def __call__(self, scores, raw_boxes):
  119. batch_size = raw_boxes[0].shape[0]
  120. reg_max = int(raw_boxes[0].shape[-1] / 4 - 1)
  121. out_boxes_num = []
  122. out_boxes_list = []
  123. for batch_id in range(batch_size):
  124. # generate centers
  125. decode_boxes = []
  126. select_scores = []
  127. for stride, box_distribute, score in zip(self.strides, raw_boxes,
  128. scores):
  129. box_distribute = box_distribute[batch_id]
  130. score = score[batch_id]
  131. # centers
  132. fm_h = self.input_shape[0] / stride
  133. fm_w = self.input_shape[1] / stride
  134. h_range = np.arange(fm_h)
  135. w_range = np.arange(fm_w)
  136. ww, hh = np.meshgrid(w_range, h_range)
  137. ct_row = (hh.flatten() + 0.5) * stride
  138. ct_col = (ww.flatten() + 0.5) * stride
  139. center = np.stack((ct_col, ct_row, ct_col, ct_row), axis=1)
  140. # box distribution to distance
  141. reg_range = np.arange(reg_max + 1)
  142. box_distance = box_distribute.reshape((-1, reg_max + 1))
  143. box_distance = softmax(box_distance, axis=1)
  144. box_distance = box_distance * np.expand_dims(reg_range, axis=0)
  145. box_distance = np.sum(box_distance, axis=1).reshape((-1, 4))
  146. box_distance = box_distance * stride
  147. # top K candidate
  148. topk_idx = np.argsort(score.max(axis=1))[::-1]
  149. topk_idx = topk_idx[:self.nms_top_k]
  150. center = center[topk_idx]
  151. score = score[topk_idx]
  152. box_distance = box_distance[topk_idx]
  153. # decode box
  154. decode_box = center + [-1, -1, 1, 1] * box_distance
  155. select_scores.append(score)
  156. decode_boxes.append(decode_box)
  157. # nms
  158. bboxes = np.concatenate(decode_boxes, axis=0)
  159. confidences = np.concatenate(select_scores, axis=0)
  160. picked_box_probs = []
  161. picked_labels = []
  162. for class_index in range(0, confidences.shape[1]):
  163. probs = confidences[:, class_index]
  164. mask = probs > self.score_threshold
  165. probs = probs[mask]
  166. if probs.shape[0] == 0:
  167. continue
  168. subset_boxes = bboxes[mask, :]
  169. box_probs = np.concatenate(
  170. [subset_boxes, probs.reshape(-1, 1)], axis=1)
  171. box_probs = hard_nms(
  172. box_probs,
  173. iou_threshold=self.nms_threshold,
  174. top_k=self.keep_top_k, )
  175. picked_box_probs.append(box_probs)
  176. picked_labels.extend([class_index] * box_probs.shape[0])
  177. if len(picked_box_probs) == 0:
  178. out_boxes_list.append(np.empty((0, 4)))
  179. out_boxes_num.append(0)
  180. else:
  181. picked_box_probs = np.concatenate(picked_box_probs)
  182. # resize output boxes
  183. picked_box_probs[:, :4] = self.warp_boxes(
  184. picked_box_probs[:, :4], self.ori_shape[batch_id])
  185. im_scale = np.concatenate([
  186. self.scale_factor[batch_id][::-1],
  187. self.scale_factor[batch_id][::-1]
  188. ])
  189. picked_box_probs[:, :4] /= im_scale
  190. # clas score box
  191. out_boxes_list.append(
  192. np.concatenate(
  193. [
  194. np.expand_dims(
  195. np.array(picked_labels),
  196. axis=-1), np.expand_dims(
  197. picked_box_probs[:, 4], axis=-1),
  198. picked_box_probs[:, :4]
  199. ],
  200. axis=1))
  201. out_boxes_num.append(len(picked_labels))
  202. out_boxes_list = np.concatenate(out_boxes_list, axis=0)
  203. out_boxes_num = np.asarray(out_boxes_num).astype(np.int32)
  204. return out_boxes_list, out_boxes_num