lidar_box3d.py 8.4 KB
Newer Older
dingchang's avatar
dingchang committed
1
# Copyright (c) OpenMMLab. All rights reserved.
2
3
from typing import Optional, Tuple, Union

4
5
import numpy as np
import torch
6
from torch import Tensor
7

zhangshilong's avatar
zhangshilong committed
8
from mmdet3d.structures.points import BasePoints
9
from .base_box3d import BaseInstance3DBoxes
10
from .utils import rotation_3d_in_axis
11
12
13


class LiDARInstance3DBoxes(BaseInstance3DBoxes):
zhangwenwei's avatar
zhangwenwei committed
14
    """3D boxes of instances in LIDAR coordinates.
zhangwenwei's avatar
zhangwenwei committed
15

zhangwenwei's avatar
zhangwenwei committed
16
    Coordinates in LiDAR:
17

zhangwenwei's avatar
zhangwenwei committed
18
    .. code-block:: none
zhangwenwei's avatar
zhangwenwei committed
19

20
21
22
23
24
                                 up z    x front (yaw=0)
                                    ^   ^
                                    |  /
                                    | /
        (yaw=0.5*pi) left y <------ 0
zhangwenwei's avatar
zhangwenwei committed
25

wuyuefeng's avatar
wuyuefeng committed
26
    The relative coordinate of bottom center in a LiDAR box is (0.5, 0.5, 0),
27
28
29
    and the yaw is around the z axis, thus the rotation axis=2. The yaw is 0 at
    the positive direction of x axis, and increases from the positive direction
    of x to the positive direction of y.
30

31
    Attributes:
32
33
34
        tensor (Tensor): Float matrix with shape (N, box_dim).
        box_dim (int): Integer indicating the dimension of a box. Each row is
            (x, y, z, x_size, y_size, z_size, yaw, ...).
liyinhao's avatar
liyinhao committed
35
        with_yaw (bool): If True, the value of yaw will be set to 0 as minmax
zhangwenwei's avatar
zhangwenwei committed
36
            boxes.
37
    """
38
    YAW_AXIS = 2
39

zhangwenwei's avatar
zhangwenwei committed
40
    @property
41
42
43
    def corners(self) -> Tensor:
        """Convert boxes to corners in clockwise order, in the form of (x0y0z0,
        x0y0z1, x0y1z1, x0y1z0, x1y0z0, x1y0z1, x1y1z1, x1y1z0).
zhangwenwei's avatar
zhangwenwei committed
44
45

        .. code-block:: none
zhangwenwei's avatar
zhangwenwei committed
46

zhangwenwei's avatar
zhangwenwei committed
47
48
49
50
51
52
53
54
55
                                           up z
                            front x           ^
                                 /            |
                                /             |
                  (x1, y0, z1) + -----------  + (x1, y1, z1)
                              /|            / |
                             / |           /  |
               (x0, y0, z1) + ----------- +   + (x1, y1, z0)
                            |  /      .   |  /
56
                            | / origin    | /
57
            left y <------- + ----------- + (x0, y1, z0)
zhangwenwei's avatar
zhangwenwei committed
58
                (x0, y0, z0)
59
60
61

        Returns:
            Tensor: A tensor with 8 corners of each box in shape (N, 8, 3).
62
        """
63
64
65
        if self.tensor.numel() == 0:
            return torch.empty([0, 8, 3], device=self.tensor.device)

zhangwenwei's avatar
zhangwenwei committed
66
        dims = self.dims
67
        corners_norm = torch.from_numpy(
zhangwenwei's avatar
zhangwenwei committed
68
            np.stack(np.unravel_index(np.arange(8), [2] * 3), axis=1)).to(
69
70
71
                device=dims.device, dtype=dims.dtype)

        corners_norm = corners_norm[[0, 1, 3, 2, 4, 5, 7, 6]]
72
        # use relative origin (0.5, 0.5, 0)
zhangwenwei's avatar
zhangwenwei committed
73
74
        corners_norm = corners_norm - dims.new_tensor([0.5, 0.5, 0])
        corners = dims.view([-1, 1, 3]) * corners_norm.reshape([1, 8, 3])
75

zhangwenwei's avatar
zhangwenwei committed
76
        # rotate around z axis
77
78
        corners = rotation_3d_in_axis(
            corners, self.tensor[:, 6], axis=self.YAW_AXIS)
79
80
81
        corners += self.tensor[:, :3].view(-1, 1, 3)
        return corners

82
83
84
85
86
87
    def rotate(
        self,
        angle: Union[Tensor, np.ndarray, float],
        points: Optional[Union[Tensor, np.ndarray, BasePoints]] = None
    ) -> Union[Tuple[Tensor, Tensor], Tuple[np.ndarray, np.ndarray], Tuple[
            BasePoints, Tensor], None]:
88
89
        """Rotate boxes with points (optional) with the given angle or rotation
        matrix.
90
91

        Args:
92
93
94
            angle (Tensor or np.ndarray or float): Rotation angle or rotation
                matrix.
            points (Tensor or np.ndarray or :obj:`BasePoints`, optional):
95
                Points to rotate. Defaults to None.
wuyuefeng's avatar
wuyuefeng committed
96
97

        Returns:
98
99
100
            tuple or None: When ``points`` is None, the function returns None,
            otherwise it returns the rotated points and the rotation matrix
            ``rot_mat_T``.
101
        """
102
        if not isinstance(angle, Tensor):
103
            angle = self.tensor.new_tensor(angle)
104

105
106
107
108
        assert angle.shape == torch.Size([3, 3]) or angle.numel() == 1, \
            f'invalid rotation angle shape {angle.shape}'

        if angle.numel() == 1:
109
110
111
112
113
            self.tensor[:, 0:3], rot_mat_T = rotation_3d_in_axis(
                self.tensor[:, 0:3],
                angle,
                axis=self.YAW_AXIS,
                return_mat=True)
114
115
        else:
            rot_mat_T = angle
116
            rot_sin = rot_mat_T[0, 1]
117
118
            rot_cos = rot_mat_T[0, 0]
            angle = np.arctan2(rot_sin, rot_cos)
119
            self.tensor[:, 0:3] = self.tensor[:, 0:3] @ rot_mat_T
120
121
122

        self.tensor[:, 6] += angle

123
124
125
126
        if self.tensor.shape[1] == 9:
            # rotate velo vector
            self.tensor[:, 7:9] = self.tensor[:, 7:9] @ rot_mat_T[:2, :2]

wuyuefeng's avatar
wuyuefeng committed
127
        if points is not None:
128
            if isinstance(points, Tensor):
wuyuefeng's avatar
wuyuefeng committed
129
130
                points[:, :3] = points[:, :3] @ rot_mat_T
            elif isinstance(points, np.ndarray):
131
                rot_mat_T = rot_mat_T.cpu().numpy()
wuyuefeng's avatar
wuyuefeng committed
132
                points[:, :3] = np.dot(points[:, :3], rot_mat_T)
133
            elif isinstance(points, BasePoints):
134
                points.rotate(rot_mat_T)
wuyuefeng's avatar
wuyuefeng committed
135
136
137
138
            else:
                raise ValueError
            return points, rot_mat_T

139
140
141
142
143
    def flip(
        self,
        bev_direction: str = 'horizontal',
        points: Optional[Union[Tensor, np.ndarray, BasePoints]] = None
    ) -> Union[Tensor, np.ndarray, BasePoints, None]:
zhangwenwei's avatar
zhangwenwei committed
144
        """Flip the boxes in BEV along given BEV direction.
145

wuyuefeng's avatar
wuyuefeng committed
146
147
148
        In LIDAR coordinates, it flips the y (horizontal) or x (vertical) axis.

        Args:
149
150
151
            bev_direction (str): Direction by which to flip. Can be chosen from
                'horizontal' and 'vertical'. Defaults to 'horizontal'.
            points (Tensor or np.ndarray or :obj:`BasePoints`, optional):
152
                Points to flip. Defaults to None.
wuyuefeng's avatar
wuyuefeng committed
153
154

        Returns:
155
156
157
            Tensor or np.ndarray or :obj:`BasePoints` or None: When ``points``
            is None, the function returns None, otherwise it returns the
            flipped points.
158
        """
wuyuefeng's avatar
wuyuefeng committed
159
160
161
162
        assert bev_direction in ('horizontal', 'vertical')
        if bev_direction == 'horizontal':
            self.tensor[:, 1::7] = -self.tensor[:, 1::7]
            if self.with_yaw:
163
                self.tensor[:, 6] = -self.tensor[:, 6]
wuyuefeng's avatar
wuyuefeng committed
164
165
166
        elif bev_direction == 'vertical':
            self.tensor[:, 0::7] = -self.tensor[:, 0::7]
            if self.with_yaw:
167
                self.tensor[:, 6] = -self.tensor[:, 6] + np.pi
168

wuyuefeng's avatar
wuyuefeng committed
169
        if points is not None:
170
171
            assert isinstance(points, (Tensor, np.ndarray, BasePoints))
            if isinstance(points, (Tensor, np.ndarray)):
172
173
174
175
176
177
                if bev_direction == 'horizontal':
                    points[:, 1] = -points[:, 1]
                elif bev_direction == 'vertical':
                    points[:, 0] = -points[:, 0]
            elif isinstance(points, BasePoints):
                points.flip(bev_direction)
wuyuefeng's avatar
wuyuefeng committed
178
179
            return points

180
181
182
183
    def convert_to(self,
                   dst: int,
                   rt_mat: Optional[Union[Tensor, np.ndarray]] = None,
                   correct_yaw: bool = False) -> 'BaseInstance3DBoxes':
Wenwei Zhang's avatar
Wenwei Zhang committed
184
        """Convert self to ``dst`` mode.
185
186

        Args:
187
188
            dst (int): The target Box mode.
            rt_mat (Tensor or np.ndarray, optional): The rotation and
189
                translation matrix between different coordinates.
190
191
192
193
194
                Defaults to None. The conversion from ``src`` coordinates to
                ``dst`` coordinates usually comes along the change of sensors,
                e.g., from camera to LiDAR. This requires a transformation
                matrix.
            correct_yaw (bool): Whether to convert the yaw angle to the target
195
                coordinate. Defaults to False.
196

197
        Returns:
198
199
            :obj:`BaseInstance3DBoxes`: The converted box of the same type in
            the ``dst`` mode.
200
201
202
        """
        from .box_3d_mode import Box3DMode
        return Box3DMode.convert(
203
204
205
206
207
            box=self,
            src=Box3DMode.LIDAR,
            dst=dst,
            rt_mat=rt_mat,
            correct_yaw=correct_yaw)
zhangwenwei's avatar
zhangwenwei committed
208

209
210
211
    def enlarged_box(
            self, extra_width: Union[float, Tensor]) -> 'LiDARInstance3DBoxes':
        """Enlarge the length, width and height of boxes.
zhangwenwei's avatar
zhangwenwei committed
212
213

        Args:
214
            extra_width (float or Tensor): Extra width to enlarge the box.
zhangwenwei's avatar
zhangwenwei committed
215
216

        Returns:
zhangwenwei's avatar
zhangwenwei committed
217
            :obj:`LiDARInstance3DBoxes`: Enlarged boxes.
zhangwenwei's avatar
zhangwenwei committed
218
219
220
221
222
223
        """
        enlarged_boxes = self.tensor.clone()
        enlarged_boxes[:, 3:6] += extra_width * 2
        # bottom center z minus extra_width
        enlarged_boxes[:, 2] -= extra_width
        return self.new_box(enlarged_boxes)