formating.py 11.3 KB
Newer Older
dingchang's avatar
dingchang committed
1
# Copyright (c) OpenMMLab. All rights reserved.
zhangwenwei's avatar
zhangwenwei committed
2
3
4
import numpy as np
from mmcv.parallel import DataContainer as DC

5
from mmdet3d.core.bbox import BaseInstance3DBoxes
6
from mmdet3d.core.points import BasePoints
7
from mmdet.datasets.builder import PIPELINES
zhangwenwei's avatar
zhangwenwei committed
8
from mmdet.datasets.pipelines import to_tensor
zhangwenwei's avatar
zhangwenwei committed
9
10
11
12

PIPELINES._module_dict.pop('DefaultFormatBundle')


13
@PIPELINES.register_module()
zhangwenwei's avatar
zhangwenwei committed
14
15
16
17
18
19
20
21
22
23
24
25
26
class DefaultFormatBundle(object):
    """Default formatting bundle.

    It simplifies the pipeline of formatting common fields, including "img",
    "proposals", "gt_bboxes", "gt_labels", "gt_masks" and "gt_semantic_seg".
    These fields are formatted as follows.

    - img: (1)transpose, (2)to tensor, (3)to DataContainer (stack=True)
    - proposals: (1)to tensor, (2)to DataContainer
    - gt_bboxes: (1)to tensor, (2)to DataContainer
    - gt_bboxes_ignore: (1)to tensor, (2)to DataContainer
    - gt_labels: (1)to tensor, (2)to DataContainer
    - gt_masks: (1)to tensor, (2)to DataContainer (cpu_only=True)
zhangwenwei's avatar
zhangwenwei committed
27
    - gt_semantic_seg: (1)unsqueeze dim-0 (2)to tensor, \
zhangwenwei's avatar
zhangwenwei committed
28
29
30
31
32
33
34
                       (3)to DataContainer (stack=True)
    """

    def __init__(self, ):
        return

    def __call__(self, results):
35
36
37
38
39
40
41
42
43
        """Call function to transform and format common fields in results.

        Args:
            results (dict): Result dict contains the data to convert.

        Returns:
            dict: The result dict contains the data that is formatted with
                default bundle.
        """
zhangwenwei's avatar
zhangwenwei committed
44
45
46
47
48
49
50
51
52
53
        if 'img' in results:
            if isinstance(results['img'], list):
                # process multiple imgs in single frame
                imgs = [img.transpose(2, 0, 1) for img in results['img']]
                imgs = np.ascontiguousarray(np.stack(imgs, axis=0))
                results['img'] = DC(to_tensor(imgs), stack=True)
            else:
                img = np.ascontiguousarray(results['img'].transpose(2, 0, 1))
                results['img'] = DC(to_tensor(img), stack=True)
        for key in [
54
                'proposals', 'gt_bboxes', 'gt_bboxes_ignore', 'gt_labels',
55
56
                'gt_labels_3d', 'attr_labels', 'pts_instance_mask',
                'pts_semantic_mask', 'centers2d', 'depths'
zhangwenwei's avatar
zhangwenwei committed
57
58
59
60
61
62
63
        ]:
            if key not in results:
                continue
            if isinstance(results[key], list):
                results[key] = DC([to_tensor(res) for res in results[key]])
            else:
                results[key] = DC(to_tensor(results[key]))
64
65
66
67
68
69
70
71
        if 'gt_bboxes_3d' in results:
            if isinstance(results['gt_bboxes_3d'], BaseInstance3DBoxes):
                results['gt_bboxes_3d'] = DC(
                    results['gt_bboxes_3d'], cpu_only=True)
            else:
                results['gt_bboxes_3d'] = DC(
                    to_tensor(results['gt_bboxes_3d']))

zhangwenwei's avatar
zhangwenwei committed
72
73
74
75
76
        if 'gt_masks' in results:
            results['gt_masks'] = DC(results['gt_masks'], cpu_only=True)
        if 'gt_semantic_seg' in results:
            results['gt_semantic_seg'] = DC(
                to_tensor(results['gt_semantic_seg'][None, ...]), stack=True)
77

zhangwenwei's avatar
zhangwenwei committed
78
79
80
81
82
83
        return results

    def __repr__(self):
        return self.__class__.__name__


84
@PIPELINES.register_module()
zhangwenwei's avatar
zhangwenwei committed
85
class Collect3D(object):
wangtai's avatar
wangtai committed
86
87
88
89
90
91
92
93
94
    """Collect data from the loader relevant to the specific task.

    This is usually the last stage of the data loader pipeline. Typically keys
    is set to some subset of "img", "proposals", "gt_bboxes",
    "gt_bboxes_ignore", "gt_labels", and/or "gt_masks".

    The "img_meta" item is always populated.  The contents of the "img_meta"
    dictionary depends on "meta_keys". By default this includes:

zhangwenwei's avatar
zhangwenwei committed
95
96
        - 'img_shape': shape of the image input to the network as a tuple \
            (h, w, c).  Note that images may be zero padded on the \
wangtai's avatar
wangtai committed
97
            bottom/right if the batch tensor is larger than this shape.
zhangwenwei's avatar
zhangwenwei committed
98
99
100
101
102
103
        - 'scale_factor': a float indicating the preprocessing scale
        - 'flip': a boolean indicating if image flip transform was used
        - 'filename': path to the image file
        - 'ori_shape': original shape of the image as a tuple (h, w, c)
        - 'pad_shape': image shape after padding
        - 'lidar2img': transform from lidar to image
104
        - 'depth2img': transform from depth to image
105
        - 'cam2img': transform from camera to image
zhangwenwei's avatar
zhangwenwei committed
106
        - 'pcd_horizontal_flip': a boolean indicating if point cloud is \
wangtai's avatar
wangtai committed
107
            flipped horizontally
zhangwenwei's avatar
zhangwenwei committed
108
        - 'pcd_vertical_flip': a boolean indicating if point cloud is \
wangtai's avatar
wangtai committed
109
110
111
112
            flipped vertically
        - 'box_mode_3d': 3D box mode
        - 'box_type_3d': 3D box type
        - 'img_norm_cfg': a dict of normalization information:
zhangwenwei's avatar
zhangwenwei committed
113
114
115
            - mean: per channel mean subtraction
            - std: per channel std divisor
            - to_rgb: bool indicating if bgr was converted to rgb
wangtai's avatar
wangtai committed
116
117
118
119
120
121
122
123
124
125
        - 'pcd_trans': point cloud transformations
        - 'sample_idx': sample index
        - 'pcd_scale_factor': point cloud scale factor
        - 'pcd_rotation': rotation applied to point cloud
        - 'pts_filename': path to point cloud file.

    Args:
        keys (Sequence[str]): Keys of results to be collected in ``data``.
        meta_keys (Sequence[str], optional): Meta keys to be converted to
            ``mmcv.DataContainer`` and collected in ``data[img_metas]``.
126
127
128
129
            Default: ('filename', 'ori_shape', 'img_shape', 'lidar2img',
            'depth2img', 'cam2img', 'pad_shape', 'scale_factor', 'flip',
            'pcd_horizontal_flip', 'pcd_vertical_flip', 'box_mode_3d',
            'box_type_3d', 'img_norm_cfg', 'pcd_trans',
zhangwenwei's avatar
zhangwenwei committed
130
            'sample_idx', 'pcd_scale_factor', 'pcd_rotation', 'pts_filename')
wangtai's avatar
wangtai committed
131
    """
zhangwenwei's avatar
zhangwenwei committed
132
133
134
135

    def __init__(self,
                 keys,
                 meta_keys=('filename', 'ori_shape', 'img_shape', 'lidar2img',
136
137
                            'depth2img', 'cam2img', 'pad_shape',
                            'scale_factor', 'flip', 'pcd_horizontal_flip',
138
                            'pcd_vertical_flip', 'box_mode_3d', 'box_type_3d',
139
                            'img_norm_cfg', 'pcd_trans', 'sample_idx',
140
141
                            'pcd_scale_factor', 'pcd_rotation',
                            'pcd_rotation_angle', 'pts_filename',
142
                            'transformation_3d_flow')):
zhangwenwei's avatar
zhangwenwei committed
143
144
145
146
        self.keys = keys
        self.meta_keys = meta_keys

    def __call__(self, results):
147
148
149
150
151
152
153
154
155
156
157
        """Call function to collect keys in results. The keys in ``meta_keys``
        will be converted to :obj:`mmcv.DataContainer`.

        Args:
            results (dict): Result dict contains the data to collect.

        Returns:
            dict: The result dict contains the following keys
                - keys in ``self.keys``
                - ``img_metas``
        """
zhangwenwei's avatar
zhangwenwei committed
158
        data = {}
zhangwenwei's avatar
zhangwenwei committed
159
        img_metas = {}
zhangwenwei's avatar
zhangwenwei committed
160
161
        for key in self.meta_keys:
            if key in results:
zhangwenwei's avatar
zhangwenwei committed
162
                img_metas[key] = results[key]
163

zhangwenwei's avatar
zhangwenwei committed
164
        data['img_metas'] = DC(img_metas, cpu_only=True)
zhangwenwei's avatar
zhangwenwei committed
165
166
167
168
169
        for key in self.keys:
            data[key] = results[key]
        return data

    def __repr__(self):
170
        """str: Return a string that describes the module."""
171
172
        return self.__class__.__name__ + \
            f'(keys={self.keys}, meta_keys={self.meta_keys})'
zhangwenwei's avatar
zhangwenwei committed
173
174


175
@PIPELINES.register_module()
zhangwenwei's avatar
zhangwenwei committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
class DefaultFormatBundle3D(DefaultFormatBundle):
    """Default formatting bundle.

    It simplifies the pipeline of formatting common fields for voxels,
    including "proposals", "gt_bboxes", "gt_labels", "gt_masks" and
    "gt_semantic_seg".
    These fields are formatted as follows.

    - img: (1)transpose, (2)to tensor, (3)to DataContainer (stack=True)
    - proposals: (1)to tensor, (2)to DataContainer
    - gt_bboxes: (1)to tensor, (2)to DataContainer
    - gt_bboxes_ignore: (1)to tensor, (2)to DataContainer
    - gt_labels: (1)to tensor, (2)to DataContainer
    """

    def __init__(self, class_names, with_gt=True, with_label=True):
        super(DefaultFormatBundle3D, self).__init__()
        self.class_names = class_names
        self.with_gt = with_gt
        self.with_label = with_label

    def __call__(self, results):
198
199
200
201
202
203
204
205
206
        """Call function to transform and format common fields in results.

        Args:
            results (dict): Result dict contains the data to convert.

        Returns:
            dict: The result dict contains the data that is formatted with
                default bundle.
        """
zhangwenwei's avatar
zhangwenwei committed
207
        # Format 3D data
208
209
210
211
212
        if 'points' in results:
            assert isinstance(results['points'], BasePoints)
            results['points'] = DC(results['points'].tensor)

        for key in ['voxels', 'coors', 'voxel_centers', 'num_points']:
zhangwenwei's avatar
zhangwenwei committed
213
214
215
216
217
218
219
220
221
222
            if key not in results:
                continue
            results[key] = DC(to_tensor(results[key]), stack=False)

        if self.with_gt:
            # Clean GT bboxes in the final
            if 'gt_bboxes_3d_mask' in results:
                gt_bboxes_3d_mask = results['gt_bboxes_3d_mask']
                results['gt_bboxes_3d'] = results['gt_bboxes_3d'][
                    gt_bboxes_3d_mask]
223
224
225
                if 'gt_names_3d' in results:
                    results['gt_names_3d'] = results['gt_names_3d'][
                        gt_bboxes_3d_mask]
226
227
228
229
230
                if 'centers2d' in results:
                    results['centers2d'] = results['centers2d'][
                        gt_bboxes_3d_mask]
                if 'depths' in results:
                    results['depths'] = results['depths'][gt_bboxes_3d_mask]
zhangwenwei's avatar
zhangwenwei committed
231
232
233
234
235
236
237
238
            if 'gt_bboxes_mask' in results:
                gt_bboxes_mask = results['gt_bboxes_mask']
                if 'gt_bboxes' in results:
                    results['gt_bboxes'] = results['gt_bboxes'][gt_bboxes_mask]
                results['gt_names'] = results['gt_names'][gt_bboxes_mask]
            if self.with_label:
                if 'gt_names' in results and len(results['gt_names']) == 0:
                    results['gt_labels'] = np.array([], dtype=np.int64)
239
                    results['attr_labels'] = np.array([], dtype=np.int64)
zhangwenwei's avatar
zhangwenwei committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
                elif 'gt_names' in results and isinstance(
                        results['gt_names'][0], list):
                    # gt_labels might be a list of list in multi-view setting
                    results['gt_labels'] = [
                        np.array([self.class_names.index(n) for n in res],
                                 dtype=np.int64) for res in results['gt_names']
                    ]
                elif 'gt_names' in results:
                    results['gt_labels'] = np.array([
                        self.class_names.index(n) for n in results['gt_names']
                    ],
                                                    dtype=np.int64)
                # we still assume one pipeline for one frame LiDAR
                # thus, the 3D name is list[string]
254
255
256
257
258
259
                if 'gt_names_3d' in results:
                    results['gt_labels_3d'] = np.array([
                        self.class_names.index(n)
                        for n in results['gt_names_3d']
                    ],
                                                       dtype=np.int64)
zhangwenwei's avatar
zhangwenwei committed
260
261
262
263
        results = super(DefaultFormatBundle3D, self).__call__(results)
        return results

    def __repr__(self):
264
        """str: Return a string that describes the module."""
zhangwenwei's avatar
zhangwenwei committed
265
        repr_str = self.__class__.__name__
266
267
        repr_str += f'(class_names={self.class_names}, '
        repr_str += f'with_gt={self.with_gt}, with_label={self.with_label})'
zhangwenwei's avatar
zhangwenwei committed
268
        return repr_str