custom_3d.py 10.3 KB
Newer Older
1
2
import mmcv
import numpy as np
zhangwenwei's avatar
zhangwenwei committed
3
4
import tempfile
from os import path as osp
zhangwenwei's avatar
zhangwenwei committed
5
from torch.utils.data import Dataset
6
7

from mmdet.datasets import DATASETS
wuyuefeng's avatar
Demo  
wuyuefeng committed
8
from ..core.bbox import get_box_type
9
10
11
12
from .pipelines import Compose


@DATASETS.register_module()
zhangwenwei's avatar
zhangwenwei committed
13
class Custom3DDataset(Dataset):
zhangwenwei's avatar
zhangwenwei committed
14
    """Customized 3D dataset.
15
16
17
18
19
20
21
22
23
24
25

    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.
wangtai's avatar
wangtai committed
26
        modality (dict, optional): Modality to specify the sensor data used
27
28
29
30
31
            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
wangtai's avatar
wangtai committed
32

wangtai's avatar
wangtai committed
33
34
35
            - 'LiDAR': Box in LiDAR coordinates.
            - 'Depth': Box in depth coordinates, usually for indoor dataset.
            - 'Camera': Box in camera coordinates.
36
37
38
39
40
        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.
    """
41
42

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

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

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

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

    def load_annotations(self, ann_file):
70
71
72
73
74
75
76
77
        """Load annotations from ann_file.

        Args:
            ann_file (str): Path of the annotation file.

        Returns:
            list[dict]: List of annotations.
        """
zhangwenwei's avatar
zhangwenwei committed
78
        return mmcv.load(ann_file)
79
80

    def get_data_info(self, index):
81
82
83
84
85
86
        """Get data info according to the given index.

        Args:
            index (int): Index of the sample data to get.

        Returns:
zhangwenwei's avatar
zhangwenwei committed
87
88
            dict: Data information that will be passed to the data \
                preprocessing pipelines. It includes the following keys:
89

wangtai's avatar
wangtai committed
90
91
92
93
                - sample_idx (str): Sample index.
                - pts_filename (str): Filename of point clouds.
                - file_name (str): Filename of point clouds.
                - ann_info (dict): Annotation info.
94
        """
95
96
        info = self.data_infos[index]
        sample_idx = info['point_cloud']['lidar_idx']
liyinhao's avatar
liyinhao committed
97
        pts_filename = osp.join(self.data_root, info['pts_path'])
98

liyinhao's avatar
liyinhao committed
99
100
101
102
        input_dict = dict(
            pts_filename=pts_filename,
            sample_idx=sample_idx,
            file_name=pts_filename)
103

zhangwenwei's avatar
zhangwenwei committed
104
        if not self.test_mode:
liyinhao's avatar
liyinhao committed
105
            annos = self.get_ann_info(index)
zhangwenwei's avatar
zhangwenwei committed
106
            input_dict['ann_info'] = annos
wuyuefeng's avatar
Votenet  
wuyuefeng committed
107
            if self.filter_empty_gt and len(annos['gt_bboxes_3d']) == 0:
zhangwenwei's avatar
zhangwenwei committed
108
                return None
109
110
        return input_dict

zhangwenwei's avatar
zhangwenwei committed
111
    def pre_pipeline(self, results):
112
113
114
        """Initialization before data preparation.

        Args:
115
            results (dict): Dict before data preprocessing.
116

wangtai's avatar
wangtai committed
117
118
119
120
121
122
123
124
125
                - img_fields (list): Image fields.
                - bbox3d_fields (list): 3D bounding boxes fields.
                - pts_mask_fields (list): Mask fields of points.
                - pts_seg_fields (list): Mask fields of point segments.
                - bbox_fields (list): Fields of bounding boxes.
                - mask_fields (list): Fields of masks.
                - seg_fields (list): Segment fields.
                - box_type_3d (str): 3D box type.
                - box_mode_3d (str): 3D box mode.
126
        """
zhangwenwei's avatar
zhangwenwei committed
127
        results['img_fields'] = []
zhangwenwei's avatar
zhangwenwei committed
128
129
130
        results['bbox3d_fields'] = []
        results['pts_mask_fields'] = []
        results['pts_seg_fields'] = []
zhangwenwei's avatar
zhangwenwei committed
131
132
133
        results['bbox_fields'] = []
        results['mask_fields'] = []
        results['seg_fields'] = []
134
135
        results['box_type_3d'] = self.box_type_3d
        results['box_mode_3d'] = self.box_mode_3d
136

liyinhao's avatar
liyinhao committed
137
    def prepare_train_data(self, index):
138
139
140
141
142
143
        """Training data preparation.

        Args:
            index (int): Index for accessing the target data.

        Returns:
zhangwenwei's avatar
zhangwenwei committed
144
            dict: Training data dict of the corresponding index.
145
        """
liyinhao's avatar
liyinhao committed
146
        input_dict = self.get_data_info(index)
147
148
        if input_dict is None:
            return None
zhangwenwei's avatar
zhangwenwei committed
149
        self.pre_pipeline(input_dict)
150
        example = self.pipeline(input_dict)
wuyuefeng's avatar
Votenet  
wuyuefeng committed
151
152
        if self.filter_empty_gt and (example is None or len(
                example['gt_bboxes_3d']._data) == 0):
153
154
155
            return None
        return example

156
    def prepare_test_data(self, index):
157
158
159
160
161
162
        """Prepare data for testing.

        Args:
            index (int): Index for accessing the target data.

        Returns:
zhangwenwei's avatar
zhangwenwei committed
163
            dict: Testing data dict of the corresponding index.
164
        """
165
        input_dict = self.get_data_info(index)
zhangwenwei's avatar
zhangwenwei committed
166
        self.pre_pipeline(input_dict)
167
168
        example = self.pipeline(input_dict)
        return example
169

liyinhao's avatar
liyinhao committed
170
171
    @classmethod
    def get_classes(cls, classes=None):
172
173
        """Get class names of current dataset.

liyinhao's avatar
liyinhao committed
174
175
176
177
178
179
        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
180
181

        Return:
wangtai's avatar
wangtai committed
182
            list[str]: A list of class names.
liyinhao's avatar
liyinhao committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
        """
        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
197
198
199
200
    def format_results(self,
                       outputs,
                       pklfile_prefix=None,
                       submission_prefix=None):
201
202
203
204
205
206
207
208
209
        """Format the results to pkl file.

        Args:
            outputs (list[dict]): Testing results of the dataset.
            pklfile_prefix (str | None): The prefix of pkl files. It includes
                the file path and the prefix of filename, e.g., "a/b/prefix".
                If not specified, a temp file will be created. Default: None.

        Returns:
zhangwenwei's avatar
zhangwenwei committed
210
211
212
            tuple: (outputs, tmp_dir), outputs is the detection results, \
                tmp_dir is the temporal directory created for saving json \
                files when ``jsonfile_prefix`` is not specified.
213
        """
liyinhao's avatar
liyinhao committed
214
215
216
217
218
219
        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
220

liyinhao's avatar
liyinhao committed
221
222
223
224
225
226
227
    def evaluate(self,
                 results,
                 metric=None,
                 iou_thr=(0.25, 0.5),
                 logger=None,
                 show=False,
                 out_dir=None):
228
229
230
231
232
        """Evaluate.

        Evaluation in indoor protocol.

        Args:
liyinhao's avatar
liyinhao committed
233
            results (list[dict]): List of results.
wuyuefeng's avatar
wuyuefeng committed
234
235
            metric (str | list[str]): Metrics to be evaluated.
            iou_thr (list[float]): AP IoU thresholds.
liyinhao's avatar
liyinhao committed
236
237
238
239
            show (bool): Whether to visualize.
                Default: False.
            out_dir (str): Path to save the visualization results.
                Default: None.
wuyuefeng's avatar
Votenet  
wuyuefeng committed
240

liyinhao's avatar
liyinhao committed
241
242
        Returns:
            dict: Evaluation results.
243
244
        """
        from mmdet3d.core.evaluation import indoor_eval
liyinhao's avatar
liyinhao committed
245
246
        assert isinstance(
            results, list), f'Expect results to be list, got {type(results)}.'
zhangwenwei's avatar
zhangwenwei committed
247
        assert len(results) > 0, 'Expect length of results > 0.'
wuyuefeng's avatar
Votenet  
wuyuefeng committed
248
        assert len(results) == len(self.data_infos)
liyinhao's avatar
liyinhao committed
249
250
251
        assert isinstance(
            results[0], dict
        ), f'Expect elements in results to be dict, got {type(results[0])}.'
252
        gt_annos = [info['annos'] for info in self.data_infos]
zhangwenwei's avatar
zhangwenwei committed
253
        label2cat = {i: cat_id for i, cat_id in enumerate(self.CLASSES)}
zhangwenwei's avatar
zhangwenwei committed
254
        ret_dict = indoor_eval(
wuyuefeng's avatar
wuyuefeng committed
255
256
257
258
259
260
261
            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
262
263
        if show:
            self.show(results, out_dir)
wuyuefeng's avatar
wuyuefeng committed
264

liyinhao's avatar
liyinhao committed
265
        return ret_dict
zhangwenwei's avatar
zhangwenwei committed
266
267

    def __len__(self):
268
269
270
271
272
        """Return the length of data infos.

        Returns:
            int: Length of data infos.
        """
zhangwenwei's avatar
zhangwenwei committed
273
274
275
        return len(self.data_infos)

    def _rand_another(self, idx):
276
277
278
279
280
        """Randomly get another item with the same flag.

        Returns:
            int: Another index of item with the same flag.
        """
zhangwenwei's avatar
zhangwenwei committed
281
282
283
284
        pool = np.where(self.flag == self.flag[idx])[0]
        return np.random.choice(pool)

    def __getitem__(self, idx):
285
286
287
288
289
        """Get item from infos according to the given index.

        Returns:
            dict: Data dictionary of the corresponding index.
        """
zhangwenwei's avatar
zhangwenwei committed
290
291
292
293
294
295
296
297
298
299
300
301
302
        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,
303
304
        otherwise group 0. In 3D datasets, they are all the same, thus
        are all zeros.
zhangwenwei's avatar
zhangwenwei committed
305
306
        """
        self.flag = np.zeros(len(self), dtype=np.uint8)