mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-11-24 00:26:08 +08:00
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 <yibrenth@gmail.com> Co-authored-by: Matias Turkulainen <30566358+maturk@users.noreply.github.com>
This commit is contained in:
1 file changed
+15
-10
@@ -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":
|
||||
|
||||
Reference in new issue
Block a user