voxel_generator.py 11.2 KB
Newer Older
dingchang's avatar
dingchang committed
1
# Copyright (c) OpenMMLab. All rights reserved.
zhangwenwei's avatar
zhangwenwei committed
2
3
4
import numba
import numpy as np

5
from mmdet3d.registry import MODELS
zhangwenwei's avatar
zhangwenwei committed
6

7
8

@MODELS.register_module()
zhangwenwei's avatar
zhangwenwei committed
9
class VoxelGenerator(object):
zhangwenwei's avatar
zhangwenwei committed
10
    """Voxel generator in numpy implementation.
zhangwenwei's avatar
zhangwenwei committed
11
12
13
14
15
16
17
18

    Args:
        voxel_size (list[float]): Size of a single voxel
        point_cloud_range (list[float]): Range of points
        max_num_points (int): Maximum number of points in a single voxel
        max_voxels (int, optional): Maximum number of voxels.
            Defaults to 20000.
    """
zhangwenwei's avatar
zhangwenwei committed
19
20
21
22
23
24

    def __init__(self,
                 voxel_size,
                 point_cloud_range,
                 max_num_points,
                 max_voxels=20000):
zhangwenwei's avatar
zhangwenwei committed
25

zhangwenwei's avatar
zhangwenwei committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
        point_cloud_range = np.array(point_cloud_range, dtype=np.float32)
        # [0, -40, -3, 70.4, 40, 1]
        voxel_size = np.array(voxel_size, dtype=np.float32)
        grid_size = (point_cloud_range[3:] -
                     point_cloud_range[:3]) / voxel_size
        grid_size = np.round(grid_size).astype(np.int64)

        self._voxel_size = voxel_size
        self._point_cloud_range = point_cloud_range
        self._max_num_points = max_num_points
        self._max_voxels = max_voxels
        self._grid_size = grid_size

    def generate(self, points):
zhangwenwei's avatar
zhangwenwei committed
40
        """Generate voxels given points."""
zhangwenwei's avatar
zhangwenwei committed
41
42
43
44
45
46
        return points_to_voxel(points, self._voxel_size,
                               self._point_cloud_range, self._max_num_points,
                               True, self._max_voxels)

    @property
    def voxel_size(self):
wangtai's avatar
wangtai committed
47
        """list[float]: Size of a single voxel."""
zhangwenwei's avatar
zhangwenwei committed
48
49
50
51
        return self._voxel_size

    @property
    def max_num_points_per_voxel(self):
wangtai's avatar
wangtai committed
52
        """int: Maximum number of points per voxel."""
zhangwenwei's avatar
zhangwenwei committed
53
54
55
56
        return self._max_num_points

    @property
    def point_cloud_range(self):
wangtai's avatar
wangtai committed
57
        """list[float]: Range of point cloud."""
zhangwenwei's avatar
zhangwenwei committed
58
59
60
61
        return self._point_cloud_range

    @property
    def grid_size(self):
wangtai's avatar
wangtai committed
62
        """np.ndarray: The size of grids."""
zhangwenwei's avatar
zhangwenwei committed
63
64
        return self._grid_size

65
66
67
68
69
70
71
72
73
74
75
76
77
    def __repr__(self):
        """str: Return a string that describes the module."""
        repr_str = self.__class__.__name__
        indent = ' ' * (len(repr_str) + 1)
        repr_str += f'(voxel_size={self._voxel_size},\n'
        repr_str += indent + 'point_cloud_range='
        repr_str += f'{self._point_cloud_range.tolist()},\n'
        repr_str += indent + f'max_num_points={self._max_num_points},\n'
        repr_str += indent + f'max_voxels={self._max_voxels},\n'
        repr_str += indent + f'grid_size={self._grid_size.tolist()}'
        repr_str += ')'
        return repr_str

zhangwenwei's avatar
zhangwenwei committed
78
79
80
81
82
83
84

def points_to_voxel(points,
                    voxel_size,
                    coors_range,
                    max_points=35,
                    reverse_index=True,
                    max_voxels=20000):
zhangwenwei's avatar
zhangwenwei committed
85
    """convert kitti points(N, >=3) to voxels.
zhangwenwei's avatar
zhangwenwei committed
86
87

    Args:
88
        points (np.ndarray): [N, ndim]. points[:, :3] contain xyz points and
zhangwenwei's avatar
zhangwenwei committed
89
            points[:, 3:] contain other information such as reflectivity.
zhangwenwei's avatar
zhangwenwei committed
90
        voxel_size (list, tuple, np.ndarray): [3] xyz, indicate voxel size
91
        coors_range (list[float | tuple[float] | ndarray]): Voxel range.
zhangwenwei's avatar
zhangwenwei committed
92
            format: xyzxyz, minmax
zhangwenwei's avatar
zhangwenwei committed
93
        max_points (int): Indicate maximum points contained in a voxel.
94
95
96
        reverse_index (bool): Whether return reversed coordinates.
            if points has xyz format and reverse_index is True, output
            coordinates will be zyx format, but points in features always
zhangwenwei's avatar
zhangwenwei committed
97
            xyz format.
98
99
        max_voxels (int): Maximum number of voxels this function creates.
            For second, 20000 is a good choice. Points should be shuffled for
zhangwenwei's avatar
zhangwenwei committed
100
            randomness before this function because max_voxels drops points.
zhangwenwei's avatar
zhangwenwei committed
101
102

    Returns:
zhangwenwei's avatar
zhangwenwei committed
103
104
105
106
        tuple[np.ndarray]:
            voxels: [M, max_points, ndim] float tensor. only contain points.
            coordinates: [M, 3] int32 tensor.
            num_points_per_voxel: [M] int32 tensor.
zhangwenwei's avatar
zhangwenwei committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
    """
    if not isinstance(voxel_size, np.ndarray):
        voxel_size = np.array(voxel_size, dtype=points.dtype)
    if not isinstance(coors_range, np.ndarray):
        coors_range = np.array(coors_range, dtype=points.dtype)
    voxelmap_shape = (coors_range[3:] - coors_range[:3]) / voxel_size
    voxelmap_shape = tuple(np.round(voxelmap_shape).astype(np.int32).tolist())
    if reverse_index:
        voxelmap_shape = voxelmap_shape[::-1]
    # don't create large array in jit(nopython=True) code.
    num_points_per_voxel = np.zeros(shape=(max_voxels, ), dtype=np.int32)
    coor_to_voxelidx = -np.ones(shape=voxelmap_shape, dtype=np.int32)
    voxels = np.zeros(
        shape=(max_voxels, max_points, points.shape[-1]), dtype=points.dtype)
    coors = np.zeros(shape=(max_voxels, 3), dtype=np.int32)
    if reverse_index:
        voxel_num = _points_to_voxel_reverse_kernel(
            points, voxel_size, coors_range, num_points_per_voxel,
            coor_to_voxelidx, voxels, coors, max_points, max_voxels)

    else:
        voxel_num = _points_to_voxel_kernel(points, voxel_size, coors_range,
                                            num_points_per_voxel,
                                            coor_to_voxelidx, voxels, coors,
                                            max_points, max_voxels)

    coors = coors[:voxel_num]
    voxels = voxels[:voxel_num]
    num_points_per_voxel = num_points_per_voxel[:voxel_num]

    return voxels, coors, num_points_per_voxel


@numba.jit(nopython=True)
def _points_to_voxel_reverse_kernel(points,
                                    voxel_size,
                                    coors_range,
                                    num_points_per_voxel,
                                    coor_to_voxelidx,
                                    voxels,
                                    coors,
                                    max_points=35,
                                    max_voxels=20000):
zhangwenwei's avatar
zhangwenwei committed
150
151
152
    """convert kitti points(N, >=3) to voxels.

    Args:
153
        points (np.ndarray): [N, ndim]. points[:, :3] contain xyz points and
zhangwenwei's avatar
zhangwenwei committed
154
            points[:, 3:] contain other information such as reflectivity.
155
156
        voxel_size (list, tuple, np.ndarray): [3] xyz, indicate voxel size
        coors_range (list[float | tuple[float] | ndarray]): Range of voxels.
zhangwenwei's avatar
zhangwenwei committed
157
158
            format: xyzxyz, minmax
        num_points_per_voxel (int): Number of points per voxel.
159
160
        coor_to_voxel_idx (np.ndarray): A voxel grid of shape (D, H, W),
            which has the same shape as the complete voxel map. It indicates
wangtai's avatar
wangtai committed
161
            the index of each corresponding voxel.
zhangwenwei's avatar
zhangwenwei committed
162
163
164
        voxels (np.ndarray): Created empty voxels.
        coors (np.ndarray): Created coordinates of each voxel.
        max_points (int): Indicate maximum points contained in a voxel.
165
166
        max_voxels (int): Maximum number of voxels this function create.
            for second, 20000 is a good choice. Points should be shuffled for
zhangwenwei's avatar
zhangwenwei committed
167
168
169
170
171
172
173
174
            randomness before this function because max_voxels drops points.

    Returns:
        tuple[np.ndarray]:
            voxels: Shape [M, max_points, ndim], only contain points.
            coordinates: Shape [M, 3].
            num_points_per_voxel: Shape [M].
    """
zhangwenwei's avatar
zhangwenwei committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    # put all computations to one loop.
    # we shouldn't create large array in main jit code, otherwise
    # reduce performance
    N = points.shape[0]
    # ndim = points.shape[1] - 1
    ndim = 3
    ndim_minus_1 = ndim - 1
    grid_size = (coors_range[3:] - coors_range[:3]) / voxel_size
    # np.round(grid_size)
    # grid_size = np.round(grid_size).astype(np.int64)(np.int32)
    grid_size = np.round(grid_size, 0, grid_size).astype(np.int32)
    coor = np.zeros(shape=(3, ), dtype=np.int32)
    voxel_num = 0
    failed = False
    for i in range(N):
        failed = False
        for j in range(ndim):
            c = np.floor((points[i, j] - coors_range[j]) / voxel_size[j])
            if c < 0 or c >= grid_size[j]:
                failed = True
                break
            coor[ndim_minus_1 - j] = c
        if failed:
            continue
        voxelidx = coor_to_voxelidx[coor[0], coor[1], coor[2]]
        if voxelidx == -1:
            voxelidx = voxel_num
            if voxel_num >= max_voxels:
203
                continue
zhangwenwei's avatar
zhangwenwei committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
            voxel_num += 1
            coor_to_voxelidx[coor[0], coor[1], coor[2]] = voxelidx
            coors[voxelidx] = coor
        num = num_points_per_voxel[voxelidx]
        if num < max_points:
            voxels[voxelidx, num] = points[i]
            num_points_per_voxel[voxelidx] += 1
    return voxel_num


@numba.jit(nopython=True)
def _points_to_voxel_kernel(points,
                            voxel_size,
                            coors_range,
                            num_points_per_voxel,
                            coor_to_voxelidx,
                            voxels,
                            coors,
                            max_points=35,
                            max_voxels=20000):
zhangwenwei's avatar
zhangwenwei committed
224
225
226
    """convert kitti points(N, >=3) to voxels.

    Args:
227
        points (np.ndarray): [N, ndim]. points[:, :3] contain xyz points and
zhangwenwei's avatar
zhangwenwei committed
228
            points[:, 3:] contain other information such as reflectivity.
wangtai's avatar
wangtai committed
229
        voxel_size (list, tuple, np.ndarray): [3] xyz, indicate voxel size.
230
        coors_range (list[float | tuple[float] | ndarray]): Range of voxels.
zhangwenwei's avatar
zhangwenwei committed
231
232
            format: xyzxyz, minmax
        num_points_per_voxel (int): Number of points per voxel.
233
234
        coor_to_voxel_idx (np.ndarray): A voxel grid of shape (D, H, W),
            which has the same shape as the complete voxel map. It indicates
wangtai's avatar
wangtai committed
235
            the index of each corresponding voxel.
zhangwenwei's avatar
zhangwenwei committed
236
237
238
        voxels (np.ndarray): Created empty voxels.
        coors (np.ndarray): Created coordinates of each voxel.
        max_points (int): Indicate maximum points contained in a voxel.
239
240
        max_voxels (int): Maximum number of voxels this function create.
            for second, 20000 is a good choice. Points should be shuffled for
zhangwenwei's avatar
zhangwenwei committed
241
242
243
244
245
246
247
248
            randomness before this function because max_voxels drops points.

    Returns:
        tuple[np.ndarray]:
            voxels: Shape [M, max_points, ndim], only contain points.
            coordinates: Shape [M, 3].
            num_points_per_voxel: Shape [M].
    """
zhangwenwei's avatar
zhangwenwei committed
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
    N = points.shape[0]
    # ndim = points.shape[1] - 1
    ndim = 3
    grid_size = (coors_range[3:] - coors_range[:3]) / voxel_size
    # grid_size = np.round(grid_size).astype(np.int64)(np.int32)
    grid_size = np.round(grid_size, 0, grid_size).astype(np.int32)

    # lower_bound = coors_range[:3]
    # upper_bound = coors_range[3:]
    coor = np.zeros(shape=(3, ), dtype=np.int32)
    voxel_num = 0
    failed = False
    for i in range(N):
        failed = False
        for j in range(ndim):
            c = np.floor((points[i, j] - coors_range[j]) / voxel_size[j])
            if c < 0 or c >= grid_size[j]:
                failed = True
                break
            coor[j] = c
        if failed:
            continue
        voxelidx = coor_to_voxelidx[coor[0], coor[1], coor[2]]
        if voxelidx == -1:
            voxelidx = voxel_num
            if voxel_num >= max_voxels:
275
                continue
zhangwenwei's avatar
zhangwenwei committed
276
277
278
279
280
281
282
283
            voxel_num += 1
            coor_to_voxelidx[coor[0], coor[1], coor[2]] = voxelidx
            coors[voxelidx] = coor
        num = num_points_per_voxel[voxelidx]
        if num < max_points:
            voxels[voxelidx, num] = points[i]
            num_points_per_voxel[voxelidx] += 1
    return voxel_num