inference.py 14.5 KB
Newer Older
dingchang's avatar
dingchang committed
1
# Copyright (c) OpenMMLab. All rights reserved.
ChaimZhu's avatar
ChaimZhu committed
2
import warnings
3
4
from copy import deepcopy
from os import path as osp
ChaimZhu's avatar
ChaimZhu committed
5
6
from pathlib import Path
from typing import Optional, Sequence, Union
7

8
import mmengine
9
import numpy as np
wuyuefeng's avatar
Demo  
wuyuefeng committed
10
import torch
ChaimZhu's avatar
ChaimZhu committed
11
import torch.nn as nn
12
from mmengine.config import Config
13
from mmengine.dataset import Compose, pseudo_collate
14
from mmengine.registry import init_default_scope
ChaimZhu's avatar
ChaimZhu committed
15
from mmengine.runner import load_checkpoint
wuyuefeng's avatar
Demo  
wuyuefeng committed
16

17
from mmdet3d.registry import DATASETS, MODELS
zhangshilong's avatar
zhangshilong committed
18
19
from mmdet3d.structures import Box3DMode, Det3DDataSample, get_box_type
from mmdet3d.structures.det3d_data_sample import SampleList
wuyuefeng's avatar
Demo  
wuyuefeng committed
20
21


22
23
24
25
def convert_SyncBN(config):
    """Convert config's naiveSyncBN to BN.

    Args:
26
         config (str or :obj:`mmengine.Config`): Config file path or the config
27
28
29
30
31
32
33
34
35
36
37
            object.
    """
    if isinstance(config, dict):
        for item in config:
            if item == 'norm_cfg':
                config[item]['type'] = config[item]['type']. \
                                    replace('naiveSyncBN', 'BN')
            else:
                convert_SyncBN(config[item])


ChaimZhu's avatar
ChaimZhu committed
38
39
40
def init_model(config: Union[str, Path, Config],
               checkpoint: Optional[str] = None,
               device: str = 'cuda:0',
41
               palette: str = 'none',
ChaimZhu's avatar
ChaimZhu committed
42
               cfg_options: Optional[dict] = None):
43
44
    """Initialize a model from config file, which could be a 3D detector or a
    3D segmentor.
wuyuefeng's avatar
Demo  
wuyuefeng committed
45
46

    Args:
ChaimZhu's avatar
ChaimZhu committed
47
48
        config (str, :obj:`Path`, or :obj:`mmengine.Config`): Config file path,
            :obj:`Path`, or the config object.
wuyuefeng's avatar
Demo  
wuyuefeng committed
49
50
51
        checkpoint (str, optional): Checkpoint path. If left as None, the model
            will not load any weights.
        device (str): Device to use.
ChaimZhu's avatar
ChaimZhu committed
52
53
        cfg_options (dict, optional): Options to override some settings in
            the used config.
wuyuefeng's avatar
Demo  
wuyuefeng committed
54
55
56
57

    Returns:
        nn.Module: The constructed detector.
    """
ChaimZhu's avatar
ChaimZhu committed
58
    if isinstance(config, (str, Path)):
59
60
        config = Config.fromfile(config)
    elif not isinstance(config, Config):
wuyuefeng's avatar
Demo  
wuyuefeng committed
61
62
        raise TypeError('config must be a filename or Config object, '
                        f'but got {type(config)}')
ChaimZhu's avatar
ChaimZhu committed
63
64
    if cfg_options is not None:
        config.merge_from_dict(cfg_options)
65

66
    convert_SyncBN(config.model)
67
    config.model.train_cfg = None
68
    init_default_scope(config.get('default_scope', 'mmdet3d'))
zhangshilong's avatar
zhangshilong committed
69
    model = MODELS.build(config.model)
ChaimZhu's avatar
ChaimZhu committed
70

wuyuefeng's avatar
Demo  
wuyuefeng committed
71
    if checkpoint is not None:
72
        checkpoint = load_checkpoint(model, checkpoint, map_location='cpu')
ChaimZhu's avatar
ChaimZhu committed
73
74
75
        # save the dataset_meta in the model for convenience
        if 'dataset_meta' in checkpoint.get('meta', {}):
            # mmdet3d 1.x
76
            model.dataset_meta = checkpoint['meta']['dataset_meta']
ChaimZhu's avatar
ChaimZhu committed
77
78
79
        elif 'CLASSES' in checkpoint.get('meta', {}):
            # < mmdet3d 1.x
            classes = checkpoint['meta']['CLASSES']
80
            model.dataset_meta = {'classes': classes}
ChaimZhu's avatar
ChaimZhu committed
81
82

            if 'PALETTE' in checkpoint.get('meta', {}):  # 3D Segmentor
83
                model.dataset_meta['palette'] = checkpoint['meta']['PALETTE']
wuyuefeng's avatar
Demo  
wuyuefeng committed
84
        else:
ChaimZhu's avatar
ChaimZhu committed
85
            # < mmdet3d 1.x
86
            model.dataset_meta = {'classes': config.class_names}
ChaimZhu's avatar
ChaimZhu committed
87
88

            if 'PALETTE' in checkpoint.get('meta', {}):  # 3D Segmentor
89
                model.dataset_meta['palette'] = checkpoint['meta']['PALETTE']
ChaimZhu's avatar
ChaimZhu committed
90

91
92
93
94
95
96
97
98
99
100
101
102
103
104
        test_dataset_cfg = deepcopy(config.test_dataloader.dataset)
        # lazy init. We only need the metainfo.
        test_dataset_cfg['lazy_init'] = True
        metainfo = DATASETS.build(test_dataset_cfg).metainfo
        cfg_palette = metainfo.get('palette', None)
        if cfg_palette is not None:
            model.dataset_meta['palette'] = cfg_palette
        else:
            if 'palette' not in model.dataset_meta:
                warnings.warn(
                    'palette does not exist, random is used by default. '
                    'You can also set the palette to customize.')
                model.dataset_meta['palette'] = 'random'

wuyuefeng's avatar
Demo  
wuyuefeng committed
105
    model.cfg = config  # save the config in the model for convenience
106
107
108
    if device != 'cpu':
        torch.cuda.set_device(device)
    else:
ChaimZhu's avatar
ChaimZhu committed
109
110
111
        warnings.warn('Don\'t suggest using CPU device. '
                      'Some functions are not supported for now.')

wuyuefeng's avatar
Demo  
wuyuefeng committed
112
113
114
115
116
    model.to(device)
    model.eval()
    return model


ChaimZhu's avatar
ChaimZhu committed
117
118
119
120
121
122
PointsType = Union[str, np.ndarray, Sequence[str], Sequence[np.ndarray]]
ImagesType = Union[str, np.ndarray, Sequence[str], Sequence[np.ndarray]]


def inference_detector(model: nn.Module,
                       pcds: PointsType) -> Union[Det3DDataSample, SampleList]:
wuyuefeng's avatar
Demo  
wuyuefeng committed
123
124
125
126
    """Inference point cloud with the detector.

    Args:
        model (nn.Module): The loaded detector.
ChaimZhu's avatar
ChaimZhu committed
127
128
        pcds (str, ndarray, Sequence[str/ndarray]):
            Either point cloud files or loaded point cloud.
wuyuefeng's avatar
Demo  
wuyuefeng committed
129
130

    Returns:
ChaimZhu's avatar
ChaimZhu committed
131
132
133
        :obj:`Det3DDataSample` or list[:obj:`Det3DDataSample`]:
        If pcds is a list or tuple, the same length list type results
        will be returned, otherwise return the detection results directly.
wuyuefeng's avatar
Demo  
wuyuefeng committed
134
    """
ChaimZhu's avatar
ChaimZhu committed
135
136
137
138
139
140
    if isinstance(pcds, (list, tuple)):
        is_batch = True
    else:
        pcds = [pcds]
        is_batch = False

wuyuefeng's avatar
Demo  
wuyuefeng committed
141
    cfg = model.cfg
142

ChaimZhu's avatar
ChaimZhu committed
143
    if not isinstance(pcds[0], str):
144
145
        cfg = cfg.copy()
        # set loading pipeline type
ChaimZhu's avatar
ChaimZhu committed
146
        cfg.test_dataloader.dataset.pipeline[0].type = 'LoadPointsFromDict'
147

wuyuefeng's avatar
Demo  
wuyuefeng committed
148
    # build the data pipeline
ChaimZhu's avatar
ChaimZhu committed
149
    test_pipeline = deepcopy(cfg.test_dataloader.dataset.pipeline)
wuyuefeng's avatar
Demo  
wuyuefeng committed
150
    test_pipeline = Compose(test_pipeline)
151
152
    box_type_3d, box_mode_3d = \
        get_box_type(cfg.test_dataloader.dataset.box_type_3d)
ChaimZhu's avatar
ChaimZhu committed
153
154
155
156
157
158
159
160

    data = []
    for pcd in pcds:
        # prepare data
        if isinstance(pcd, str):
            # load from point cloud file
            data_ = dict(
                lidar_points=dict(lidar_path=pcd),
161
                timestamp=1,
ChaimZhu's avatar
ChaimZhu committed
162
                # for ScanNet demo we need axis_align_matrix
163
164
165
                axis_align_matrix=np.eye(4),
                box_type_3d=box_type_3d,
                box_mode_3d=box_mode_3d)
ChaimZhu's avatar
ChaimZhu committed
166
167
168
169
        else:
            # directly use loaded point cloud
            data_ = dict(
                points=pcd,
170
                timestamp=1,
ChaimZhu's avatar
ChaimZhu committed
171
                # for ScanNet demo we need axis_align_matrix
172
173
174
                axis_align_matrix=np.eye(4),
                box_type_3d=box_type_3d,
                box_mode_3d=box_mode_3d)
ChaimZhu's avatar
ChaimZhu committed
175
176
        data_ = test_pipeline(data_)
        data.append(data_)
177

178
179
    collate_data = pseudo_collate(data)

wuyuefeng's avatar
Demo  
wuyuefeng committed
180
181
    # forward the model
    with torch.no_grad():
182
        results = model.test_step(collate_data)
ChaimZhu's avatar
ChaimZhu committed
183
184

    if not is_batch:
185
        return results[0], data[0]
ChaimZhu's avatar
ChaimZhu committed
186
    else:
187
        return results, data
wuyuefeng's avatar
Demo  
wuyuefeng committed
188
189


ChaimZhu's avatar
ChaimZhu committed
190
191
192
def inference_multi_modality_detector(model: nn.Module,
                                      pcds: Union[str, Sequence[str]],
                                      imgs: Union[str, Sequence[str]],
193
                                      ann_file: Union[str, Sequence[str]],
194
195
                                      cam_type: str = 'CAM2'):
    """Inference point cloud with the multi-modality detector. Now we only
196
197
    support multi-modality detector for KITTI and SUNRGBD datasets since the
    multi-view image loading is not supported yet in this inference function.
198
199
200

    Args:
        model (nn.Module): The loaded detector.
ChaimZhu's avatar
ChaimZhu committed
201
202
203
204
        pcds (str, Sequence[str]):
            Either point cloud files or loaded point cloud.
        imgs (str, Sequence[str]):
           Either image files or loaded images.
205
        ann_file (str, Sequence[str]): Annotation files.
206
207
208
209
        cam_type (str): Image of Camera chose to infer. When detector only uses
            single-view image, we need to specify a camera view. For kitti
            dataset, it should be 'CAM2'. For sunrgbd, it should be 'CAM0'.
            When detector uses multi-view images, we should set it to 'all'.
210
211

    Returns:
ChaimZhu's avatar
ChaimZhu committed
212
213
214
        :obj:`Det3DDataSample` or list[:obj:`Det3DDataSample`]:
        If pcds is a list or tuple, the same length list type results
        will be returned, otherwise return the detection results directly.
215
    """
ChaimZhu's avatar
ChaimZhu committed
216
217
218
    if isinstance(pcds, (list, tuple)):
        is_batch = True
        assert isinstance(imgs, (list, tuple))
219
        assert len(pcds) == len(imgs)
ChaimZhu's avatar
ChaimZhu committed
220
221
222
223
224
    else:
        pcds = [pcds]
        imgs = [imgs]
        is_batch = False

225
    cfg = model.cfg
ChaimZhu's avatar
ChaimZhu committed
226

227
    # build the data pipeline
ChaimZhu's avatar
ChaimZhu committed
228
    test_pipeline = deepcopy(cfg.test_dataloader.dataset.pipeline)
229
    test_pipeline = Compose(test_pipeline)
ChaimZhu's avatar
ChaimZhu committed
230
231
232
    box_type_3d, box_mode_3d = \
        get_box_type(cfg.test_dataloader.dataset.box_type_3d)

233
    data_list = mmengine.load(ann_file)['data_list']
234

ChaimZhu's avatar
ChaimZhu committed
235
236
237
    data = []
    for index, pcd in enumerate(pcds):
        # get data info containing calib
238
        data_info = data_list[index]
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
        img = imgs[index]

        if cam_type != 'all':
            assert osp.isfile(img), f'{img} must be a file.'
            img_path = data_info['images'][cam_type]['img_path']
            if osp.basename(img_path) != osp.basename(img):
                raise ValueError(
                    f'the info file of {img_path} is not provided.')
            data_ = dict(
                lidar_points=dict(lidar_path=pcd),
                img_path=img,
                box_type_3d=box_type_3d,
                box_mode_3d=box_mode_3d)
            data_info['images'][cam_type]['img_path'] = img
            if 'cam2img' in data_info['images'][cam_type]:
                # The data annotation in SRUNRGBD dataset does not contain
                # `cam2img`
                data_['cam2img'] = np.array(
                    data_info['images'][cam_type]['cam2img'])

            # LiDAR to image conversion for KITTI dataset
            if box_mode_3d == Box3DMode.LIDAR:
                if 'lidar2img' in data_info['images'][cam_type]:
                    data_['lidar2img'] = np.array(
                        data_info['images'][cam_type]['lidar2img'])
            # Depth to image conversion for SUNRGBD dataset
            elif box_mode_3d == Box3DMode.DEPTH:
                data_['depth2img'] = np.array(
                    data_info['images'][cam_type]['depth2img'])
        else:
            assert osp.isdir(img), f'{img} must be a file directory'
            for _, img_info in data_info['images'].items():
                img_info['img_path'] = osp.join(img, img_info['img_path'])
                assert osp.isfile(img_info['img_path']
                                  ), f'{img_info["img_path"]} does not exist.'
            data_ = dict(
                lidar_points=dict(lidar_path=pcd),
                images=data_info['images'],
                box_type_3d=box_type_3d,
                box_mode_3d=box_mode_3d)

        if 'timestamp' in data_info:
            # Using multi-sweeps need `timestamp`
            data_['timestamp'] = data_info['timestamp']
ChaimZhu's avatar
ChaimZhu committed
283

284
        data_ = test_pipeline(data_)
ChaimZhu's avatar
ChaimZhu committed
285
        data.append(data_)
286

287
288
    collate_data = pseudo_collate(data)

289
290
    # forward the model
    with torch.no_grad():
291
        results = model.test_step(collate_data)
292

ChaimZhu's avatar
ChaimZhu committed
293
    if not is_batch:
294
        return results[0], data[0]
ChaimZhu's avatar
ChaimZhu committed
295
    else:
296
        return results, data
297
298


299
300
301
302
def inference_mono_3d_detector(model: nn.Module,
                               imgs: ImagesType,
                               ann_file: Union[str, Sequence[str]],
                               cam_type: str = 'CAM_FRONT'):
303
304
305
306
    """Inference image with the monocular 3D detector.

    Args:
        model (nn.Module): The loaded detector.
ChaimZhu's avatar
ChaimZhu committed
307
308
309
        imgs (str, Sequence[str]):
           Either image files or loaded images.
        ann_files (str, Sequence[str]): Annotation files.
310
311
312
313
        cam_type (str): Image of Camera chose to infer.
            For kitti dataset, it should be 'CAM_2',
            and for nuscenes dataset, it should be
            'CAM_FRONT'. Defaults to 'CAM_FRONT'.
314
315

    Returns:
ChaimZhu's avatar
ChaimZhu committed
316
317
318
        :obj:`Det3DDataSample` or list[:obj:`Det3DDataSample`]:
        If pcds is a list or tuple, the same length list type results
        will be returned, otherwise return the detection results directly.
319
    """
ChaimZhu's avatar
ChaimZhu committed
320
321
322
323
324
325
    if isinstance(imgs, (list, tuple)):
        is_batch = True
    else:
        imgs = [imgs]
        is_batch = False

326
    cfg = model.cfg
ChaimZhu's avatar
ChaimZhu committed
327

328
    # build the data pipeline
ChaimZhu's avatar
ChaimZhu committed
329
    test_pipeline = deepcopy(cfg.test_dataloader.dataset.pipeline)
330
    test_pipeline = Compose(test_pipeline)
ChaimZhu's avatar
ChaimZhu committed
331
332
333
    box_type_3d, box_mode_3d = \
        get_box_type(cfg.test_dataloader.dataset.box_type_3d)

334
    data_list = mmengine.load(ann_file)['data_list']
335
336
    assert len(imgs) == len(data_list)

ChaimZhu's avatar
ChaimZhu committed
337
338
339
    data = []
    for index, img in enumerate(imgs):
        # get data info containing calib
340
341
342
343
344
345
346
        data_info = data_list[index]
        img_path = data_info['images'][cam_type]['img_path']
        if osp.basename(img_path) != osp.basename(img):
            raise ValueError(f'the info file of {img_path} is not provided.')

        # replace the img_path in data_info with img
        data_info['images'][cam_type]['img_path'] = img
347
348
        # avoid data_info['images'] has multiple keys anout camera views.
        mono_img_info = {f'{cam_type}': data_info['images'][cam_type]}
ChaimZhu's avatar
ChaimZhu committed
349
        data_ = dict(
350
            images=mono_img_info,
ChaimZhu's avatar
ChaimZhu committed
351
352
353
354
            box_type_3d=box_type_3d,
            box_mode_3d=box_mode_3d)

        data_ = test_pipeline(data_)
355
        data.append(data_)
356

357
358
    collate_data = pseudo_collate(data)

359
360
    # forward the model
    with torch.no_grad():
361
        results = model.test_step(collate_data)
362

ChaimZhu's avatar
ChaimZhu committed
363
364
365
366
    if not is_batch:
        return results[0]
    else:
        return results
367

ChaimZhu's avatar
ChaimZhu committed
368
369

def inference_segmentor(model: nn.Module, pcds: PointsType):
370
    """Inference point cloud with the segmentor.
wuyuefeng's avatar
Demo  
wuyuefeng committed
371
372

    Args:
373
        model (nn.Module): The loaded segmentor.
ChaimZhu's avatar
ChaimZhu committed
374
375
        pcds (str, Sequence[str]):
            Either point cloud files or loaded point cloud.
376
377

    Returns:
ChaimZhu's avatar
ChaimZhu committed
378
379
380
        :obj:`Det3DDataSample` or list[:obj:`Det3DDataSample`]:
        If pcds is a list or tuple, the same length list type results
        will be returned, otherwise return the detection results directly.
wuyuefeng's avatar
Demo  
wuyuefeng committed
381
    """
ChaimZhu's avatar
ChaimZhu committed
382
383
384
385
386
387
    if isinstance(pcds, (list, tuple)):
        is_batch = True
    else:
        pcds = [pcds]
        is_batch = False

388
    cfg = model.cfg
ChaimZhu's avatar
ChaimZhu committed
389

390
    # build the data pipeline
ChaimZhu's avatar
ChaimZhu committed
391
    test_pipeline = deepcopy(cfg.test_dataloader.dataset.pipeline)
392
393
394

    new_test_pipeline = []
    for pipeline in test_pipeline:
395
396
        if pipeline['type'] != 'LoadAnnotations3D' and pipeline[
                'type'] != 'PointSegClassMapping':
397
398
            new_test_pipeline.append(pipeline)
    test_pipeline = Compose(new_test_pipeline)
ChaimZhu's avatar
ChaimZhu committed
399
400

    data = []
401
    # TODO: support load points array
ChaimZhu's avatar
ChaimZhu committed
402
403
404
405
406
    for pcd in pcds:
        data_ = dict(lidar_points=dict(lidar_path=pcd))
        data_ = test_pipeline(data_)
        data.append(data_)

407
408
    collate_data = pseudo_collate(data)

409
410
    # forward the model
    with torch.no_grad():
411
        results = model.test_step(collate_data)
ChaimZhu's avatar
ChaimZhu committed
412
413

    if not is_batch:
414
        return results[0], data[0]
ChaimZhu's avatar
ChaimZhu committed
415
    else:
416
        return results, data