indoor_metric.py 6.63 KB
Newer Older
jshilong's avatar
jshilong committed
1
# Copyright (c) OpenMMLab. All rights reserved.
zhangshilong's avatar
zhangshilong committed
2
from collections import OrderedDict
jshilong's avatar
jshilong committed
3
4
from typing import Dict, List, Optional, Sequence

zhangshilong's avatar
zhangshilong committed
5
import numpy as np
6
from mmdet.evaluation import eval_map
jshilong's avatar
jshilong committed
7
8
9
from mmengine.evaluator import BaseMetric
from mmengine.logging import MMLogger

zhangshilong's avatar
zhangshilong committed
10
from mmdet3d.evaluation import indoor_eval
jshilong's avatar
jshilong committed
11
from mmdet3d.registry import METRICS
zhangshilong's avatar
zhangshilong committed
12
from mmdet3d.structures import get_box_type
jshilong's avatar
jshilong committed
13
14
15
16


@METRICS.register_module()
class IndoorMetric(BaseMetric):
zhangshilong's avatar
zhangshilong committed
17
    """Indoor scene evaluation metric.
jshilong's avatar
jshilong committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

    Args:
        iou_thr (list[float]): List of iou threshold when calculate the
            metric. Defaults to  [0.25, 0.5].
        collect_device (str, optional): Device name used for collecting
            results from different ranks during distributed training.
            Must be 'cpu' or 'gpu'. Defaults to 'cpu'.
        prefix (str): The prefix that will be added in the metric
            names to disambiguate homonymous metrics of different evaluators.
            If prefix is not provided in the argument, self.default_prefix
            will be used instead. Default: None
    """

    def __init__(self,
                 iou_thr: List[float] = [0.25, 0.5],
                 collect_device: str = 'cpu',
                 prefix: Optional[str] = None,
                 **kwargs):
        super(IndoorMetric, self).__init__(
            prefix=prefix, collect_device=collect_device)
        self.iou_thr = iou_thr

40
    def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None:
jshilong's avatar
jshilong committed
41
42
43
44
45
46
47
        """Process one batch of data samples and predictions.

        The processed results should be stored in ``self.results``,
        which will be used to compute the metrics when all batches
        have been processed.

        Args:
48
49
            data_batch (dict): A batch of data from the dataloader.
            data_samples (Sequence[dict]): A batch of outputs from
jshilong's avatar
jshilong committed
50
51
                the model.
        """
52
53
54
        for data_sample in data_samples:
            pred_3d = data_sample['pred_instances_3d']
            eval_ann_info = data_sample['eval_ann_info']
jshilong's avatar
jshilong committed
55
56
57
58
59
60
            cpu_pred_3d = dict()
            for k, v in pred_3d.items():
                if hasattr(v, 'to'):
                    cpu_pred_3d[k] = v.to('cpu')
                else:
                    cpu_pred_3d[k] = v
61
            self.results.append((eval_ann_info, cpu_pred_3d))
jshilong's avatar
jshilong committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

    def compute_metrics(self, results: list) -> Dict[str, float]:
        """Compute the metrics from processed results.

        Args:
            results (list): The processed results of each batch.

        Returns:
            Dict[str, float]: The computed metrics. The keys are the names of
            the metrics, and the values are corresponding results.
        """
        logger: MMLogger = MMLogger.get_current_instance()
        ann_infos = []
        pred_results = []

        for eval_ann, sinlge_pred_results in results:
            ann_infos.append(eval_ann)
            pred_results.append(sinlge_pred_results)

81
        # some checkpoints may not record the key "box_type_3d"
jshilong's avatar
jshilong committed
82
        box_type_3d, box_mode_3d = get_box_type(
83
            self.dataset_meta.get('box_type_3d', 'depth'))
jshilong's avatar
jshilong committed
84
85
86
87
88

        ret_dict = indoor_eval(
            ann_infos,
            pred_results,
            self.iou_thr,
89
            self.dataset_meta['classes'],
jshilong's avatar
jshilong committed
90
91
92
93
            logger=logger,
            box_mode_3d=box_mode_3d)

        return ret_dict
zhangshilong's avatar
zhangshilong committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120


@METRICS.register_module()
class Indoor2DMetric(BaseMetric):
    """indoor 2d predictions evaluation metric.

    Args:
        iou_thr (list[float]): List of iou threshold when calculate the
            metric. Defaults to  [0.5].
        collect_device (str, optional): Device name used for collecting
            results from different ranks during distributed training.
            Must be 'cpu' or 'gpu'. Defaults to 'cpu'.
        prefix (str): The prefix that will be added in the metric
            names to disambiguate homonymous metrics of different evaluators.
            If prefix is not provided in the argument, self.default_prefix
            will be used instead. Default: None
    """

    def __init__(self,
                 iou_thr: List[float] = [0.5],
                 collect_device: str = 'cpu',
                 prefix: Optional[str] = None,
                 **kwargs):
        super(Indoor2DMetric, self).__init__(
            prefix=prefix, collect_device=collect_device)
        self.iou_thr = iou_thr

121
    def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None:
zhangshilong's avatar
zhangshilong committed
122
123
124
125
126
127
128
        """Process one batch of data samples and predictions.

        The processed results should be stored in ``self.results``,
        which will be used to compute the metrics when all batches
        have been processed.

        Args:
129
            data_batch (dict): A batch of data from the dataloader.
zhangshilong's avatar
zhangshilong committed
130
131
132
            predictions (Sequence[dict]): A batch of outputs from
                the model.
        """
133
134
135
        for data_sample in data_samples:
            pred = data_sample['pred_instances']
            eval_ann_info = data_sample['eval_ann_info']
zhangshilong's avatar
zhangshilong committed
136
            ann = dict(
137
138
                labels=eval_ann_info['gt_bboxes_labels'],
                bboxes=eval_ann_info['gt_bboxes'])
zhangshilong's avatar
zhangshilong committed
139
140
141
142
143
144

            pred_bboxes = pred['bboxes'].cpu().numpy()
            pred_scores = pred['scores'].cpu().numpy()
            pred_labels = pred['labels'].cpu().numpy()

            dets = []
145
            for label in range(len(self.dataset_meta['classes'])):
zhangshilong's avatar
zhangshilong committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
                index = np.where(pred_labels == label)[0]
                pred_bbox_scores = np.hstack(
                    [pred_bboxes[index], pred_scores[index].reshape((-1, 1))])
                dets.append(pred_bbox_scores)

            self.results.append((ann, dets))

    def compute_metrics(self, results: list) -> Dict[str, float]:
        """Compute the metrics from processed results.

        Args:
            results (list): The processed results of each batch.

        Returns:
            Dict[str, float]: The computed metrics. The keys are the names of
            the metrics, and the values are corresponding results.
        """
        logger: MMLogger = MMLogger.get_current_instance()
        annotations, preds = zip(*results)
        eval_results = OrderedDict()
        iou_thr_2d = (self.iou_thr) if isinstance(self.iou_thr,
                                                  float) else self.iou_thr
        for iou_thr_2d_single in iou_thr_2d:
            mean_ap, _ = eval_map(
                preds,
                annotations,
                scale_ranges=None,
                iou_thr=iou_thr_2d_single,
174
                dataset=self.dataset_meta['classes'],
zhangshilong's avatar
zhangshilong committed
175
176
177
                logger=logger)
            eval_results['mAP_' + str(iou_thr_2d_single)] = mean_ap
        return eval_results