map_utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. from __future__ import unicode_literals
  18. import os
  19. import sys
  20. import numpy as np
  21. import itertools
  22. import paddle
  23. from ppdet.modeling.rbox_utils import poly2rbox_np
  24. from ppdet.utils.logger import setup_logger
  25. logger = setup_logger(__name__)
  26. __all__ = [
  27. 'draw_pr_curve',
  28. 'bbox_area',
  29. 'jaccard_overlap',
  30. 'prune_zero_padding',
  31. 'DetectionMAP',
  32. 'ap_per_class',
  33. 'compute_ap',
  34. ]
  35. def draw_pr_curve(precision,
  36. recall,
  37. iou=0.5,
  38. out_dir='pr_curve',
  39. file_name='precision_recall_curve.jpg'):
  40. if not os.path.exists(out_dir):
  41. os.makedirs(out_dir)
  42. output_path = os.path.join(out_dir, file_name)
  43. try:
  44. import matplotlib.pyplot as plt
  45. except Exception as e:
  46. logger.error('Matplotlib not found, plaese install matplotlib.'
  47. 'for example: `pip install matplotlib`.')
  48. raise e
  49. plt.cla()
  50. plt.figure('P-R Curve')
  51. plt.title('Precision/Recall Curve(IoU={})'.format(iou))
  52. plt.xlabel('Recall')
  53. plt.ylabel('Precision')
  54. plt.grid(True)
  55. plt.plot(recall, precision)
  56. plt.savefig(output_path)
  57. def bbox_area(bbox, is_bbox_normalized):
  58. """
  59. Calculate area of a bounding box
  60. """
  61. norm = 1. - float(is_bbox_normalized)
  62. width = bbox[2] - bbox[0] + norm
  63. height = bbox[3] - bbox[1] + norm
  64. return width * height
  65. def jaccard_overlap(pred, gt, is_bbox_normalized=False):
  66. """
  67. Calculate jaccard overlap ratio between two bounding box
  68. """
  69. if pred[0] >= gt[2] or pred[2] <= gt[0] or \
  70. pred[1] >= gt[3] or pred[3] <= gt[1]:
  71. return 0.
  72. inter_xmin = max(pred[0], gt[0])
  73. inter_ymin = max(pred[1], gt[1])
  74. inter_xmax = min(pred[2], gt[2])
  75. inter_ymax = min(pred[3], gt[3])
  76. inter_size = bbox_area([inter_xmin, inter_ymin, inter_xmax, inter_ymax],
  77. is_bbox_normalized)
  78. pred_size = bbox_area(pred, is_bbox_normalized)
  79. gt_size = bbox_area(gt, is_bbox_normalized)
  80. overlap = float(inter_size) / (pred_size + gt_size - inter_size)
  81. return overlap
  82. def calc_rbox_iou(pred, gt_poly):
  83. """
  84. calc iou between rotated bbox
  85. """
  86. # calc iou of bounding box for speedup
  87. pred = np.array(pred, np.float32).reshape(-1, 2)
  88. gt_poly = np.array(gt_poly, np.float32).reshape(-1, 2)
  89. pred_rect = [
  90. np.min(pred[:, 0]), np.min(pred[:, 1]), np.max(pred[:, 0]),
  91. np.max(pred[:, 1])
  92. ]
  93. gt_rect = [
  94. np.min(gt_poly[:, 0]), np.min(gt_poly[:, 1]), np.max(gt_poly[:, 0]),
  95. np.max(gt_poly[:, 1])
  96. ]
  97. iou = jaccard_overlap(pred_rect, gt_rect, False)
  98. if iou <= 0:
  99. return iou
  100. # calc rbox iou
  101. pred_rbox = poly2rbox_np(pred.reshape(-1, 8)).reshape(-1, 5)
  102. gt_rbox = poly2rbox_np(gt_poly.reshape(-1, 8)).reshape(-1, 5)
  103. try:
  104. from ext_op import rbox_iou
  105. except Exception as e:
  106. print("import custom_ops error, try install ext_op " \
  107. "following ppdet/ext_op/README.md", e)
  108. sys.stdout.flush()
  109. sys.exit(-1)
  110. pd_gt_rbox = paddle.to_tensor(gt_rbox, dtype='float32')
  111. pd_pred_rbox = paddle.to_tensor(pred_rbox, dtype='float32')
  112. iou = rbox_iou(pd_gt_rbox, pd_pred_rbox)
  113. iou = iou.numpy()
  114. return iou[0][0]
  115. def prune_zero_padding(gt_box, gt_label, difficult=None):
  116. valid_cnt = 0
  117. for i in range(len(gt_box)):
  118. if (gt_box[i] == 0).all():
  119. break
  120. valid_cnt += 1
  121. return (gt_box[:valid_cnt], gt_label[:valid_cnt], difficult[:valid_cnt]
  122. if difficult is not None else None)
  123. class DetectionMAP(object):
  124. """
  125. Calculate detection mean average precision.
  126. Currently support two types: 11point and integral
  127. Args:
  128. class_num (int): The class number.
  129. overlap_thresh (float): The threshold of overlap
  130. ratio between prediction bounding box and
  131. ground truth bounding box for deciding
  132. true/false positive. Default 0.5.
  133. map_type (str): Calculation method of mean average
  134. precision, currently support '11point' and
  135. 'integral'. Default '11point'.
  136. is_bbox_normalized (bool): Whether bounding boxes
  137. is normalized to range[0, 1]. Default False.
  138. evaluate_difficult (bool): Whether to evaluate
  139. difficult bounding boxes. Default False.
  140. catid2name (dict): Mapping between category id and category name.
  141. classwise (bool): Whether per-category AP and draw
  142. P-R Curve or not.
  143. """
  144. def __init__(self,
  145. class_num,
  146. overlap_thresh=0.5,
  147. map_type='11point',
  148. is_bbox_normalized=False,
  149. evaluate_difficult=False,
  150. catid2name=None,
  151. classwise=False):
  152. self.class_num = class_num
  153. self.overlap_thresh = overlap_thresh
  154. assert map_type in ['11point', 'integral'], \
  155. "map_type currently only support '11point' "\
  156. "and 'integral'"
  157. self.map_type = map_type
  158. self.is_bbox_normalized = is_bbox_normalized
  159. self.evaluate_difficult = evaluate_difficult
  160. self.classwise = classwise
  161. self.classes = []
  162. for cname in catid2name.values():
  163. self.classes.append(cname)
  164. self.reset()
  165. def update(self, bbox, score, label, gt_box, gt_label, difficult=None):
  166. """
  167. Update metric statics from given prediction and ground
  168. truth infomations.
  169. """
  170. if difficult is None:
  171. difficult = np.zeros_like(gt_label)
  172. # record class gt count
  173. for gtl, diff in zip(gt_label, difficult):
  174. if self.evaluate_difficult or int(diff) == 0:
  175. self.class_gt_counts[int(np.array(gtl))] += 1
  176. # record class score positive
  177. visited = [False] * len(gt_label)
  178. for b, s, l in zip(bbox, score, label):
  179. pred = b.tolist() if isinstance(b, np.ndarray) else b
  180. max_idx = -1
  181. max_overlap = -1.0
  182. for i, gl in enumerate(gt_label):
  183. if int(gl) == int(l):
  184. if len(gt_box[i]) == 8:
  185. overlap = calc_rbox_iou(pred, gt_box[i])
  186. else:
  187. overlap = jaccard_overlap(pred, gt_box[i],
  188. self.is_bbox_normalized)
  189. if overlap > max_overlap:
  190. max_overlap = overlap
  191. max_idx = i
  192. if max_overlap > self.overlap_thresh:
  193. if self.evaluate_difficult or \
  194. int(np.array(difficult[max_idx])) == 0:
  195. if not visited[max_idx]:
  196. self.class_score_poss[int(l)].append([s, 1.0])
  197. visited[max_idx] = True
  198. else:
  199. self.class_score_poss[int(l)].append([s, 0.0])
  200. else:
  201. self.class_score_poss[int(l)].append([s, 0.0])
  202. def reset(self):
  203. """
  204. Reset metric statics
  205. """
  206. self.class_score_poss = [[] for _ in range(self.class_num)]
  207. self.class_gt_counts = [0] * self.class_num
  208. self.mAP = 0.0
  209. def accumulate(self):
  210. """
  211. Accumulate metric results and calculate mAP
  212. """
  213. mAP = 0.
  214. valid_cnt = 0
  215. eval_results = []
  216. for score_pos, count in zip(self.class_score_poss,
  217. self.class_gt_counts):
  218. if count == 0: continue
  219. if len(score_pos) == 0:
  220. valid_cnt += 1
  221. continue
  222. accum_tp_list, accum_fp_list = \
  223. self._get_tp_fp_accum(score_pos)
  224. precision = []
  225. recall = []
  226. for ac_tp, ac_fp in zip(accum_tp_list, accum_fp_list):
  227. precision.append(float(ac_tp) / (ac_tp + ac_fp))
  228. recall.append(float(ac_tp) / count)
  229. one_class_ap = 0.0
  230. if self.map_type == '11point':
  231. max_precisions = [0.] * 11
  232. start_idx = len(precision) - 1
  233. for j in range(10, -1, -1):
  234. for i in range(start_idx, -1, -1):
  235. if recall[i] < float(j) / 10.:
  236. start_idx = i
  237. if j > 0:
  238. max_precisions[j - 1] = max_precisions[j]
  239. break
  240. else:
  241. if max_precisions[j] < precision[i]:
  242. max_precisions[j] = precision[i]
  243. one_class_ap = sum(max_precisions) / 11.
  244. mAP += one_class_ap
  245. valid_cnt += 1
  246. elif self.map_type == 'integral':
  247. import math
  248. prev_recall = 0.
  249. for i in range(len(precision)):
  250. recall_gap = math.fabs(recall[i] - prev_recall)
  251. if recall_gap > 1e-6:
  252. one_class_ap += precision[i] * recall_gap
  253. prev_recall = recall[i]
  254. mAP += one_class_ap
  255. valid_cnt += 1
  256. else:
  257. logger.error("Unspported mAP type {}".format(self.map_type))
  258. sys.exit(1)
  259. eval_results.append({
  260. 'class': self.classes[valid_cnt - 1],
  261. 'ap': one_class_ap,
  262. 'precision': precision,
  263. 'recall': recall,
  264. })
  265. self.eval_results = eval_results
  266. self.mAP = mAP / float(valid_cnt) if valid_cnt > 0 else mAP
  267. def get_map(self):
  268. """
  269. Get mAP result
  270. """
  271. if self.mAP is None:
  272. logger.error("mAP is not calculated.")
  273. if self.classwise:
  274. # Compute per-category AP and PR curve
  275. try:
  276. from terminaltables import AsciiTable
  277. except Exception as e:
  278. logger.error(
  279. 'terminaltables not found, plaese install terminaltables. '
  280. 'for example: `pip install terminaltables`.')
  281. raise e
  282. results_per_category = []
  283. for eval_result in self.eval_results:
  284. results_per_category.append(
  285. (str(eval_result['class']),
  286. '{:0.3f}'.format(float(eval_result['ap']))))
  287. draw_pr_curve(
  288. eval_result['precision'],
  289. eval_result['recall'],
  290. out_dir='voc_pr_curve',
  291. file_name='{}_precision_recall_curve.jpg'.format(
  292. eval_result['class']))
  293. num_columns = min(6, len(results_per_category) * 2)
  294. results_flatten = list(itertools.chain(*results_per_category))
  295. headers = ['category', 'AP'] * (num_columns // 2)
  296. results_2d = itertools.zip_longest(* [
  297. results_flatten[i::num_columns] for i in range(num_columns)
  298. ])
  299. table_data = [headers]
  300. table_data += [result for result in results_2d]
  301. table = AsciiTable(table_data)
  302. logger.info('Per-category of VOC AP: \n{}'.format(table.table))
  303. logger.info(
  304. "per-category PR curve has output to voc_pr_curve folder.")
  305. return self.mAP
  306. def _get_tp_fp_accum(self, score_pos_list):
  307. """
  308. Calculate accumulating true/false positive results from
  309. [score, pos] records
  310. """
  311. sorted_list = sorted(score_pos_list, key=lambda s: s[0], reverse=True)
  312. accum_tp = 0
  313. accum_fp = 0
  314. accum_tp_list = []
  315. accum_fp_list = []
  316. for (score, pos) in sorted_list:
  317. accum_tp += int(pos)
  318. accum_tp_list.append(accum_tp)
  319. accum_fp += 1 - int(pos)
  320. accum_fp_list.append(accum_fp)
  321. return accum_tp_list, accum_fp_list
  322. def ap_per_class(tp, conf, pred_cls, target_cls):
  323. """
  324. Computes the average precision, given the recall and precision curves.
  325. Method originally from https://github.com/rafaelpadilla/Object-Detection-Metrics.
  326. Args:
  327. tp (list): True positives.
  328. conf (list): Objectness value from 0-1.
  329. pred_cls (list): Predicted object classes.
  330. target_cls (list): Target object classes.
  331. """
  332. tp, conf, pred_cls, target_cls = np.array(tp), np.array(conf), np.array(
  333. pred_cls), np.array(target_cls)
  334. # Sort by objectness
  335. i = np.argsort(-conf)
  336. tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
  337. # Find unique classes
  338. unique_classes = np.unique(np.concatenate((pred_cls, target_cls), 0))
  339. # Create Precision-Recall curve and compute AP for each class
  340. ap, p, r = [], [], []
  341. for c in unique_classes:
  342. i = pred_cls == c
  343. n_gt = sum(target_cls == c) # Number of ground truth objects
  344. n_p = sum(i) # Number of predicted objects
  345. if (n_p == 0) and (n_gt == 0):
  346. continue
  347. elif (n_p == 0) or (n_gt == 0):
  348. ap.append(0)
  349. r.append(0)
  350. p.append(0)
  351. else:
  352. # Accumulate FPs and TPs
  353. fpc = np.cumsum(1 - tp[i])
  354. tpc = np.cumsum(tp[i])
  355. # Recall
  356. recall_curve = tpc / (n_gt + 1e-16)
  357. r.append(tpc[-1] / (n_gt + 1e-16))
  358. # Precision
  359. precision_curve = tpc / (tpc + fpc)
  360. p.append(tpc[-1] / (tpc[-1] + fpc[-1]))
  361. # AP from recall-precision curve
  362. ap.append(compute_ap(recall_curve, precision_curve))
  363. return np.array(ap), unique_classes.astype('int32'), np.array(r), np.array(
  364. p)
  365. def compute_ap(recall, precision):
  366. """
  367. Computes the average precision, given the recall and precision curves.
  368. Code originally from https://github.com/rbgirshick/py-faster-rcnn.
  369. Args:
  370. recall (list): The recall curve.
  371. precision (list): The precision curve.
  372. Returns:
  373. The average precision as computed in py-faster-rcnn.
  374. """
  375. # correct AP calculation
  376. # first append sentinel values at the end
  377. mrec = np.concatenate(([0.], recall, [1.]))
  378. mpre = np.concatenate(([0.], precision, [0.]))
  379. # compute the precision envelope
  380. for i in range(mpre.size - 1, 0, -1):
  381. mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
  382. # to calculate area under PR curve, look for points
  383. # where X axis (recall) changes value
  384. i = np.where(mrec[1:] != mrec[:-1])[0]
  385. # and sum (\Delta recall) * prec
  386. ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
  387. return ap