kitti_dataset.py 19 KB
Newer Older
zhangwenwei's avatar
zhangwenwei committed
1
2
import copy
import os
3
4
import os.path as osp
import tempfile
zhangwenwei's avatar
zhangwenwei committed
5
6
7
8

import mmcv
import numpy as np
import torch
zhangwenwei's avatar
zhangwenwei committed
9
from mmcv.utils import print_log
zhangwenwei's avatar
zhangwenwei committed
10

zhangwenwei's avatar
zhangwenwei committed
11
from mmdet.datasets import DATASETS
12
from ..core.bbox import Box3DMode, CameraInstance3DBoxes, box_np_ops
zhangwenwei's avatar
zhangwenwei committed
13
from .custom_3d import Custom3DDataset
zhangwenwei's avatar
zhangwenwei committed
14
15
16
from .utils import remove_dontcare


17
@DATASETS.register_module()
zhangwenwei's avatar
zhangwenwei committed
18
class KittiDataset(Custom3DDataset):
zhangwenwei's avatar
zhangwenwei committed
19
20
21
22

    CLASSES = ('car', 'pedestrian', 'cyclist')

    def __init__(self,
zhangwenwei's avatar
zhangwenwei committed
23
                 data_root,
zhangwenwei's avatar
zhangwenwei committed
24
25
                 ann_file,
                 split,
zhangwenwei's avatar
zhangwenwei committed
26
                 pts_prefix='velodyne',
zhangwenwei's avatar
zhangwenwei committed
27
                 pipeline=None,
zhangwenwei's avatar
zhangwenwei committed
28
                 classes=None,
zhangwenwei's avatar
zhangwenwei committed
29
30
                 modality=None,
                 test_mode=False):
zhangwenwei's avatar
zhangwenwei committed
31
32
33
34
35
36
37
38
39
        super().__init__(
            data_root=data_root,
            ann_file=ann_file,
            pipeline=pipeline,
            classes=classes,
            modality=modality,
            test_mode=test_mode)

        self.root_split = os.path.join(self.data_root, split)
zhangwenwei's avatar
zhangwenwei committed
40
41
        assert self.modality is not None
        self.pcd_limit_range = [0, -40, -3, 70.4, 40, 0.0]
zhangwenwei's avatar
zhangwenwei committed
42
        self.pts_prefix = pts_prefix
zhangwenwei's avatar
zhangwenwei committed
43

zhangwenwei's avatar
zhangwenwei committed
44
45
46
47
    def _get_pts_filename(self, idx):
        pts_filename = osp.join(self.root_split, self.pts_prefix,
                                f'{idx:06d}.bin')
        return pts_filename
zhangwenwei's avatar
zhangwenwei committed
48

zhangwenwei's avatar
zhangwenwei committed
49
50
    def get_data_info(self, index):
        info = self.data_infos[index]
zhangwenwei's avatar
zhangwenwei committed
51
        sample_idx = info['image']['image_idx']
zhangwenwei's avatar
zhangwenwei committed
52
53
54
        img_filename = os.path.join(self.root_split,
                                    info['image']['image_path'])

zhangwenwei's avatar
zhangwenwei committed
55
56
57
58
59
60
        # TODO: consider use torch.Tensor only
        rect = info['calib']['R0_rect'].astype(np.float32)
        Trv2c = info['calib']['Tr_velo_to_cam'].astype(np.float32)
        P2 = info['calib']['P2'].astype(np.float32)
        lidar2img = P2 @ rect @ Trv2c

zhangwenwei's avatar
zhangwenwei committed
61
        pts_filename = self._get_pts_filename(sample_idx)
zhangwenwei's avatar
zhangwenwei committed
62
63
        input_dict = dict(
            sample_idx=sample_idx,
zhangwenwei's avatar
zhangwenwei committed
64
65
66
67
68
            pts_filename=pts_filename,
            img_filename=img_filename,
            lidar2img=lidar2img)

        if not self.test_mode:
zhangwenwei's avatar
zhangwenwei committed
69
            annos = self.get_ann_info(index)
zhangwenwei's avatar
zhangwenwei committed
70
            input_dict['ann_info'] = annos
zhangwenwei's avatar
zhangwenwei committed
71
72
73
74
75

        return input_dict

    def get_ann_info(self, index):
        # Use index to get the annos, thus the evalhook could also use this api
zhangwenwei's avatar
zhangwenwei committed
76
        info = self.data_infos[index]
zhangwenwei's avatar
zhangwenwei committed
77
78
79
80
81
82
83
84
85
86
87
88
89
        rect = info['calib']['R0_rect'].astype(np.float32)
        Trv2c = info['calib']['Tr_velo_to_cam'].astype(np.float32)

        annos = info['annos']
        # we need other objects to avoid collision when sample
        annos = remove_dontcare(annos)
        loc = annos['location']
        dims = annos['dimensions']
        rots = annos['rotation_y']
        gt_names = annos['name']
        # print(gt_names, len(loc))
        gt_bboxes_3d = np.concatenate([loc, dims, rots[..., np.newaxis]],
                                      axis=1).astype(np.float32)
90
91
92
93

        # convert gt_bboxes_3d to velodyne coordinates
        gt_bboxes_3d = CameraInstance3DBoxes(gt_bboxes_3d).convert_to(
            Box3DMode.LIDAR, np.linalg.inv(rect @ Trv2c))
zhangwenwei's avatar
zhangwenwei committed
94
95
96
        gt_bboxes = annos['bbox']

        selected = self.drop_arrays_by_name(gt_names, ['DontCare'])
97
        # gt_bboxes_3d = gt_bboxes_3d[selected].astype('float32')
zhangwenwei's avatar
zhangwenwei committed
98
99
100
101
102
103
104
105
106
107
108
        gt_bboxes = gt_bboxes[selected].astype('float32')
        gt_names = gt_names[selected]

        gt_labels = []
        for cat in gt_names:
            if cat in self.CLASSES:
                gt_labels.append(self.CLASSES.index(cat))
            else:
                gt_labels.append(-1)
        gt_labels = np.array(gt_labels)
        gt_labels_3d = copy.deepcopy(gt_labels)
zhangwenwei's avatar
zhangwenwei committed
109
110
111

        anns_results = dict(
            gt_bboxes_3d=gt_bboxes_3d,
zhangwenwei's avatar
zhangwenwei committed
112
113
114
            gt_labels_3d=gt_labels_3d,
            gt_bboxes=gt_bboxes,
            gt_labels=gt_labels)
zhangwenwei's avatar
zhangwenwei committed
115
116
117
118
119
120
121
122
123
124
125
126
        return anns_results

    def drop_arrays_by_name(self, gt_names, used_classes):
        inds = [i for i, x in enumerate(gt_names) if x not in used_classes]
        inds = np.array(inds, dtype=np.int64)
        return inds

    def keep_arrays_by_name(self, gt_names, used_classes):
        inds = [i for i, x in enumerate(gt_names) if x in used_classes]
        inds = np.array(inds, dtype=np.int64)
        return inds

127
128
129
130
131
132
133
134
135
136
    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')
        else:
            tmp_dir = None

zhangwenwei's avatar
zhangwenwei committed
137
        if not isinstance(outputs[0], dict):
zhangwenwei's avatar
zhangwenwei committed
138
            result_files = self.bbox2result_kitti2d(outputs, self.CLASSES,
zhangwenwei's avatar
zhangwenwei committed
139
                                                    pklfile_prefix,
140
                                                    submission_prefix)
zhangwenwei's avatar
zhangwenwei committed
141
        else:
zhangwenwei's avatar
zhangwenwei committed
142
            result_files = self.bbox2result_kitti(outputs, self.CLASSES,
143
144
                                                  pklfile_prefix,
                                                  submission_prefix)
zhangwenwei's avatar
zhangwenwei committed
145
        return result_files, tmp_dir
zhangwenwei's avatar
zhangwenwei committed
146

147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
    def evaluate(self,
                 results,
                 metric=None,
                 logger=None,
                 pklfile_prefix=None,
                 submission_prefix=None,
                 result_names=['pts_bbox']):
        """Evaluation in KITTI protocol.

        Args:
            results (list): Testing results of the dataset.
            metric (str | list[str]): Metrics to be evaluated.
            logger (logging.Logger | str | None): Logger used for printing
                related information during evaluation. Default: None.
            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.
            submission_prefix (str | None): The prefix of submission datas.
                If not specified, the submission data will not be generated.

        Returns:
            dict[str: float]
        """
        result_files, tmp_dir = self.format_results(results, pklfile_prefix)
zhangwenwei's avatar
zhangwenwei committed
171
        from mmdet3d.core.evaluation import kitti_eval
zhangwenwei's avatar
zhangwenwei committed
172
        gt_annos = [info['annos'] for info in self.data_infos]
173
        if metric == 'img_bbox':
zhangwenwei's avatar
zhangwenwei committed
174
            ap_result_str, ap_dict = kitti_eval(
zhangwenwei's avatar
zhangwenwei committed
175
                gt_annos, result_files, self.CLASSES, eval_types=['bbox'])
zhangwenwei's avatar
zhangwenwei committed
176
177
        else:
            ap_result_str, ap_dict = kitti_eval(gt_annos, result_files,
zhangwenwei's avatar
zhangwenwei committed
178
                                                self.CLASSES)
zhangwenwei's avatar
zhangwenwei committed
179
        print_log('\n' + ap_result_str, logger=logger)
180
181
        if tmp_dir is not None:
            tmp_dir.cleanup()
182
        return ap_dict
183
184
185
186
187
188

    def bbox2result_kitti(self,
                          net_outputs,
                          class_names,
                          pklfile_prefix=None,
                          submission_prefix=None):
zhangwenwei's avatar
zhangwenwei committed
189
        assert len(net_outputs) == len(self.data_infos)
190
191
        if submission_prefix is not None:
            mmcv.mkdir_or_exist(submission_prefix)
zhangwenwei's avatar
zhangwenwei committed
192
193

        det_annos = []
zhangwenwei's avatar
zhangwenwei committed
194
        print('\nConverting prediction to KITTI format')
zhangwenwei's avatar
zhangwenwei committed
195
196
197
        for idx, pred_dicts in enumerate(
                mmcv.track_iter_progress(net_outputs)):
            annos = []
zhangwenwei's avatar
zhangwenwei committed
198
            info = self.data_infos[idx]
zhangwenwei's avatar
zhangwenwei committed
199
            sample_idx = info['image']['image_idx']
zhangwenwei's avatar
zhangwenwei committed
200
            image_shape = info['image']['image_shape'][:2]
zhangwenwei's avatar
zhangwenwei committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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
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

            box_dict = self.convert_valid_bboxes(pred_dicts, info)
            if len(box_dict['bbox']) > 0:
                box_2d_preds = box_dict['bbox']
                box_preds = box_dict['box3d_camera']
                scores = box_dict['scores']
                box_preds_lidar = box_dict['box3d_lidar']
                label_preds = box_dict['label_preds']

                anno = {
                    'name': [],
                    'truncated': [],
                    'occluded': [],
                    'alpha': [],
                    'bbox': [],
                    'dimensions': [],
                    'location': [],
                    'rotation_y': [],
                    'score': []
                }

                for box, box_lidar, bbox, score, label in zip(
                        box_preds, box_preds_lidar, box_2d_preds, scores,
                        label_preds):
                    bbox[2:] = np.minimum(bbox[2:], image_shape[::-1])
                    bbox[:2] = np.maximum(bbox[:2], [0, 0])
                    anno['name'].append(class_names[int(label)])
                    anno['truncated'].append(0.0)
                    anno['occluded'].append(0)
                    anno['alpha'].append(
                        -np.arctan2(-box_lidar[1], box_lidar[0]) + box[6])
                    anno['bbox'].append(bbox)
                    anno['dimensions'].append(box[3:6])
                    anno['location'].append(box[:3])
                    anno['rotation_y'].append(box[6])
                    anno['score'].append(score)

                anno = {k: np.stack(v) for k, v in anno.items()}
                annos.append(anno)

                if submission_prefix is not None:
                    curr_file = f'{submission_prefix}/{sample_idx:06d}.txt'
                    with open(curr_file, 'w') as f:
                        bbox = anno['bbox']
                        loc = anno['location']
                        dims = anno['dimensions']  # lhw -> hwl

                        for idx in range(len(bbox)):
                            print(
                                '{} -1 -1 {:.4f} {:.4f} {:.4f} {:.4f} '
                                '{:.4f} {:.4f} {:.4f} '
                                '{:.4f} {:.4f} {:.4f} {:.4f} {:.4f} {:.4f}'.
                                format(anno['name'][idx], anno['alpha'][idx],
                                       bbox[idx][0], bbox[idx][1],
                                       bbox[idx][2], bbox[idx][3],
                                       dims[idx][1], dims[idx][2],
                                       dims[idx][0], loc[idx][0], loc[idx][1],
                                       loc[idx][2], anno['rotation_y'][idx],
                                       anno['score'][idx]),
                                file=f)
            else:
                annos.append({
                    'name': np.array([]),
                    'truncated': np.array([]),
                    'occluded': np.array([]),
                    'alpha': np.array([]),
                    'bbox': np.zeros([0, 4]),
                    'dimensions': np.zeros([0, 3]),
                    'location': np.zeros([0, 3]),
                    'rotation_y': np.array([]),
                    'score': np.array([]),
                })
            annos[-1]['sample_idx'] = np.array(
                [sample_idx] * len(annos[-1]['score']), dtype=np.int64)
zhangwenwei's avatar
zhangwenwei committed
275
276
277

            det_annos += annos

278
279
280
        if pklfile_prefix is not None:
            if not pklfile_prefix.endswith(('.pkl', '.pickle')):
                out = f'{pklfile_prefix}.pkl'
zhangwenwei's avatar
zhangwenwei committed
281
282
283
284
285
286
287
288
            mmcv.dump(det_annos, out)
            print('Result is saved to %s' % out)

        return det_annos

    def bbox2result_kitti2d(self,
                            net_outputs,
                            class_names,
289
290
                            pklfile_prefix=None,
                            submission_prefix=None):
zhangwenwei's avatar
zhangwenwei committed
291
292
293
294
295
        """Convert results to kitti format for evaluation and test submission

        Args:
            net_outputs (List[array]): list of array storing the bbox and score
            class_nanes (List[String]): A list of class names
296
297
            pklfile_prefix (str | None): The prefix of pkl file.
            submission_prefix (str | None): The prefix of submission file.
zhangwenwei's avatar
zhangwenwei committed
298
299
300
301

        Return:
            List([dict]): A list of dict have the kitti format
        """
zhangwenwei's avatar
zhangwenwei committed
302
        assert len(net_outputs) == len(self.data_infos)
zhangwenwei's avatar
zhangwenwei committed
303
304

        det_annos = []
zhangwenwei's avatar
zhangwenwei committed
305
        print('\nConverting prediction to KITTI format')
zhangwenwei's avatar
zhangwenwei committed
306
307
308
309
310
311
312
313
314
315
316
317
318
        for i, bboxes_per_sample in enumerate(
                mmcv.track_iter_progress(net_outputs)):
            annos = []
            anno = dict(
                name=[],
                truncated=[],
                occluded=[],
                alpha=[],
                bbox=[],
                dimensions=[],
                location=[],
                rotation_y=[],
                score=[])
zhangwenwei's avatar
zhangwenwei committed
319
            sample_idx = self.data_infos[i]['image']['image_idx']
zhangwenwei's avatar
zhangwenwei committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360

            num_example = 0
            for label in range(len(bboxes_per_sample)):
                bbox = bboxes_per_sample[label]
                for i in range(bbox.shape[0]):
                    anno['name'].append(class_names[int(label)])
                    anno['truncated'].append(0.0)
                    anno['occluded'].append(0)
                    anno['alpha'].append(0.0)
                    anno['bbox'].append(bbox[i, :4])
                    # set dimensions (height, width, length) to zero
                    anno['dimensions'].append(
                        np.zeros(shape=[3], dtype=np.float32))
                    # set the 3D translation to (-1000, -1000, -1000)
                    anno['location'].append(
                        np.ones(shape=[3], dtype=np.float32) * (-1000.0))
                    anno['rotation_y'].append(0.0)
                    anno['score'].append(bbox[i, 4])
                    num_example += 1

            if num_example == 0:
                annos.append(
                    dict(
                        name=np.array([]),
                        truncated=np.array([]),
                        occluded=np.array([]),
                        alpha=np.array([]),
                        bbox=np.zeros([0, 4]),
                        dimensions=np.zeros([0, 3]),
                        location=np.zeros([0, 3]),
                        rotation_y=np.array([]),
                        score=np.array([]),
                    ))
            else:
                anno = {k: np.stack(v) for k, v in anno.items()}
                annos.append(anno)

            annos[-1]['sample_idx'] = np.array(
                [sample_idx] * num_example, dtype=np.int64)
            det_annos += annos

361
362
363
364
365
366
367
368
        if pklfile_prefix is not None:
            # save file in pkl format
            pklfile_path = (
                pklfile_prefix[:-4] if pklfile_prefix.endswith(
                    ('.pkl', '.pickle')) else pklfile_prefix)
            mmcv.dump(det_annos, pklfile_path)

        if submission_prefix is not None:
zhangwenwei's avatar
zhangwenwei committed
369
            # save file in submission format
370
371
            mmcv.mkdir_or_exist(submission_prefix)
            print(f'Saving KITTI submission to {submission_prefix}')
zhangwenwei's avatar
zhangwenwei committed
372
            for i, anno in enumerate(det_annos):
zhangwenwei's avatar
zhangwenwei committed
373
                sample_idx = self.data_infos[i]['image']['image_idx']
374
                cur_det_file = f'{submission_prefix}/{sample_idx:06d}.txt'
zhangwenwei's avatar
zhangwenwei committed
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
                with open(cur_det_file, 'w') as f:
                    bbox = anno['bbox']
                    loc = anno['location']
                    dims = anno['dimensions'][::-1]  # lhw -> hwl
                    for idx in range(len(bbox)):
                        print(
                            '{} -1 -1 {:4f} {:4f} {:4f} {:4f} {:4f} {:4f} '
                            '{:4f} {:4f} {:4f} {:4f} {:4f} {:4f} {:4f}'.format(
                                anno['name'][idx],
                                anno['alpha'][idx],
                                *bbox[idx],  # 4 float
                                *dims[idx],  # 3 float
                                *loc[idx],  # 3 float
                                anno['rotation_y'][idx],
                                anno['score'][idx]),
                            file=f,
                        )
392
            print('Result is saved to {}'.format(submission_prefix))
zhangwenwei's avatar
zhangwenwei committed
393
394
395
396
397

        return det_annos

    def convert_valid_bboxes(self, box_dict, info):
        # TODO: refactor this function
zhangwenwei's avatar
zhangwenwei committed
398
399
400
        final_box_preds = box_dict['boxes_3d']
        final_scores = box_dict['scores_3d']
        final_labels = box_dict['labels_3d']
zhangwenwei's avatar
zhangwenwei committed
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
        sample_idx = info['image']['image_idx']
        final_box_preds[:, -1] = box_np_ops.limit_period(
            final_box_preds[:, -1] - np.pi, offset=0.5, period=np.pi * 2)

        if final_box_preds.shape[0] == 0:
            return dict(
                bbox=final_box_preds.new_zeros([0, 4]).numpy(),
                box3d_camera=final_box_preds.new_zeros([0, 7]).numpy(),
                box3d_lidar=final_box_preds.new_zeros([0, 7]).numpy(),
                scores=final_box_preds.new_zeros([0]).numpy(),
                label_preds=final_box_preds.new_zeros([0, 4]).numpy(),
                sample_idx=sample_idx,
            )

        from mmdet3d.core.bbox import box_torch_ops
        rect = info['calib']['R0_rect'].astype(np.float32)
        Trv2c = info['calib']['Tr_velo_to_cam'].astype(np.float32)
        P2 = info['calib']['P2'].astype(np.float32)
        img_shape = info['image']['image_shape']
        rect = final_box_preds.new_tensor(rect)
        Trv2c = final_box_preds.new_tensor(Trv2c)
        P2 = final_box_preds.new_tensor(P2)

        final_box_preds_camera = box_torch_ops.box_lidar_to_camera(
            final_box_preds, rect, Trv2c)
        locs = final_box_preds_camera[:, :3]
        dims = final_box_preds_camera[:, 3:6]
        angles = final_box_preds_camera[:, 6]
        camera_box_origin = [0.5, 1.0, 0.5]
        box_corners = box_torch_ops.center_to_corner_box3d(
            locs, dims, angles, camera_box_origin, axis=1)
        box_corners_in_image = box_torch_ops.project_to_image(box_corners, P2)
        # box_corners_in_image: [N, 8, 2]
        minxy = torch.min(box_corners_in_image, dim=1)[0]
        maxxy = torch.max(box_corners_in_image, dim=1)[0]
        box_2d_preds = torch.cat([minxy, maxxy], dim=1)
        # Post-processing
        # check final_box_preds_camera
        image_shape = final_box_preds.new_tensor(img_shape)
        valid_cam_inds = ((final_box_preds_camera[:, 0] < image_shape[1]) &
                          (final_box_preds_camera[:, 1] < image_shape[0]) &
                          (final_box_preds_camera[:, 2] > 0) &
                          (final_box_preds_camera[:, 3] > 0))
        # check final_box_preds
        limit_range = final_box_preds.new_tensor(self.pcd_limit_range)
        valid_pcd_inds = ((final_box_preds[:, :3] > limit_range[:3]) &
                          (final_box_preds[:, :3] < limit_range[3:]))
        valid_inds = valid_cam_inds & valid_pcd_inds.all(-1)

        if valid_inds.sum() > 0:
            return dict(
                bbox=box_2d_preds[valid_inds, :].numpy(),
                box3d_camera=final_box_preds_camera[valid_inds, :].numpy(),
                box3d_lidar=final_box_preds[valid_inds, :].numpy(),
                scores=final_scores[valid_inds].numpy(),
                label_preds=final_labels[valid_inds].numpy(),
                sample_idx=sample_idx,
            )
        else:
            return dict(
                bbox=final_box_preds.new_zeros([0, 4]).numpy(),
                box3d_camera=final_box_preds.new_zeros([0, 7]).numpy(),
                box3d_lidar=final_box_preds.new_zeros([0, 7]).numpy(),
                scores=final_box_preds.new_zeros([0]).numpy(),
                label_preds=final_box_preds.new_zeros([0, 4]).numpy(),
                sample_idx=sample_idx,
            )