3
0

map_utils.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. # Copyright (c) 2019 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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from __future__ import unicode_literals
  18. import sys
  19. import numpy as np
  20. import logging
  21. logger = logging.getLogger(__name__)
  22. __all__ = ['bbox_area', 'jaccard_overlap', 'DetectionMAP']
  23. def bbox_area(bbox, is_bbox_normalized):
  24. """
  25. Calculate area of a bounding box
  26. """
  27. norm = 1. - float(is_bbox_normalized)
  28. width = bbox[2] - bbox[0] + norm
  29. height = bbox[3] - bbox[1] + norm
  30. return width * height
  31. def jaccard_overlap(pred, gt, is_bbox_normalized=False):
  32. """
  33. Calculate jaccard overlap ratio between two bounding box
  34. """
  35. if pred[0] >= gt[2] or pred[2] <= gt[0] or \
  36. pred[1] >= gt[3] or pred[3] <= gt[1]:
  37. return 0.
  38. inter_xmin = max(pred[0], gt[0])
  39. inter_ymin = max(pred[1], gt[1])
  40. inter_xmax = min(pred[2], gt[2])
  41. inter_ymax = min(pred[3], gt[3])
  42. inter_size = bbox_area([inter_xmin, inter_ymin, inter_xmax, inter_ymax],
  43. is_bbox_normalized)
  44. pred_size = bbox_area(pred, is_bbox_normalized)
  45. gt_size = bbox_area(gt, is_bbox_normalized)
  46. overlap = float(inter_size) / (pred_size + gt_size - inter_size)
  47. return overlap
  48. class DetectionMAP(object):
  49. """
  50. Calculate detection mean average precision.
  51. Currently support two types: 11point and integral
  52. Args:
  53. class_num (int): the class number.
  54. overlap_thresh (float): The threshold of overlap
  55. ratio between prediction bounding box and
  56. ground truth bounding box for deciding
  57. true/false positive. Default 0.5.
  58. map_type (str): calculation method of mean average
  59. precision, currently support '11point' and
  60. 'integral'. Default '11point'.
  61. is_bbox_normalized (bool): whther bounding boxes
  62. is normalized to range[0, 1]. Default False.
  63. evaluate_difficult (bool): whether to evaluate
  64. difficult bounding boxes. Default False.
  65. """
  66. def __init__(self,
  67. class_num,
  68. overlap_thresh=0.5,
  69. map_type='11point',
  70. is_bbox_normalized=False,
  71. evaluate_difficult=False):
  72. self.class_num = class_num
  73. self.overlap_thresh = overlap_thresh
  74. assert map_type in ['11point', 'integral'], \
  75. "map_type currently only support '11point' "\
  76. "and 'integral'"
  77. self.map_type = map_type
  78. self.is_bbox_normalized = is_bbox_normalized
  79. self.evaluate_difficult = evaluate_difficult
  80. self.reset()
  81. def update(self, bbox, gt_box, gt_label, difficult=None):
  82. """
  83. Update metric statics from given prediction and ground
  84. truth infomations.
  85. """
  86. if difficult is None:
  87. difficult = np.zeros_like(gt_label)
  88. # record class gt count
  89. for gtl, diff in zip(gt_label, difficult):
  90. if self.evaluate_difficult or int(diff) == 0:
  91. self.class_gt_counts[int(np.array(gtl))] += 1
  92. # record class score positive
  93. visited = [False] * len(gt_label)
  94. for b in bbox:
  95. label, score, xmin, ymin, xmax, ymax = b.tolist()
  96. pred = [xmin, ymin, xmax, ymax]
  97. max_idx = -1
  98. max_overlap = -1.0
  99. for i, gl in enumerate(gt_label):
  100. if int(gl) == int(label):
  101. overlap = jaccard_overlap(pred, gt_box[i],
  102. self.is_bbox_normalized)
  103. if overlap > max_overlap:
  104. max_overlap = overlap
  105. max_idx = i
  106. if max_overlap > self.overlap_thresh:
  107. if self.evaluate_difficult or \
  108. int(np.array(difficult[max_idx])) == 0:
  109. if not visited[max_idx]:
  110. self.class_score_poss[int(label)].append([score, 1.0])
  111. visited[max_idx] = True
  112. else:
  113. self.class_score_poss[int(label)].append([score, 0.0])
  114. else:
  115. self.class_score_poss[int(label)].append([score, 0.0])
  116. def reset(self):
  117. """
  118. Reset metric statics
  119. """
  120. self.class_score_poss = [[] for _ in range(self.class_num)]
  121. self.class_gt_counts = [0] * self.class_num
  122. self.mAP = None
  123. def accumulate(self):
  124. """
  125. Accumulate metric results and calculate mAP
  126. """
  127. mAP = 0.
  128. valid_cnt = 0
  129. for score_pos, count in zip(self.class_score_poss,
  130. self.class_gt_counts):
  131. if count == 0: continue
  132. if len(score_pos) == 0:
  133. valid_cnt += 1
  134. continue
  135. accum_tp_list, accum_fp_list = \
  136. self._get_tp_fp_accum(score_pos)
  137. precision = []
  138. recall = []
  139. for ac_tp, ac_fp in zip(accum_tp_list, accum_fp_list):
  140. precision.append(float(ac_tp) / (ac_tp + ac_fp))
  141. recall.append(float(ac_tp) / count)
  142. if self.map_type == '11point':
  143. max_precisions = [0.] * 11
  144. start_idx = len(precision) - 1
  145. for j in range(10, -1, -1):
  146. for i in range(start_idx, -1, -1):
  147. if recall[i] < float(j) / 10.:
  148. start_idx = i
  149. if j > 0:
  150. max_precisions[j - 1] = max_precisions[j]
  151. break
  152. else:
  153. if max_precisions[j] < precision[i]:
  154. max_precisions[j] = precision[i]
  155. mAP += sum(max_precisions) / 11.
  156. valid_cnt += 1
  157. elif self.map_type == 'integral':
  158. import math
  159. ap = 0.
  160. prev_recall = 0.
  161. for i in range(len(precision)):
  162. recall_gap = math.fabs(recall[i] - prev_recall)
  163. if recall_gap > 1e-6:
  164. ap += precision[i] * recall_gap
  165. prev_recall = recall[i]
  166. mAP += ap
  167. valid_cnt += 1
  168. else:
  169. logger.error("Unspported mAP type {}".format(self.map_type))
  170. sys.exit(1)
  171. self.mAP = mAP / float(valid_cnt) if valid_cnt > 0 else mAP
  172. def get_map(self):
  173. """
  174. Get mAP result
  175. """
  176. if self.mAP is None:
  177. logger.error("mAP is not calculated.")
  178. return self.mAP
  179. def _get_tp_fp_accum(self, score_pos_list):
  180. """
  181. Calculate accumulating true/false positive results from
  182. [score, pos] records
  183. """
  184. sorted_list = sorted(score_pos_list, key=lambda s: s[0], reverse=True)
  185. accum_tp = 0
  186. accum_fp = 0
  187. accum_tp_list = []
  188. accum_fp_list = []
  189. for (score, pos) in sorted_list:
  190. accum_tp += int(pos)
  191. accum_tp_list.append(accum_tp)
  192. accum_fp += 1 - int(pos)
  193. accum_fp_list.append(accum_fp)
  194. return accum_tp_list, accum_fp_list