From 12195f034f51e229bb9bef3b99925d48979b4a6f Mon Sep 17 00:00:00 2001 From: "J.Y" <132313008+jb-ye@users.noreply.github.com> Date: Fri, 22 Mar 2024 02:07:07 -0400 Subject: [PATCH] Fix rotation_matrix for opposite float32 vectors (#3011) * Fix rotation_matrix for opposite float32 vectors * Reformulate rotation_matrix() without division => drop unnecessary `eps` * Rename `rotation_matrix()` => `rotation_matrix_between()` --------- Co-authored-by: Brent Yi Co-authored-by: Matias Turkulainen <30566358+maturk@users.noreply.github.com> --- nerfstudio/cameras/camera_utils.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/nerfstudio/cameras/camera_utils.py b/nerfstudio/cameras/camera_utils.py index 9c1ee0220..185a852a2 100644 --- a/nerfstudio/cameras/camera_utils.py +++ b/nerfstudio/cameras/camera_utils.py @@ -446,7 +446,7 @@ def radial_and_tangential_undistort( return torch.stack([x, y], dim=-1) -def rotation_matrix(a: Float[Tensor, "3"], b: Float[Tensor, "3"]) -> Float[Tensor, "3 3"]: +def rotation_matrix_between(a: Float[Tensor, "3"], b: Float[Tensor, "3"]) -> Float[Tensor, "3 3"]: """Compute the rotation matrix that rotates vector a to vector b. Args: @@ -457,13 +457,15 @@ def rotation_matrix(a: Float[Tensor, "3"], b: Float[Tensor, "3"]) -> Float[Tenso """ a = a / torch.linalg.norm(a) b = b / torch.linalg.norm(b) - v = torch.cross(a, b) - c = torch.dot(a, b) - # If vectors are exactly opposite, we add a little noise to one of them - if c < -1 + 1e-8: - eps = (torch.rand(3) - 0.5) * 0.01 - return rotation_matrix(a + eps, b) - s = torch.linalg.norm(v) + v = torch.linalg.cross(a, b) # Axis of rotation. + + # Handle cases where `a` and `b` are parallel. + eps = 1e-6 + if torch.sum(torch.abs(v)) < eps: + x = torch.tensor([1.0, 0, 0]) if abs(a[0]) < eps else torch.tensor([0, 1.0, 0]) + v = torch.linalg.cross(a, x) + + v = v / torch.linalg.norm(v) skew_sym_mat = torch.Tensor( [ [0, -v[2], v[1]], @@ -471,7 +473,10 @@ def rotation_matrix(a: Float[Tensor, "3"], b: Float[Tensor, "3"]) -> Float[Tenso [-v[1], v[0], 0], ] ) - return torch.eye(3) + skew_sym_mat + skew_sym_mat @ skew_sym_mat * ((1 - c) / (s**2 + 1e-8)) + theta = torch.acos(torch.clip(torch.dot(a, b), -1, 1)) + + # Rodrigues rotation formula. https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula + return torch.eye(3) + torch.sin(theta) * skew_sym_mat + (1 - torch.cos(theta)) * (skew_sym_mat @ skew_sym_mat) def focus_of_attention(poses: Float[Tensor, "*num_poses 4 4"], initial_focus: Float[Tensor, "3"]) -> Float[Tensor, "3"]: @@ -609,7 +614,7 @@ def auto_orient_and_center_poses( # re-normalize up = up / torch.linalg.norm(up) - rotation = rotation_matrix(up, torch.Tensor([0, 0, 1])) + rotation = rotation_matrix_between(up, torch.Tensor([0, 0, 1])) transform = torch.cat([rotation, rotation @ -translation[..., None]], dim=-1) oriented_poses = transform @ poses elif method == "none":