voc_metric.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import copy
  3. import warnings
  4. from collections import OrderedDict
  5. from typing import List, Optional, Sequence, Union
  6. import numpy as np
  7. from mmengine.evaluator import BaseMetric
  8. from mmengine.logging import MMLogger
  9. from mmdet.registry import METRICS
  10. from ..functional import eval_map, eval_recalls
  11. @METRICS.register_module()
  12. class VOCMetric(BaseMetric):
  13. """Pascal VOC evaluation metric.
  14. Args:
  15. iou_thrs (float or List[float]): IoU threshold. Defaults to 0.5.
  16. scale_ranges (List[tuple], optional): Scale ranges for evaluating
  17. mAP. If not specified, all bounding boxes would be included in
  18. evaluation. Defaults to None.
  19. metric (str | list[str]): Metrics to be evaluated. Options are
  20. 'mAP', 'recall'. If is list, the first setting in the list will
  21. be used to evaluate metric.
  22. proposal_nums (Sequence[int]): Proposal number used for evaluating
  23. recalls, such as recall@100, recall@1000.
  24. Default: (100, 300, 1000).
  25. eval_mode (str): 'area' or '11points', 'area' means calculating the
  26. area under precision-recall curve, '11points' means calculating
  27. the average precision of recalls at [0, 0.1, ..., 1].
  28. The PASCAL VOC2007 defaults to use '11points', while PASCAL
  29. VOC2012 defaults to use 'area'.
  30. collect_device (str): Device name used for collecting results from
  31. different ranks during distributed training. Must be 'cpu' or
  32. 'gpu'. Defaults to 'cpu'.
  33. prefix (str, optional): The prefix that will be added in the metric
  34. names to disambiguate homonymous metrics of different evaluators.
  35. If prefix is not provided in the argument, self.default_prefix
  36. will be used instead. Defaults to None.
  37. """
  38. default_prefix: Optional[str] = 'pascal_voc'
  39. def __init__(self,
  40. iou_thrs: Union[float, List[float]] = 0.5,
  41. scale_ranges: Optional[List[tuple]] = None,
  42. metric: Union[str, List[str]] = 'mAP',
  43. proposal_nums: Sequence[int] = (100, 300, 1000),
  44. eval_mode: str = '11points',
  45. collect_device: str = 'cpu',
  46. prefix: Optional[str] = None) -> None:
  47. super().__init__(collect_device=collect_device, prefix=prefix)
  48. self.iou_thrs = [iou_thrs] if isinstance(iou_thrs, float) \
  49. else iou_thrs
  50. self.scale_ranges = scale_ranges
  51. # voc evaluation metrics
  52. if not isinstance(metric, str):
  53. assert len(metric) == 1
  54. metric = metric[0]
  55. allowed_metrics = ['recall', 'mAP']
  56. if metric not in allowed_metrics:
  57. raise KeyError(
  58. f"metric should be one of 'recall', 'mAP', but got {metric}.")
  59. self.metric = metric
  60. self.proposal_nums = proposal_nums
  61. assert eval_mode in ['area', '11points'], \
  62. 'Unrecognized mode, only "area" and "11points" are supported'
  63. self.eval_mode = eval_mode
  64. # TODO: data_batch is no longer needed, consider adjusting the
  65. # parameter position
  66. def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None:
  67. """Process one batch of data samples and predictions. The processed
  68. results should be stored in ``self.results``, which will be used to
  69. compute the metrics when all batches have been processed.
  70. Args:
  71. data_batch (dict): A batch of data from the dataloader.
  72. data_samples (Sequence[dict]): A batch of data samples that
  73. contain annotations and predictions.
  74. """
  75. for data_sample in data_samples:
  76. gt = copy.deepcopy(data_sample)
  77. # TODO: Need to refactor to support LoadAnnotations
  78. gt_instances = gt['gt_instances']
  79. gt_ignore_instances = gt['ignored_instances']
  80. ann = dict(
  81. labels=gt_instances['labels'].cpu().numpy(),
  82. bboxes=gt_instances['bboxes'].cpu().numpy(),
  83. bboxes_ignore=gt_ignore_instances['bboxes'].cpu().numpy(),
  84. labels_ignore=gt_ignore_instances['labels'].cpu().numpy())
  85. pred = data_sample['pred_instances']
  86. pred_bboxes = pred['bboxes'].cpu().numpy()
  87. pred_scores = pred['scores'].cpu().numpy()
  88. pred_labels = pred['labels'].cpu().numpy()
  89. dets = []
  90. for label in range(len(self.dataset_meta['classes'])):
  91. index = np.where(pred_labels == label)[0]
  92. pred_bbox_scores = np.hstack(
  93. [pred_bboxes[index], pred_scores[index].reshape((-1, 1))])
  94. dets.append(pred_bbox_scores)
  95. self.results.append((ann, dets))
  96. def compute_metrics(self, results: list) -> dict:
  97. """Compute the metrics from processed results.
  98. Args:
  99. results (list): The processed results of each batch.
  100. Returns:
  101. dict: The computed metrics. The keys are the names of the metrics,
  102. and the values are corresponding results.
  103. """
  104. logger: MMLogger = MMLogger.get_current_instance()
  105. gts, preds = zip(*results)
  106. eval_results = OrderedDict()
  107. if self.metric == 'mAP':
  108. assert isinstance(self.iou_thrs, list)
  109. dataset_type = self.dataset_meta.get('dataset_type')
  110. if dataset_type in ['VOC2007', 'VOC2012']:
  111. dataset_name = 'voc'
  112. if dataset_type == 'VOC2007' and self.eval_mode != '11points':
  113. warnings.warn('Pascal VOC2007 uses `11points` as default '
  114. 'evaluate mode, but you are using '
  115. f'{self.eval_mode}.')
  116. elif dataset_type == 'VOC2012' and self.eval_mode != 'area':
  117. warnings.warn('Pascal VOC2012 uses `area` as default '
  118. 'evaluate mode, but you are using '
  119. f'{self.eval_mode}.')
  120. else:
  121. dataset_name = self.dataset_meta['classes']
  122. mean_aps = []
  123. for iou_thr in self.iou_thrs:
  124. logger.info(f'\n{"-" * 15}iou_thr: {iou_thr}{"-" * 15}')
  125. # Follow the official implementation,
  126. # http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCdevkit_18-May-2011.tar
  127. # we should use the legacy coordinate system in mmdet 1.x,
  128. # which means w, h should be computed as 'x2 - x1 + 1` and
  129. # `y2 - y1 + 1`
  130. mean_ap, _ = eval_map(
  131. preds,
  132. gts,
  133. scale_ranges=self.scale_ranges,
  134. iou_thr=iou_thr,
  135. dataset=dataset_name,
  136. logger=logger,
  137. eval_mode=self.eval_mode,
  138. use_legacy_coordinate=True)
  139. mean_aps.append(mean_ap)
  140. eval_results[f'AP{int(iou_thr * 100):02d}'] = round(mean_ap, 3)
  141. eval_results['mAP'] = sum(mean_aps) / len(mean_aps)
  142. eval_results.move_to_end('mAP', last=False)
  143. elif self.metric == 'recall':
  144. # TODO: Currently not checked.
  145. gt_bboxes = [ann['bboxes'] for ann in self.annotations]
  146. recalls = eval_recalls(
  147. gt_bboxes,
  148. results,
  149. self.proposal_nums,
  150. self.iou_thrs,
  151. logger=logger,
  152. use_legacy_coordinate=True)
  153. for i, num in enumerate(self.proposal_nums):
  154. for j, iou_thr in enumerate(self.iou_thrs):
  155. eval_results[f'recall@{num}@{iou_thr}'] = recalls[i, j]
  156. if recalls.shape[1] > 1:
  157. ar = recalls.mean(axis=1)
  158. for i, num in enumerate(self.proposal_nums):
  159. eval_results[f'AR@{num}'] = ar[i]
  160. return eval_results