backup / model /data_augmentation.py
MatchLab's picture
Upload folder using huggingface_hub
c94c8c9 verified
# ================================
# 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