det3d_dataset.py 16.7 KB
Newer Older
jshilong's avatar
jshilong committed
1
2
3
# Copyright (c) OpenMMLab. All rights reserved.
import copy
from os import path as osp
4
from typing import Callable, List, Optional, Set, Union
jshilong's avatar
jshilong committed
5

6
import mmengine
jshilong's avatar
jshilong committed
7
import numpy as np
8
import torch
jshilong's avatar
jshilong committed
9
from mmengine.dataset import BaseDataset
10
11
from mmengine.logging import print_log
from terminaltables import AsciiTable
jshilong's avatar
jshilong committed
12
13

from mmdet3d.datasets import DATASETS
zhangshilong's avatar
zhangshilong committed
14
from mmdet3d.structures import get_box_type
jshilong's avatar
jshilong committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30


@DATASETS.register_module()
class Det3DDataset(BaseDataset):
    """Base Class of 3D dataset.

    This is the base dataset of SUNRGB-D, ScanNet, nuScenes, and KITTI
    dataset.
    # TODO: doc link here for the standard data format

    Args:
        data_root (str, optional): The root directory for ``data_prefix`` and
            ``ann_file``. Defaults to None.
        ann_file (str): Annotation file path. Defaults to ''.
        metainfo (dict, optional): Meta information for dataset, such as class
            information. Defaults to None.
31
        data_prefix (dict): Prefix for training data. Defaults to
32
            dict(pts='velodyne', img='').
33
        pipeline (List[dict]): Pipeline used for data processing.
34
35
36
            Defaults to [].
        modality (dict): Modality to specify the sensor data used as input,
            it usually has following keys:
jshilong's avatar
jshilong committed
37
38
39

                - use_camera: bool
                - use_lidar: bool
40
            Defaults to dict(use_lidar=True, use_camera=False).
jshilong's avatar
jshilong committed
41
42
        default_cam_key (str, optional): The default camera name adopted.
            Defaults to None.
43
        box_type_3d (str): Type of 3D box of this dataset.
jshilong's avatar
jshilong committed
44
45
            Based on the `box_type_3d`, the dataset will encapsulate the box
            to its original format then converted them to `box_type_3d`.
46
            Defaults to 'LiDAR' in this dataset. Available options includes:
jshilong's avatar
jshilong committed
47
48
49
50
51
52
53

            - 'LiDAR': Box in LiDAR coordinates, usually for
              outdoor point cloud 3d detection.
            - 'Depth': Box in depth coordinates, usually for
              indoor point cloud 3d detection.
            - 'Camera': Box in camera coordinates, usually
              for vision-based 3d detection.
54
55
56
57
58
        filter_empty_gt (bool): Whether to filter the data with empty GT.
            If it's set to be True, the example with empty annotations after
            data pipeline will be dropped and a random example will be chosen
            in `__getitem__`. Defaults to True.
        test_mode (bool): Whether the dataset is in test mode.
jshilong's avatar
jshilong committed
59
            Defaults to False.
60
61
62
63
        load_eval_anns (bool): Whether to load annotations in test_mode,
            the annotation will be save in `eval_ann_infos`, which can be
            used in Evaluator. Defaults to True.
        file_client_args (dict): Configuration of file client.
64
            Defaults to dict(backend='disk').
65
66
67
        show_ins_var (bool): For debug purpose. Whether to show variation
            of the number of instances before and after through pipeline.
            Defaults to False.
jshilong's avatar
jshilong committed
68
69
70
71
72
73
74
75
76
    """

    def __init__(self,
                 data_root: Optional[str] = None,
                 ann_file: str = '',
                 metainfo: Optional[dict] = None,
                 data_prefix: dict = dict(pts='velodyne', img=''),
                 pipeline: List[Union[dict, Callable]] = [],
                 modality: dict = dict(use_lidar=True, use_camera=False),
jshilong's avatar
jshilong committed
77
                 default_cam_key: str = None,
jshilong's avatar
jshilong committed
78
79
80
                 box_type_3d: dict = 'LiDAR',
                 filter_empty_gt: bool = True,
                 test_mode: bool = False,
81
                 load_eval_anns: bool = True,
jshilong's avatar
jshilong committed
82
                 file_client_args: dict = dict(backend='disk'),
83
                 show_ins_var: bool = False,
84
                 **kwargs) -> None:
jshilong's avatar
jshilong committed
85
        # init file client
86
        self.file_client = mmengine.FileClient(**file_client_args)
jshilong's avatar
jshilong committed
87
        self.filter_empty_gt = filter_empty_gt
jshilong's avatar
jshilong committed
88
        self.load_eval_anns = load_eval_anns
jshilong's avatar
jshilong committed
89
90
91
92
93
94
95
96
97
        _default_modality_keys = ('use_lidar', 'use_camera')
        if modality is None:
            modality = dict()

        # Defaults to False if not specify
        for key in _default_modality_keys:
            if key not in modality:
                modality[key] = False
        self.modality = modality
jshilong's avatar
jshilong committed
98
        self.default_cam_key = default_cam_key
jshilong's avatar
jshilong committed
99
100
        assert self.modality['use_lidar'] or self.modality['use_camera'], (
            'Please specify the `modality` (`use_lidar` '
jshilong's avatar
jshilong committed
101
            f', `use_camera`) for {self.__class__.__name__}')
jshilong's avatar
jshilong committed
102
103

        self.box_type_3d, self.box_mode_3d = get_box_type(box_type_3d)
VVsssssk's avatar
VVsssssk committed
104

105
106
        if metainfo is not None and 'classes' in metainfo:
            # we allow to train on subset of self.METAINFO['classes']
jshilong's avatar
jshilong committed
107
108
109
            # map unselected labels to -1
            self.label_mapping = {
                i: -1
110
                for i in range(len(self.METAINFO['classes']))
jshilong's avatar
jshilong committed
111
112
            }
            self.label_mapping[-1] = -1
113
114
            for label_idx, name in enumerate(metainfo['classes']):
                ori_label = self.METAINFO['classes'].index(name)
jshilong's avatar
jshilong committed
115
                self.label_mapping[ori_label] = label_idx
116

117
            self.num_ins_per_cat = {name: 0 for name in metainfo['classes']}
jshilong's avatar
jshilong committed
118
119
120
        else:
            self.label_mapping = {
                i: i
121
                for i in range(len(self.METAINFO['classes']))
jshilong's avatar
jshilong committed
122
123
124
            }
            self.label_mapping[-1] = -1

125
126
            self.num_ins_per_cat = {
                name: 0
127
                for name in self.METAINFO['classes']
128
129
            }

jshilong's avatar
jshilong committed
130
131
132
133
134
135
136
137
138
        super().__init__(
            ann_file=ann_file,
            metainfo=metainfo,
            data_root=data_root,
            data_prefix=data_prefix,
            pipeline=pipeline,
            test_mode=test_mode,
            **kwargs)

VVsssssk's avatar
VVsssssk committed
139
140
141
142
        # can be accessed by other component in runner
        self.metainfo['box_type_3d'] = box_type_3d
        self.metainfo['label_mapping'] = self.label_mapping

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
        # used for showing variation of the number of instances before and
        # after through the pipeline
        self.show_ins_var = show_ins_var

        # show statistics of this dataset
        print_log('-' * 30, 'current')
        print_log(f'The length of the dataset: {len(self)}', 'current')
        content_show = [['category', 'number']]
        for cat_name, num in self.num_ins_per_cat.items():
            content_show.append([cat_name, num])
        table = AsciiTable(content_show)
        print_log(
            f'The number of instances per category in the dataset:\n{table.table}',  # noqa: E501
            'current')

158
    def _remove_dontcare(self, ann_info: dict) -> dict:
jshilong's avatar
jshilong committed
159
160
        """Remove annotations that do not need to be cared.

161
        -1 indicates dontcare in MMDet3d.
jshilong's avatar
jshilong committed
162
163
164
165
166
167
168
169
170
171
172

        Args:
            ann_info (dict): Dict of annotation infos. The
                instance with label `-1` will be removed.

        Returns:
            dict: Annotations after filtering.
        """
        img_filtered_annotations = {}
        filter_mask = ann_info['gt_labels_3d'] > -1
        for key in ann_info.keys():
zhangshilong's avatar
zhangshilong committed
173
174
175
176
            if key != 'instances':
                img_filtered_annotations[key] = (ann_info[key][filter_mask])
            else:
                img_filtered_annotations[key] = ann_info[key]
jshilong's avatar
jshilong committed
177
178
179
180
181
182
183
184
185
186
187
188
        return img_filtered_annotations

    def get_ann_info(self, index: int) -> dict:
        """Get annotation info according to the given index.

        Use index to get the corresponding annotations, thus the
        evalhook could use this api.

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

        Returns:
189
            dict: Annotation information.
jshilong's avatar
jshilong committed
190
191
192
193
194
195
196
197
198
199
        """
        data_info = self.get_data_info(index)
        # test model
        if 'ann_info' not in data_info:
            ann_info = self.parse_ann_info(data_info)
        else:
            ann_info = data_info['ann_info']

        return ann_info

200
    def parse_ann_info(self, info: dict) -> Union[dict, None]:
201
        """Process the `instances` in data info to `ann_info`.
jshilong's avatar
jshilong committed
202
203
204
205
206
207
208
209
210
211

        In `Custom3DDataset`, we simply concatenate all the field
        in `instances` to `np.ndarray`, you can do the specific
        process in subclass. You have to convert `gt_bboxes_3d`
        to different coordinates according to the task.

        Args:
            info (dict): Info dict.

        Returns:
212
            dict or None: Processed `ann_info`.
jshilong's avatar
jshilong committed
213
214
        """
        # add s or gt prefix for most keys after concat
zhangshilong's avatar
zhangshilong committed
215
216
        # we only process 3d annotations here, the corresponding
        # 2d annotation process is in the `LoadAnnotations3D`
zhangshilong's avatar
zhangshilong committed
217
        # in `transforms`
jshilong's avatar
jshilong committed
218
219
        name_mapping = {
            'bbox_label_3d': 'gt_labels_3d',
220
221
            'bbox_label': 'gt_bboxes_labels',
            'bbox': 'gt_bboxes',
jshilong's avatar
jshilong committed
222
223
224
            'bbox_3d': 'gt_bboxes_3d',
            'depth': 'depths',
            'center_2d': 'centers_2d',
ChaimZhu's avatar
ChaimZhu committed
225
226
            'attr_label': 'attr_labels',
            'velocity': 'velocities',
jshilong's avatar
jshilong committed
227
228
        }
        instances = info['instances']
229
230
231
232
233
234
235
        # empty gt
        if len(instances) == 0:
            return None
        else:
            keys = list(instances[0].keys())
            ann_info = dict()
            for ann_name in keys:
zhangshilong's avatar
zhangshilong committed
236
237
                temp_anns = [item[ann_name] for item in instances]
                # map the original dataset label to training label
238
                if 'label' in ann_name and ann_name != 'attr_label':
zhangshilong's avatar
zhangshilong committed
239
240
241
                    temp_anns = [
                        self.label_mapping[item] for item in temp_anns
                    ]
242
                if ann_name in name_mapping:
ChaimZhu's avatar
ChaimZhu committed
243
244
245
                    mapped_ann_name = name_mapping[ann_name]
                else:
                    mapped_ann_name = ann_name
246
247
248

                if 'label' in ann_name:
                    temp_anns = np.array(temp_anns).astype(np.int64)
ChaimZhu's avatar
ChaimZhu committed
249
                elif ann_name in name_mapping:
250
                    temp_anns = np.array(temp_anns).astype(np.float32)
ChaimZhu's avatar
ChaimZhu committed
251
252
                else:
                    temp_anns = np.array(temp_anns)
253

ChaimZhu's avatar
ChaimZhu committed
254
                ann_info[mapped_ann_name] = temp_anns
zhangshilong's avatar
zhangshilong committed
255
            ann_info['instances'] = info['instances']
256
257

            for label in ann_info['gt_labels_3d']:
258
259
260
                if label != -1:
                    cat_name = self.metainfo['classes'][label]
                    self.num_ins_per_cat[cat_name] += 1
261

jshilong's avatar
jshilong committed
262
263
264
265
266
267
        return ann_info

    def parse_data_info(self, info: dict) -> dict:
        """Process the raw data info.

        Convert all relative path of needed modality data file to
268
269
        the absolute path. And process the `instances` field to
        `ann_info` in training stage.
jshilong's avatar
jshilong committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284

        Args:
            info (dict): Raw info dict.

        Returns:
            dict: Has `ann_info` in training stage. And
            all path has been converted to absolute path.
        """

        if self.modality['use_lidar']:
            info['lidar_points']['lidar_path'] = \
                osp.join(
                    self.data_prefix.get('pts', ''),
                    info['lidar_points']['lidar_path'])

ChaimZhu's avatar
ChaimZhu committed
285
            info['num_pts_feats'] = info['lidar_points']['num_pts_feats']
jshilong's avatar
jshilong committed
286
            info['lidar_path'] = info['lidar_points']['lidar_path']
VVsssssk's avatar
VVsssssk committed
287
288
289
290
291
292
293
294
295
296
            if 'lidar_sweeps' in info:
                for sweep in info['lidar_sweeps']:
                    file_suffix = sweep['lidar_points']['lidar_path'].split(
                        '/')[-1]
                    if 'samples' in sweep['lidar_points']['lidar_path']:
                        sweep['lidar_points']['lidar_path'] = osp.join(
                            self.data_prefix['pts'], file_suffix)
                    else:
                        sweep['lidar_points']['lidar_path'] = osp.join(
                            self.data_prefix['sweeps'], file_suffix)
jshilong's avatar
jshilong committed
297

jshilong's avatar
jshilong committed
298
299
300
        if self.modality['use_camera']:
            for cam_id, img_info in info['images'].items():
                if 'img_path' in img_info:
VVsssssk's avatar
VVsssssk committed
301
302
303
304
305
306
                    if cam_id in self.data_prefix:
                        cam_prefix = self.data_prefix[cam_id]
                    else:
                        cam_prefix = self.data_prefix.get('img', '')
                    img_info['img_path'] = osp.join(cam_prefix,
                                                    img_info['img_path'])
jshilong's avatar
jshilong committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
            if self.default_cam_key is not None:
                info['img_path'] = info['images'][
                    self.default_cam_key]['img_path']
                if 'lidar2cam' in info['images'][self.default_cam_key]:
                    info['lidar2cam'] = np.array(
                        info['images'][self.default_cam_key]['lidar2cam'])
                if 'cam2img' in info['images'][self.default_cam_key]:
                    info['cam2img'] = np.array(
                        info['images'][self.default_cam_key]['cam2img'])
                if 'lidar2img' in info['images'][self.default_cam_key]:
                    info['lidar2img'] = np.array(
                        info['images'][self.default_cam_key]['lidar2img'])
                else:
                    info['lidar2img'] = info['cam2img'] @ info['lidar2cam']
jshilong's avatar
jshilong committed
321
322

        if not self.test_mode:
Tai-Wang's avatar
Tai-Wang committed
323
            # used in training
jshilong's avatar
jshilong committed
324
            info['ann_info'] = self.parse_ann_info(info)
jshilong's avatar
jshilong committed
325
326
        if self.test_mode and self.load_eval_anns:
            info['eval_ann_info'] = self.parse_ann_info(info)
jshilong's avatar
jshilong committed
327
328
329

        return info

330
331
    def _show_ins_var(self, old_labels: np.ndarray,
                      new_labels: torch.Tensor) -> None:
332
333
334
335
336
337
338
339
340
        """Show variation of the number of instances before and after through
        the pipeline.

        Args:
            old_labels (np.ndarray): The labels before through the pipeline.
            new_labels (torch.Tensor): The labels after through the pipeline.
        """
        ori_num_per_cat = dict()
        for label in old_labels:
341
342
343
344
            if label != -1:
                cat_name = self.metainfo['classes'][label]
                ori_num_per_cat[cat_name] = ori_num_per_cat.get(cat_name,
                                                                0) + 1
345
346
        new_num_per_cat = dict()
        for label in new_labels:
347
348
349
350
            if label != -1:
                cat_name = self.metainfo['classes'][label]
                new_num_per_cat[cat_name] = new_num_per_cat.get(cat_name,
                                                                0) + 1
351
352
353
354
355
356
357
358
359
        content_show = [['category', 'new number', 'ori number']]
        for cat_name, num in ori_num_per_cat.items():
            new_num = new_num_per_cat.get(cat_name, 0)
            content_show.append([cat_name, new_num, num])
        table = AsciiTable(content_show)
        print_log(
            'The number of instances per category after and before '
            f'through pipeline:\n{table.table}', 'current')

360
    def prepare_data(self, index: int) -> Union[dict, None]:
jshilong's avatar
jshilong committed
361
362
363
364
365
366
367
368
        """Data preparation for both training and testing stage.

        Called by `__getitem__`  of dataset.

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

        Returns:
369
            dict or None: Data dict of the corresponding index.
jshilong's avatar
jshilong committed
370
        """
371
        ori_input_dict = self.get_data_info(index)
jshilong's avatar
jshilong committed
372
373

        # deepcopy here to avoid inplace modification in pipeline.
374
        input_dict = copy.deepcopy(ori_input_dict)
jshilong's avatar
jshilong committed
375
376
377
378
379
380
381
382
383
384
385
386

        # box_type_3d (str): 3D box type.
        input_dict['box_type_3d'] = self.box_type_3d
        # box_mode_3d (str): 3D box mode.
        input_dict['box_mode_3d'] = self.box_mode_3d

        # pre-pipline return None to random another in `__getitem__`
        if not self.test_mode and self.filter_empty_gt:
            if len(input_dict['ann_info']['gt_labels_3d']) == 0:
                return None

        example = self.pipeline(input_dict)
387

jshilong's avatar
jshilong committed
388
389
390
        if not self.test_mode and self.filter_empty_gt:
            # after pipeline drop the example with empty annotations
            # return None to random another in `__getitem__`
391
            if example is None or len(
392
                    example['data_samples'].gt_instances_3d.labels_3d) == 0:
jshilong's avatar
jshilong committed
393
                return None
394
395

        if self.show_ins_var:
396
397
398
399
400
401
402
403
404
405
            if 'ann_info' in ori_input_dict:
                self._show_ins_var(
                    ori_input_dict['ann_info']['gt_labels_3d'],
                    example['data_samples'].gt_instances_3d.labels_3d)
            else:
                print_log(
                    "'ann_info' is not in the input dict. It's probably that "
                    'the data is not in training mode',
                    'current',
                    level=30)
406

jshilong's avatar
jshilong committed
407
        return example
408

409
    def get_cat_ids(self, idx: int) -> Set[int]:
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
        """Get category ids by index. Dataset wrapped by ClassBalancedDataset
        must implement this method.

        The ``CBGSDataset`` or ``ClassBalancedDataset``requires a subclass
        which implements this method.

        Args:
            idx (int): The index of data.

        Returns:
            set[int]: All categories in the sample of specified index.
        """
        info = self.get_data_info(idx)
        gt_labels = info['ann_info']['gt_labels_3d'].tolist()
        return set(gt_labels)