picodet_postprocess.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. layout_dict_path,
  80. strides=[8, 16, 32, 64],
  81. score_threshold=0.4,
  82. nms_threshold=0.5,
  83. nms_top_k=1000,
  84. keep_top_k=100):
  85. self.labels = self.load_layout_dict(layout_dict_path)
  86. self.strides = strides
  87. self.score_threshold = score_threshold
  88. self.nms_threshold = nms_threshold
  89. self.nms_top_k = nms_top_k
  90. self.keep_top_k = keep_top_k
  91. def load_layout_dict(self, layout_dict_path):
  92. with open(layout_dict_path, 'r', encoding='utf-8') as fp:
  93. labels = fp.readlines()
  94. return [label.strip('\n') for label in labels]
  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 img_info(self, ori_img, img):
  119. origin_shape = ori_img.shape
  120. resize_shape = img.shape
  121. im_scale_y = resize_shape[2] / float(origin_shape[0])
  122. im_scale_x = resize_shape[3] / float(origin_shape[1])
  123. scale_factor = np.array([im_scale_y, im_scale_x], dtype=np.float32)
  124. img_shape = np.array(img.shape[2:], dtype=np.float32)
  125. input_shape = np.array(img).astype('float32').shape[2:]
  126. ori_shape = np.array((img_shape, )).astype('float32')
  127. scale_factor = np.array((scale_factor, )).astype('float32')
  128. return ori_shape, input_shape, scale_factor
  129. def __call__(self, ori_img, img, preds):
  130. scores, raw_boxes = preds['boxes'], preds['boxes_num']
  131. batch_size = raw_boxes[0].shape[0]
  132. reg_max = int(raw_boxes[0].shape[-1] / 4 - 1)
  133. out_boxes_num = []
  134. out_boxes_list = []
  135. results = []
  136. ori_shape, input_shape, scale_factor = self.img_info(ori_img, img)
  137. for batch_id in range(batch_size):
  138. # generate centers
  139. decode_boxes = []
  140. select_scores = []
  141. for stride, box_distribute, score in zip(self.strides, raw_boxes,
  142. scores):
  143. box_distribute = box_distribute[batch_id]
  144. score = score[batch_id]
  145. # centers
  146. fm_h = input_shape[0] / stride
  147. fm_w = input_shape[1] / stride
  148. h_range = np.arange(fm_h)
  149. w_range = np.arange(fm_w)
  150. ww, hh = np.meshgrid(w_range, h_range)
  151. ct_row = (hh.flatten() + 0.5) * stride
  152. ct_col = (ww.flatten() + 0.5) * stride
  153. center = np.stack((ct_col, ct_row, ct_col, ct_row), axis=1)
  154. # box distribution to distance
  155. reg_range = np.arange(reg_max + 1)
  156. box_distance = box_distribute.reshape((-1, reg_max + 1))
  157. box_distance = softmax(box_distance, axis=1)
  158. box_distance = box_distance * np.expand_dims(reg_range, axis=0)
  159. box_distance = np.sum(box_distance, axis=1).reshape((-1, 4))
  160. box_distance = box_distance * stride
  161. # top K candidate
  162. topk_idx = np.argsort(score.max(axis=1))[::-1]
  163. topk_idx = topk_idx[:self.nms_top_k]
  164. center = center[topk_idx]
  165. score = score[topk_idx]
  166. box_distance = box_distance[topk_idx]
  167. # decode box
  168. decode_box = center + [-1, -1, 1, 1] * box_distance
  169. select_scores.append(score)
  170. decode_boxes.append(decode_box)
  171. # nms
  172. bboxes = np.concatenate(decode_boxes, axis=0)
  173. confidences = np.concatenate(select_scores, axis=0)
  174. picked_box_probs = []
  175. picked_labels = []
  176. for class_index in range(0, confidences.shape[1]):
  177. probs = confidences[:, class_index]
  178. mask = probs > self.score_threshold
  179. probs = probs[mask]
  180. if probs.shape[0] == 0:
  181. continue
  182. subset_boxes = bboxes[mask, :]
  183. box_probs = np.concatenate(
  184. [subset_boxes, probs.reshape(-1, 1)], axis=1)
  185. box_probs = hard_nms(
  186. box_probs,
  187. iou_threshold=self.nms_threshold,
  188. top_k=self.keep_top_k, )
  189. picked_box_probs.append(box_probs)
  190. picked_labels.extend([class_index] * box_probs.shape[0])
  191. if len(picked_box_probs) == 0:
  192. out_boxes_list.append(np.empty((0, 4)))
  193. out_boxes_num.append(0)
  194. else:
  195. picked_box_probs = np.concatenate(picked_box_probs)
  196. # resize output boxes
  197. picked_box_probs[:, :4] = self.warp_boxes(
  198. picked_box_probs[:, :4], ori_shape[batch_id])
  199. im_scale = np.concatenate([
  200. scale_factor[batch_id][::-1], scale_factor[batch_id][::-1]
  201. ])
  202. picked_box_probs[:, :4] /= im_scale
  203. # clas score box
  204. out_boxes_list.append(
  205. np.concatenate(
  206. [
  207. np.expand_dims(
  208. np.array(picked_labels),
  209. axis=-1), np.expand_dims(
  210. picked_box_probs[:, 4], axis=-1),
  211. picked_box_probs[:, :4]
  212. ],
  213. axis=1))
  214. out_boxes_num.append(len(picked_labels))
  215. out_boxes_list = np.concatenate(out_boxes_list, axis=0)
  216. out_boxes_num = np.asarray(out_boxes_num).astype(np.int32)
  217. for dt in out_boxes_list:
  218. clsid, bbox, score = int(dt[0]), dt[2:], dt[1]
  219. label = self.labels[clsid]
  220. result = {'bbox': bbox, 'label': label}
  221. results.append(result)
  222. return results