custom_3d.py 8.26 KB
Newer Older
liyinhao's avatar
liyinhao committed
1
2
3
import os.path as osp
import tempfile

4
5
import mmcv
import numpy as np
zhangwenwei's avatar
zhangwenwei committed
6
from torch.utils.data import Dataset
7
8

from mmdet.datasets import DATASETS
9
10
from ..core.bbox import (Box3DMode, CameraInstance3DBoxes,
                         DepthInstance3DBoxes, LiDARInstance3DBoxes)
11
12
13
14
from .pipelines import Compose


@DATASETS.register_module()
zhangwenwei's avatar
zhangwenwei committed
15
class Custom3DDataset(Dataset):
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    """Customized 3D dataset

    This is the base dataset of SUNRGB-D, ScanNet, nuScenes, and KITTI
    dataset.

    Args:
        data_root (str): Path of dataset root.
        ann_file (str): Path of annotation file.
        pipeline (list[dict], optional): Pipeline used for data processing.
            Defaults to None.
        classes (tuple[str], optional): Classes used in the dataset.
            Defaults to None.
        modality ([dict], optional): Modality to specify the sensor data used
            as input. Defaults to None.
        box_type_3d (str, optional): Type of 3D box of this dataset.
            Based on the `box_type_3d`, the dataset will encapsulate the box
            to its original format then converted them to `box_type_3d`.
            Defaults to 'LiDAR'. Available options includes
            - 'LiDAR': box in LiDAR coordinates
            - 'Depth': box in depth coordinates, usually for indoor dataset
            - 'Camera': box in camera coordinates
        filter_empty_gt (bool, optional): Whether to filter empty GT.
            Defaults to True.
        test_mode (bool, optional): Whether the dataset is in test mode.
            Defaults to False.
    """
42
43

    def __init__(self,
zhangwenwei's avatar
zhangwenwei committed
44
                 data_root,
45
46
                 ann_file,
                 pipeline=None,
liyinhao's avatar
liyinhao committed
47
                 classes=None,
zhangwenwei's avatar
zhangwenwei committed
48
                 modality=None,
49
                 box_type_3d='LiDAR',
wuyuefeng's avatar
Votenet  
wuyuefeng committed
50
                 filter_empty_gt=True,
zhangwenwei's avatar
zhangwenwei committed
51
                 test_mode=False):
52
        super().__init__()
zhangwenwei's avatar
zhangwenwei committed
53
54
        self.data_root = data_root
        self.ann_file = ann_file
55
        self.test_mode = test_mode
zhangwenwei's avatar
zhangwenwei committed
56
        self.modality = modality
wuyuefeng's avatar
Votenet  
wuyuefeng committed
57
        self.filter_empty_gt = filter_empty_gt
58
        self.get_box_type(box_type_3d)
zhangwenwei's avatar
zhangwenwei committed
59
60
61

        self.CLASSES = self.get_classes(classes)
        self.data_infos = self.load_annotations(self.ann_file)
62
63
64
65

        if pipeline is not None:
            self.pipeline = Compose(pipeline)

zhangwenwei's avatar
zhangwenwei committed
66
67
68
69
70
71
        # set group flag for the sampler
        if not self.test_mode:
            self._set_group_flag()

    def load_annotations(self, ann_file):
        return mmcv.load(ann_file)
72

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    def get_box_type(self, box_type):
        box_type_lower = box_type.lower()
        if box_type_lower == 'lidar':
            self.box_type_3d = LiDARInstance3DBoxes
            self.box_mode_3d = Box3DMode.LIDAR
        elif box_type_lower == 'camera':
            self.box_type_3d = CameraInstance3DBoxes
            self.box_mode_3d = Box3DMode.CAM
        elif box_type_lower == 'depth':
            self.box_type_3d = DepthInstance3DBoxes
            self.box_mode_3d = Box3DMode.DEPTH
        else:
            raise ValueError('Only "box_type" of "camera", "lidar", "depth"'
                             f' are supported, got {box_type}')

88
89
90
    def get_data_info(self, index):
        info = self.data_infos[index]
        sample_idx = info['point_cloud']['lidar_idx']
liyinhao's avatar
liyinhao committed
91
        pts_filename = osp.join(self.data_root, info['pts_path'])
92

liyinhao's avatar
liyinhao committed
93
94
95
96
        input_dict = dict(
            pts_filename=pts_filename,
            sample_idx=sample_idx,
            file_name=pts_filename)
97

zhangwenwei's avatar
zhangwenwei committed
98
        if not self.test_mode:
liyinhao's avatar
liyinhao committed
99
            annos = self.get_ann_info(index)
zhangwenwei's avatar
zhangwenwei committed
100
            input_dict['ann_info'] = annos
wuyuefeng's avatar
Votenet  
wuyuefeng committed
101
            if self.filter_empty_gt and len(annos['gt_bboxes_3d']) == 0:
zhangwenwei's avatar
zhangwenwei committed
102
                return None
103
104
        return input_dict

zhangwenwei's avatar
zhangwenwei committed
105
    def pre_pipeline(self, results):
zhangwenwei's avatar
zhangwenwei committed
106
        results['img_fields'] = []
zhangwenwei's avatar
zhangwenwei committed
107
108
109
        results['bbox3d_fields'] = []
        results['pts_mask_fields'] = []
        results['pts_seg_fields'] = []
zhangwenwei's avatar
zhangwenwei committed
110
111
112
        results['bbox_fields'] = []
        results['mask_fields'] = []
        results['seg_fields'] = []
113
114
        results['box_type_3d'] = self.box_type_3d
        results['box_mode_3d'] = self.box_mode_3d
115

liyinhao's avatar
liyinhao committed
116
117
    def prepare_train_data(self, index):
        input_dict = self.get_data_info(index)
118
119
        if input_dict is None:
            return None
zhangwenwei's avatar
zhangwenwei committed
120
        self.pre_pipeline(input_dict)
121
        example = self.pipeline(input_dict)
wuyuefeng's avatar
Votenet  
wuyuefeng committed
122
123
        if self.filter_empty_gt and (example is None or len(
                example['gt_bboxes_3d']._data) == 0):
124
125
126
            return None
        return example

127
128
    def prepare_test_data(self, index):
        input_dict = self.get_data_info(index)
zhangwenwei's avatar
zhangwenwei committed
129
        self.pre_pipeline(input_dict)
130
131
        example = self.pipeline(input_dict)
        return example
132

liyinhao's avatar
liyinhao committed
133
134
    @classmethod
    def get_classes(cls, classes=None):
135
136
        """Get class names of current dataset.

liyinhao's avatar
liyinhao committed
137
138
139
140
141
142
        Args:
            classes (Sequence[str] | str | None): If classes is None, use
                default CLASSES defined by builtin dataset. If classes is a
                string, take it as a file name. The file contains the name of
                classes where each line contains one class name. If classes is
                a tuple or list, override the CLASSES defined by the dataset.
zhangwenwei's avatar
zhangwenwei committed
143
144
145

        Return:
            list[str]: return the list of class names
liyinhao's avatar
liyinhao committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
        """
        if classes is None:
            return cls.CLASSES

        if isinstance(classes, str):
            # take it as a file path
            class_names = mmcv.list_from_file(classes)
        elif isinstance(classes, (tuple, list)):
            class_names = classes
        else:
            raise ValueError(f'Unsupported type {type(classes)} of classes.')

        return class_names

liyinhao's avatar
liyinhao committed
160
161
162
163
164
165
166
167
168
169
    def format_results(self,
                       outputs,
                       pklfile_prefix=None,
                       submission_prefix=None):
        if pklfile_prefix is None:
            tmp_dir = tempfile.TemporaryDirectory()
            pklfile_prefix = osp.join(tmp_dir.name, 'results')
            out = f'{pklfile_prefix}.pkl'
        mmcv.dump(outputs, out)
        return outputs, tmp_dir
170

liyinhao's avatar
liyinhao committed
171
172
173
174
175
176
177
    def evaluate(self,
                 results,
                 metric=None,
                 iou_thr=(0.25, 0.5),
                 logger=None,
                 show=False,
                 out_dir=None):
178
179
180
181
182
        """Evaluate.

        Evaluation in indoor protocol.

        Args:
liyinhao's avatar
liyinhao committed
183
            results (list[dict]): List of results.
wuyuefeng's avatar
wuyuefeng committed
184
185
            metric (str | list[str]): Metrics to be evaluated.
            iou_thr (list[float]): AP IoU thresholds.
liyinhao's avatar
liyinhao committed
186
187
188
189
            show (bool): Whether to visualize.
                Default: False.
            out_dir (str): Path to save the visualization results.
                Default: None.
wuyuefeng's avatar
Votenet  
wuyuefeng committed
190

liyinhao's avatar
liyinhao committed
191
192
        Returns:
            dict: Evaluation results.
193
194
        """
        from mmdet3d.core.evaluation import indoor_eval
liyinhao's avatar
liyinhao committed
195
196
        assert isinstance(
            results, list), f'Expect results to be list, got {type(results)}.'
wuyuefeng's avatar
Votenet  
wuyuefeng committed
197
198
        assert len(results) > 0, f'Expect length of results > 0.'
        assert len(results) == len(self.data_infos)
liyinhao's avatar
liyinhao committed
199
200
201
        assert isinstance(
            results[0], dict
        ), f'Expect elements in results to be dict, got {type(results[0])}.'
202
        gt_annos = [info['annos'] for info in self.data_infos]
zhangwenwei's avatar
zhangwenwei committed
203
        label2cat = {i: cat_id for i, cat_id in enumerate(self.CLASSES)}
zhangwenwei's avatar
zhangwenwei committed
204
        ret_dict = indoor_eval(
wuyuefeng's avatar
wuyuefeng committed
205
206
207
208
209
210
211
            gt_annos,
            results,
            iou_thr,
            label2cat,
            logger=logger,
            box_type_3d=self.box_type_3d,
            box_mode_3d=self.box_mode_3d)
liyinhao's avatar
liyinhao committed
212
213
        if show:
            self.show(results, out_dir)
wuyuefeng's avatar
wuyuefeng committed
214

liyinhao's avatar
liyinhao committed
215
        return ret_dict
zhangwenwei's avatar
zhangwenwei committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242

    def __len__(self):
        return len(self.data_infos)

    def _rand_another(self, idx):
        pool = np.where(self.flag == self.flag[idx])[0]
        return np.random.choice(pool)

    def __getitem__(self, idx):
        if self.test_mode:
            return self.prepare_test_data(idx)
        while True:
            data = self.prepare_train_data(idx)
            if data is None:
                idx = self._rand_another(idx)
                continue
            return data

    def _set_group_flag(self):
        """Set flag according to image aspect ratio.

        Images with aspect ratio greater than 1 will be set as group 1,
        otherwise group 0.
        In 3D datasets, they are all the same, thus are all zeros

        """
        self.flag = np.zeros(len(self), dtype=np.uint8)