File size: 11,680 Bytes
c94c8c9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 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 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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
# ================================
# Point Cloud Augmentation Functions (Single + Batched)
# ================================
import torch
import math
# -------------------------------
# Center the point cloud
# -------------------------------
def center_point_cloud(points: torch.Tensor):
"""
Center a point cloud by subtracting its centroid.
Args:
points:
(N, 3) or (B, N, 3) tensor
Returns:
centered_points:
same shape as input
center:
(1, 3) if input was (N, 3)
(B, 1, 3) if input was (B, N, 3)
"""
assert points.dim() in (2, 3) and points.size(-1) == 3, \
"Expected shape (N,3) or (B,N,3)"
if points.dim() == 2:
# (N,3)
center = points.mean(dim=0, keepdim=True) # (1,3)
centered = points - center # (N,3)
else:
# (B,N,3)
center = points.mean(dim=1, keepdim=True) # (B,1,3)
centered = points - center # (B,N,3)
return centered, center
# -------------------------------
# Random rotation helpers
# -------------------------------
def random_rotation_matrix(
batch_size: int | None = None,
device=None,
dtype=torch.float32,
):
"""
Generate random 3D rotation matrix/matrices.
If batch_size is None:
returns (3, 3) rotation matrix.
Else:
returns (B, 3, 3) rotation matrices.
Uniform sampling over SO(3) using independent yaw-pitch-roll.
(Not perfectly uniform on SO(3) but good enough for augmentation.)
"""
if device is None:
device = torch.device("cpu")
if batch_size is None:
angles = torch.rand(3, device=device, dtype=dtype) * 2 * math.pi # (3,)
cx, cy, cz = torch.cos(angles)
sx, sy, sz = torch.sin(angles)
rot_x = torch.tensor([
[1, 0, 0],
[0, cx, -sx],
[0, sx, cx],
], device=device, dtype=dtype)
rot_y = torch.tensor([
[ cy, 0, sy],
[ 0, 1, 0],
[-sy, 0, cy],
], device=device, dtype=dtype)
rot_z = torch.tensor([
[cz, -sz, 0],
[sz, cz, 0],
[ 0, 0, 1],
], device=device, dtype=dtype)
R = rot_z @ rot_y @ rot_x # (3,3)
return R
else:
# batch of rotations
angles = torch.rand(batch_size, 3, device=device, dtype=dtype) * 2 * math.pi # (B,3)
cx, cy, cz = torch.cos(angles[:, 0]), torch.cos(angles[:, 1]), torch.cos(angles[:, 2])
sx, sy, sz = torch.sin(angles[:, 0]), torch.sin(angles[:, 1]), torch.sin(angles[:, 2])
# build batched rotation matrices
R = torch.zeros(batch_size, 3, 3, device=device, dtype=dtype)
# RotX
R_x = torch.zeros_like(R)
R_x[:, 0, 0] = 1
R_x[:, 1, 1] = cx
R_x[:, 1, 2] = -sx
R_x[:, 2, 1] = sx
R_x[:, 2, 2] = cx
# RotY
R_y = torch.zeros_like(R)
R_y[:, 0, 0] = cy
R_y[:, 0, 2] = sy
R_y[:, 1, 1] = 1
R_y[:, 2, 0] = -sy
R_y[:, 2, 2] = cy
# RotZ
R_z = torch.zeros_like(R)
R_z[:, 0, 0] = cz
R_z[:, 0, 1] = -sz
R_z[:, 1, 0] = sz
R_z[:, 1, 1] = cz
R_z[:, 2, 2] = 1
# Z * Y * X, batched
# (B,3,3) @ (B,3,3) -> (B,3,3)
R = torch.bmm(R_z, torch.bmm(R_y, R_x))
return R
# -------------------------------
# Full 3D rotation
# -------------------------------
def rotate_point_cloud(points: torch.Tensor, R: torch.Tensor = None):
"""
Rotate a point cloud with optional rotation matrix.
Args:
points:
(N,3) or (B,N,3)
R:
If points is (N,3):
None or (3,3)
If points is (B,N,3):
None, (3,3) shared, or (B,3,3) per-cloud.
Returns:
rotated_points: same shape as points
R: (3,3) or (B,3,3) rotation used
"""
assert points.dim() in (2, 3) and points.size(-1) == 3, \
"Expected shape (N,3) or (B,N,3)"
device, dtype = points.device, points.dtype
if points.dim() == 2:
# (N,3)
if R is None:
R = random_rotation_matrix(device=device, dtype=dtype) # (3,3)
assert R.shape == (3, 3), "R must be (3,3) for single cloud"
rotated = points @ R.T # (N,3)
return rotated, R
else:
# (B,N,3)
B, N, _ = points.shape
if R is None:
R = random_rotation_matrix(batch_size=B, device=device, dtype=dtype) # (B,3,3)
elif R.dim() == 2:
# broadcast shared rotation to all clouds
assert R.shape == (3, 3), "R must be (3,3) or (B,3,3)"
R = R.unsqueeze(0).expand(B, -1, -1) # (B,3,3)
else:
assert R.shape == (B, 3, 3), "R must be (3,3) or (B,3,3)"
# rotated[b, n, :] = points[b, n, :] @ R[b].T
rotated = torch.einsum("bnc,bfc->bnf", points, R.transpose(1, 2)) # (B,N,3)
return rotated, R
# -------------------------------
# Rotation around z-axis only
# -------------------------------
def rotate_point_cloud_z(points: torch.Tensor, angle=None):
"""
Rotate point cloud around z-axis only.
Args:
points:
(N,3) or (B,N,3)
angle:
If points is (N,3): float or None (radians).
- None: sample random in [0, 2π).
If points is (B,N,3): tensor of shape (B,) or None.
- None: random angle per cloud in [0, 2π).
Returns:
rotated_points: same shape as points
Rz:
(3,3) for single cloud
(B,3,3) for batched
"""
assert points.dim() in (2, 3) and points.size(-1) == 3, \
"Expected shape (N,3) or (B,N,3)"
device, dtype = points.device, points.dtype
if points.dim() == 2:
# single cloud (N,3)
if angle is None:
angle = torch.rand(1, device=device, dtype=dtype).item() * 2 * math.pi
c, s = math.cos(angle), math.sin(angle)
Rz = torch.tensor([
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
], device=device, dtype=dtype)
rotated = points @ Rz.T # (N,3)
return rotated, Rz
else:
# batched (B,N,3)
B, N, _ = points.shape
if angle is None:
angle = torch.rand(B, device=device, dtype=dtype) * 2 * math.pi # (B,)
elif not torch.is_tensor(angle):
# scalar -> shared angle
angle = torch.full((B,), float(angle), device=device, dtype=dtype)
c = torch.cos(angle) # (B,)
s = torch.sin(angle) # (B,)
Rz = torch.zeros(B, 3, 3, device=device, dtype=dtype)
Rz[:, 0, 0] = c
Rz[:, 0, 1] = -s
Rz[:, 1, 0] = s
Rz[:, 1, 1] = c
Rz[:, 2, 2] = 1
rotated = torch.einsum("bnc,bfc->bnf", points, Rz.transpose(1, 2)) # (B,N,3)
return rotated, Rz
# -------------------------------
# Translation
# -------------------------------
def translate_point_cloud(points: torch.Tensor,
t: torch.Tensor = None,
scale: float = 0.05):
"""
Translate a point cloud.
Args:
points:
(N,3) or (B,N,3)
t:
Translation vector.
For (N,3): None, (3,), or (1,3).
For (B,N,3): None, (3,), (1,3), or (B,3).
scale:
Magnitude for random translation when t is None.
Returns:
translated_points: same shape as points
t_out:
(1,3) for single cloud
(B,1,3) for batched clouds
"""
assert points.dim() in (2, 3) and points.size(-1) == 3, \
"Expected shape (N,3) or (B,N,3)"
device, dtype = points.device, points.dtype
if points.dim() == 2:
# (N,3)
if t is None:
t = (torch.rand(1, 3, device=device, dtype=dtype) * 2 - 1) * scale # (1,3)
t = t.view(1, 3)
translated = points + t # (N,3)
return translated, t
else:
# (B,N,3)
B, N, _ = points.shape
if t is None:
t = (torch.rand(B, 3, device=device, dtype=dtype) * 2 - 1) * scale # (B,3)
else:
if t.dim() == 1:
assert t.shape[0] == 3, "t must be (3,), (1,3), or (B,3)"
t = t.view(1, 3).expand(B, -1) # (B,3)
elif t.dim() == 2:
if t.shape[0] == 1:
# (1,3) -> broadcast
t = t.expand(B, -1) # (B,3)
else:
assert t.shape == (B, 3), "t must be (3,), (1,3), or (B,3)"
else:
raise ValueError("t must have shape (3,), (1,3), or (B,3)")
t_out = t.view(B, 1, 3) # (B,1,3)
translated = points + t_out # (B,N,3)
return translated, t_out
# -------------------------------
# Scaling
# -------------------------------
def scale_point_cloud(points: torch.Tensor,
s: torch.Tensor = None,
min_s: float = 0.9,
max_s: float = 1.1):
"""
Uniformly scale a point cloud.
Args:
points:
(N,3) or (B,N,3)
s:
If points is (N,3):
None or scalar tensor (or shape (1,))
If points is (B,N,3):
None, scalar, or (B,) for per-cloud scaling.
min_s, max_s:
Range for random scaling when s is None.
Returns:
scaled_points: same shape as points
s_vec:
(1,3) if single cloud
(B,1,3) if batched
"""
assert points.dim() in (2, 3) and points.size(-1) == 3, \
"Expected shape (N,3) or (B,N,3)"
device, dtype = points.device, points.dtype
if points.dim() == 2:
# (N,3)
if s is None:
s = torch.empty(1, device=device, dtype=dtype).uniform_(min_s, max_s) # (1,)
if torch.is_tensor(s):
s = s.view(1, 1) # scalar
else:
s = torch.tensor([[float(s)]], device=device, dtype=dtype)
s_vec = s.repeat(1, 3) # (1,3)
scaled = points * s # (N,3)
return scaled, s_vec
else:
# (B,N,3)
B, N, _ = points.shape
if s is None:
s = torch.empty(B, device=device, dtype=dtype).uniform_(min_s, max_s) # (B,)
elif not torch.is_tensor(s):
s = torch.full((B,), float(s), device=device, dtype=dtype)
assert s.shape == (B,), "For batched input, s must be scalar or shape (B,)"
s = s.view(B, 1, 1) # (B,1,1)
s_vec = s.repeat(1, 1, 3) # (B,1,3)
scaled = points * s # (B,N,3)
return scaled, s_vec
# -------------------------------
# Example: Full augmentation pipeline
# -------------------------------
def augment_point_cloud(points: torch.Tensor):
"""
Example augmentation pipeline:
center -> random rotate -> random scale -> random translate
Works for:
(N,3) or (B,N,3)
Returns:
aug_points: same shape as input
info: dict with keys center, R, s, t
center: (1,3) or (B,1,3)
R: (3,3) or (B,3,3)
s: (1,3) or (B,1,3)
t: (1,3) or (B,1,3)
"""
pts, center = center_point_cloud(points)
pts, R = rotate_point_cloud(pts)
pts, s = scale_point_cloud(pts, min_s=0.8, max_s=1.2)
pts, t = translate_point_cloud(pts, scale=0.1)
info = dict(center=center, R=R, s=s, t=t)
return pts, info
|