browse_dataset.py 8.34 KB
Newer Older
1
import argparse
2
3
import numpy as np
import warnings
4
5
6
from mmcv import Config, DictAction, mkdir_or_exist, track_iter_progress
from os import path as osp

7
8
from mmdet3d.core.bbox import (Box3DMode, CameraInstance3DBoxes, Coord3DMode,
                               DepthInstance3DBoxes, LiDARInstance3DBoxes)
9
10
11
from mmdet3d.core.visualizer import (show_multi_modality_result, show_result,
                                     show_seg_result)
from mmdet3d.datasets import build_dataset
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27


def parse_args():
    parser = argparse.ArgumentParser(description='Browse a dataset')
    parser.add_argument('config', help='train config file path')
    parser.add_argument(
        '--skip-type',
        type=str,
        nargs='+',
        default=['Normalize'],
        help='skip some useless pipeline')
    parser.add_argument(
        '--output-dir',
        default=None,
        type=str,
        help='If there is no display interface, you can save it')
28
    parser.add_argument(
29
30
31
32
        '--task',
        type=str,
        choices=['det', 'seg', 'multi_modality-det', 'mono-det'],
        help='Determine the visualization method depending on the task.')
33
34
35
36
37
    parser.add_argument(
        '--online',
        action='store_true',
        help='Whether to perform online visualization. Note that you often '
        'need a monitor to do so.')
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    parser.add_argument(
        '--cfg-options',
        nargs='+',
        action=DictAction,
        help='override some settings in the used config, the key-value pair '
        'in xxx=yyy format will be merged into config file. If the value to '
        'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
        'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
        'Note that the quotation marks are necessary and that no white space '
        'is allowed.')
    args = parser.parse_args()
    return args


52
53
def build_data_cfg(config_path, skip_type, cfg_options):
    """Build data config for loading visualization data."""
54
55
56
57
58
59
60
    cfg = Config.fromfile(config_path)
    if cfg_options is not None:
        cfg.merge_from_dict(cfg_options)
    # import modules from string list.
    if cfg.get('custom_imports', None):
        from mmcv.utils import import_modules_from_strings
        import_modules_from_strings(**cfg['custom_imports'])
61
62
    # extract inner dataset of `RepeatDataset` as `cfg.data.train`
    # so we don't need to worry about it later
63
    if cfg.data.train['type'] == 'RepeatDataset':
64
65
66
67
        cfg.data.train = cfg.data.train.dataset
    train_data_cfg = cfg.data.train
    # eval_pipeline purely consists of loading functions
    # use eval_pipeline for data loading
68
    train_data_cfg['pipeline'] = [
69
        x for x in cfg.eval_pipeline if x['type'] not in skip_type
70
71
72
73
74
    ]

    return cfg


75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
def to_depth_mode(points, bboxes):
    """Convert points and bboxes to Depth Coord and Depth Box mode."""
    if points is not None:
        points = Coord3DMode.convert_point(points.copy(), Coord3DMode.LIDAR,
                                           Coord3DMode.DEPTH)
    if bboxes is not None:
        bboxes = Box3DMode.convert(bboxes.clone(), Box3DMode.LIDAR,
                                   Box3DMode.DEPTH)
    return points, bboxes


def show_det_data(idx, dataset, out_dir, filename, show=False):
    """Visualize 3D point cloud and 3D bboxes."""
    example = dataset.prepare_train_data(idx)
    points = example['points']._data.numpy()
    gt_bboxes = dataset.get_ann_info(idx)['gt_bboxes_3d'].tensor
    if dataset.box_mode_3d != Box3DMode.DEPTH:
        points, gt_bboxes = to_depth_mode(points, gt_bboxes)
    show_result(
        points,
        gt_bboxes.clone(),
        None,
        out_dir,
        filename,
        show=show,
        snapshot=True)


def show_seg_data(idx, dataset, out_dir, filename, show=False):
    """Visualize 3D point cloud and segmentation mask."""
    example = dataset.prepare_train_data(idx)
    points = example['points']._data.numpy()
    gt_seg = example['pts_semantic_mask']._data.numpy()
    show_seg_result(
        points,
        gt_seg.copy(),
        None,
        out_dir,
        filename,
        np.array(dataset.PALETTE),
        dataset.ignore_index,
        show=show,
        snapshot=True)


120
121
122
123
124
125
def show_proj_bbox_img(idx,
                       dataset,
                       out_dir,
                       filename,
                       show=False,
                       is_nus_mono=False):
126
    """Visualize 3D bboxes on 2D image by projection."""
127
128
129
130
    try:
        example = dataset.prepare_train_data(idx)
    except AttributeError:  # for Mono-3D datasets
        example = dataset.prepare_train_img(idx)
131
132
133
134
135
136
137
138
139
140
141
142
143
    gt_bboxes = dataset.get_ann_info(idx)['gt_bboxes_3d']
    img_metas = example['img_metas']._data
    img = example['img']._data.numpy()
    # need to transpose channel to first dim
    img = img.transpose(1, 2, 0)
    # no 3D gt bboxes, just show img
    if gt_bboxes.tensor.shape[0] == 0:
        gt_bboxes = None
    if isinstance(gt_bboxes, DepthInstance3DBoxes):
        show_multi_modality_result(
            img,
            gt_bboxes,
            None,
144
            None,
145
146
            out_dir,
            filename,
147
            box_mode='depth',
148
149
150
151
152
153
154
155
156
157
            img_metas=img_metas,
            show=show)
    elif isinstance(gt_bboxes, LiDARInstance3DBoxes):
        show_multi_modality_result(
            img,
            gt_bboxes,
            None,
            img_metas['lidar2img'],
            out_dir,
            filename,
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
            box_mode='lidar',
            img_metas=img_metas,
            show=show)
    elif isinstance(gt_bboxes, CameraInstance3DBoxes):
        # TODO: remove the hack of box from NuScenesMonoDataset
        if is_nus_mono:
            from mmdet3d.core.bbox import mono_cam_box2vis
            gt_bboxes = mono_cam_box2vis(gt_bboxes)
        show_multi_modality_result(
            img,
            gt_bboxes,
            None,
            img_metas['cam_intrinsic'],
            out_dir,
            filename,
            box_mode='camera',
174
175
176
177
            img_metas=img_metas,
            show=show)
    else:
        # can't project, just show img
178
179
        warnings.warn(
            f'unrecognized gt box type {type(gt_bboxes)}, only show image')
180
181
182
183
        show_multi_modality_result(
            img, None, None, None, out_dir, filename, show=show)


184
185
186
187
188
189
def main():
    args = parse_args()

    if args.output_dir is not None:
        mkdir_or_exist(args.output_dir)

190
191
192
193
194
195
    cfg = build_data_cfg(args.config, args.skip_type, args.cfg_options)
    try:
        dataset = build_dataset(
            cfg.data.train, default_args=dict(filter_empty_gt=False))
    except TypeError:  # seg dataset doesn't have `filter_empty_gt` key
        dataset = build_dataset(cfg.data.train)
196
    data_infos = dataset.data_infos
197
198
199
    dataset_type = cfg.dataset_type

    # configure visualization mode
200
    vis_task = args.task  # 'det', 'seg', 'multi_modality-det', 'mono-det'
201
202

    for idx, data_info in enumerate(track_iter_progress(data_infos)):
203
        if dataset_type in ['KittiDataset', 'WaymoDataset']:
204
            data_path = data_info['point_cloud']['velodyne_path']
205
206
207
208
        elif dataset_type in [
                'ScanNetDataset', 'SUNRGBDDataset', 'ScanNetSegDataset',
                'S3DISSegDataset'
        ]:
209
            data_path = data_info['pts_path']
210
        elif dataset_type in ['NuScenesDataset', 'LyftDataset']:
211
212
213
            data_path = data_info['lidar_path']
        elif dataset_type in ['NuScenesMonoDataset']:
            data_path = data_info['file_name']
214
215
        else:
            raise NotImplementedError(
216
                f'unsupported dataset type {dataset_type}')
217

218
        file_name = osp.splitext(osp.basename(data_path))[0]
219

220
        if vis_task in ['det', 'multi_modality-det']:
221
222
223
            # show 3D bboxes on 3D point clouds
            show_det_data(
                idx, dataset, args.output_dir, file_name, show=args.online)
224
225
226
227
228
229
230
231
232
233
        if vis_task in ['multi_modality-det', 'mono-det']:
            # project 3D bboxes to 2D image
            show_proj_bbox_img(
                idx,
                dataset,
                args.output_dir,
                file_name,
                show=args.online,
                is_nus_mono=(dataset_type == 'NuScenesMonoDataset'))
        elif vis_task in ['seg']:
234
235
236
            # show 3D segmentation mask on 3D point clouds
            show_seg_data(
                idx, dataset, args.output_dir, file_name, show=args.online)
237
238
239
240


if __name__ == '__main__':
    main()