π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(geometry): add opt-in check_rotation to camtoworld/worldtocam Rt (#4817)
Tanmay Verma28414a914416
diff --git a/changelog.d/4817.added.md b/changelog.d/4817.added.mdnew file mode 100644index 000000000..00c79e2bd--- /dev/null+++ b/changelog.d/4817.added.md@@ -0,0 +1 @@+`camtoworld_to_worldtocam_Rt` and `worldtocam_to_camtoworld_Rt` accept `check_rotation=True`, which raises `ValueError` when `R` is not a rotation matrix instead of silently returning a wrong pose.diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 5f09ab435..537046596 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -2695,7 +2695,37 @@ def camtoworld_vision_to_graphics_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[return matrix4x4_to_Rt(mat4x4)-def camtoworld_to_worldtocam_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+def _check_is_rotation(R: torch.Tensor, fn_name: str) -> None:+ # Opt-in validation behind check_rotation=True; the default path stays unchecked.+ # det has no half or integer kernels, so the check runs in float32 unless R is already float64.+ # The tolerance follows R's own precision: 100 eps, but 16 eps for float16/bfloat16, where 100 eps+ # (0.78 in bfloat16) would accept a 50% shear. Every tolerance stays below 1/3, so an R that passes+ # the orthogonality test is non-singular and det(R) <= 0 can only mean a reflection.+ # eps literals rather than torch.finfo, which TorchScript cannot compile.+ work = R if R.dtype == torch.float64 else R.to(torch.float32)+ if R.dtype == torch.float64:+ tol = 100.0 * 2.0**-52+ elif R.dtype == torch.bfloat16:+ tol = 16.0 * 2.0**-7+ elif R.dtype == torch.float16:+ tol = 16.0 * 2.0**-10+ else: # float32, and integer input checked in float32+ tol = 100.0 * 2.0**-23+ eye = torch.eye(3, device=R.device, dtype=work.dtype)+ ortho_err = (work @ work.transpose(-2, -1) - eye).abs().amax(dim=(-2, -1))+ # "not all within" rather than "any above", so that a NaN entry fails the check.+ if not bool((ortho_err <= tol).all()):+ raise ValueError(+ f"{fn_name}: R is not a rotation matrix: max|R @ R^T - I| = {float(ortho_err.max())} "+ f"is not within the tolerance {tol}."+ )+ if bool((torch.linalg.det(work) <= 0).any()):+ raise ValueError(f"{fn_name}: R is a reflection (det(R) < 0), not a rotation matrix.")+++def camtoworld_to_worldtocam_Rt(+ R: torch.Tensor, t: torch.Tensor, check_rotation: bool = False+) -> tuple[torch.Tensor, torch.Tensor]:r"""Convert camtoworld to worldtocam frame used in Colmap.See@@ -2720,11 +2750,12 @@ def camtoworld_to_worldtocam_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch- the shapes are :math:`(B, 3, 3)` and :math:`(B, 3, 1)`.. warning::- ``R`` is **assumed** to be a rotation and this is never checked, so for- a non-orthogonal ``R`` the result is a transpose and not an inverse,- silently: ``R = [[1, 0.5, 0], [0, 1, 0], [0, 0, 2]]`` gives- ``max|M_inv @ M - I| = 3.0``. Tracked in- `#3961 <https://github.com/kornia/kornia/issues/3961>`_.+ ``R`` is **assumed** to be a rotation and by default this is not+ checked, so for a non-orthogonal ``R`` the result is a transpose and+ not an inverse, silently: ``R = [[1, 0.5, 0], [0, 1, 0], [0, 0, 2]]``+ gives ``max|M_inv @ M - I| = 3.0``. Pass ``check_rotation=True`` to+ raise a ``ValueError`` instead, which also rejects reflections+ (``det(R) < 0``)... warning::The batch sizes of ``R`` and ``t`` are not checked: ``t`` is broadcast@@ -2736,6 +2767,10 @@ def camtoworld_to_worldtocam_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torchArgs:R: Rotation matrix, :math:`(B, 3, 3).`t: Translation matrix :math:`(B, 3, 1)`.+ check_rotation: if ``True``, raise ``ValueError`` unless every ``R``+ is a rotation: ``max|R @ R^T - I|`` within 100 eps of the dtype of+ ``R`` (16 eps for float16 and bfloat16) and ``det(R) > 0``.+ Defaults to ``False`` (unchecked).Returns:Rinv: Rotation matrix, :math:`(B, 3, 3).`@@ -2754,13 +2789,18 @@ def camtoworld_to_worldtocam_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torchKORNIA_CHECK_SHAPE(R, ["B", "3", "3"])KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])+ if check_rotation:+ _check_is_rotation(R, "camtoworld_to_worldtocam_Rt")+R_inv = R.transpose(1, 2)new_t: torch.Tensor = -R_inv @ treturn (R_inv, new_t)-def worldtocam_to_camtoworld_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+def worldtocam_to_camtoworld_Rt(+ R: torch.Tensor, t: torch.Tensor, check_rotation: bool = False+) -> tuple[torch.Tensor, torch.Tensor]:r"""Convert worldtocam frame used in Colmap to camtoworld.Convention:@@ -2780,6 +2820,10 @@ def worldtocam_to_camtoworld_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torchArgs:R: Rotation matrix, :math:`(B, 3, 3).`t: Translation matrix :math:`(B, 3, 1)`.+ check_rotation: if ``True``, raise ``ValueError`` unless every ``R``+ is a rotation: ``max|R @ R^T - I|`` within 100 eps of the dtype of+ ``R`` (16 eps for float16 and bfloat16) and ``det(R) > 0``.+ Defaults to ``False`` (unchecked).Returns:Rinv: Rotation matrix, :math:`(B, 3, 3).`@@ -2798,6 +2842,9 @@ def worldtocam_to_camtoworld_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torchKORNIA_CHECK_SHAPE(R, ["B", "3", "3"])KORNIA_CHECK_SHAPE(t, ["B", "3", "1"])+ if check_rotation:+ _check_is_rotation(R, "worldtocam_to_camtoworld_Rt")+R_inv = R.transpose(1, 2)new_t: torch.Tensor = -R_inv @ tdiff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex 167bb5845..7f1c2c38c 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -454,7 +454,7 @@ def _homography_sizes(op_name: str) -> tuple[tuple[int, ...], tuple[int, ...]]:# and TestCamtoworldRtToPoseRt -- one definition and one materialisation site instead of nine# copies that would have to be edited in lockstep, and it is what makes those classes'# "same asymmetric pose as TestRt2Extrinsics" cross-references true by construction.-# The kornia#3961 wart deliberately uses a DIFFERENT, non-orthogonal rotation and stays out of this.+# The unchecked-default pin (kornia#3961) deliberately uses a DIFFERENT, non-orthogonal rotation._ASYMMETRIC_R = [[[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]]_ASYMMETRIC_T = [[[1.0], [2.0], [3.0]]]@@ -4898,7 +4898,7 @@ class TestCamtoworldGraphicsToVision(BaseTester):# documentation -- and applying it twice, or once in each direction, returns the input# (value-exactly for this pose, whose entries keep every product exact). So nothing can# detect that a pose was already converted. The pose pair holds because R is a rotation;- # test_wart_non_orthogonal_rotation_is_transposed_not_inverted_3961 pins the other case.+ # test_convention_unchecked_default_transposes_non_orthogonal_rotation_3961 pins the other case._skip_if_dtype_unavailable(device, dtype)rotation, translation = _asymmetric_pose(device, dtype)pose = (Rt_to_matrix4x4(rotation, translation),) if forward_name.endswith("4x4") else (rotation, translation)@@ -5019,22 +5019,14 @@ class TestCamtoworldRtToPoseRt(BaseTester):# _assert_strictly_batched helper._assert_strictly_batched(op_name, shapes, device)- def test_wart_non_orthogonal_rotation_is_transposed_not_inverted_3961(self, device, dtype):- # Wart pin for kornia#3961: R is ASSUMED orthogonal and the assumption is never checked, so- # for any other matrix the result is a transpose that is not an inverse -- silently, with no- # error and no warning. Three cells, each a different observable of the same root:+ def test_convention_unchecked_default_transposes_non_orthogonal_rotation_3961(self, device, dtype):+ # Convention pin (kornia#3961): R is ASSUMED to be a rotation and, with the default+ # check_rotation=False, this is not checked, so for any other matrix the result is a transpose+ # that is not an inverse -- silently. The call below deliberately omits the argument; the+ # opt-in validation is covered by the test_check_rotation_* tests. Three observables:# (1) the returned rotation is exactly R.T even though R.T is not R^-1 here;- # (2) composing the two 4x4 matrices misses the identity by 3.0, i.e. not by a rounding- # amount -- this is what a caller notices as "my poses drifted";- # (3) even the round trip breaks, the translation coming back 9.0 away from the input;- # cell (3) is kept separate from (2) because a fix that validated only the rotation- # would leave the translation error in place for a caller who ignores the raise.- # There is deliberately NO companion strict xfail: the intended behavior is undecided -- a- # fix could raise on a non-orthogonal R, or fall back to a true inverse -- and an- # assertion-shaped xfail could express only one of those and would stay silently XFAIL if- # the other were chosen. Same shape as the #3959 and #3957 wart pins in this file.- # If any cell fails, #3961 was (partly) fixed -- remove this pin. NOT a contract that a- # non-orthogonal R must keep producing these numbers.+ # (2) composing the two 4x4 matrices misses the identity by 3.0, not by a rounding amount;+ # (3) the round trip returns the translation 9.0 away from the input.# R = [[1, 0.5, 0], [0, 1, 0], [0, 0, 2]] has det = 2 and dyadic entries, so every literal# below is exact in every dtype.# Snippet used to generate expected (torch only, executed on cpu):@@ -5055,12 +5047,133 @@ class TestCamtoworldRtToPoseRt(BaseTester):inverted_t, torch.tensor([[[-1.0], [-2.5], [-6.0]]], device=device, dtype=dtype), atol=0.0, rtol=0.0)assert (composed - torch.eye(4, device=device, dtype=dtype)).abs().max().item() == 3.0, (- "kornia#3961: a non-orthogonal rotation no longer misses the identity by 3.0"+ "kornia#3961: the unchecked default no longer misses the identity by 3.0")self.assert_close(round_trip_t, torch.tensor([[[2.25], [2.5], [12.0]]], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ def test_check_rotation_accepts_rotation_unchanged(self, fn, device, dtype):+ # kornia#3961: with check_rotation=True a genuine rotation passes, and the result is+ # bitwise the unchecked one -- the flag only validates, it never changes the output.+ _skip_if_dtype_unavailable(device, dtype)+ rotation, translation = _asymmetric_pose(device, dtype)+ expected_R, expected_t = fn(rotation, translation)+ out_R, out_t = fn(rotation, translation, check_rotation=True)+ self.assert_close(out_R, expected_R, atol=0.0, rtol=0.0)+ self.assert_close(out_t, expected_t, atol=0.0, rtol=0.0)++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ def test_check_rotation_accepts_rounding_error(self, fn, device, dtype):+ # Rotations carrying only their dtype's rounding must pass. Over 10,000 random rotations the+ # worst max|R @ R^T - I| measured 8 eps (float32), 9 eps (float64) and 0.8 eps+ # (float16/bfloat16, built in float32 and cast), against a tolerance of 100 eps (16 eps for+ # float16/bfloat16).+ _skip_if_dtype_unavailable(device, dtype)+ build_dtype = dtype if dtype in (torch.float32, torch.float64) else torch.float32+ generator = torch.Generator().manual_seed(0)+ axis_angle = torch.randn(64, 3, generator=generator, dtype=build_dtype) * 3+ rotation = axis_angle_to_rotation_matrix(axis_angle.to(device)).to(dtype)+ translation = torch.zeros(64, 3, 1, device=device, dtype=dtype)+ fn(rotation, translation, check_rotation=True) # must not raise++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ def test_check_rotation_rejects_non_orthogonal(self, fn, device, dtype):+ # The issue's matrix (det = 2), exact in every dtype.+ _skip_if_dtype_unavailable(device, dtype)+ rotation = torch.tensor([[[1.0, 0.5, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 2.0]]], device=device, dtype=dtype)+ translation = torch.tensor([[[1.0], [2.0], [3.0]]], device=device, dtype=dtype)+ with pytest.raises(ValueError, match="not a rotation matrix"):+ fn(rotation, translation, check_rotation=True)++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ def test_check_rotation_rejects_reflection(self, fn, device, dtype):+ # A mirror is orthogonal (R @ R^T = I) but det = -1, so only the determinant test catches it.+ _skip_if_dtype_unavailable(device, dtype)+ rotation = torch.tensor([[[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ translation = torch.zeros(1, 3, 1, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="reflection"):+ fn(rotation, translation, check_rotation=True)++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ def test_check_rotation_rejects_one_bad_matrix_in_batch(self, fn, device, dtype):+ # One bad matrix among good ones is enough to raise.+ _skip_if_dtype_unavailable(device, dtype)+ good, _ = _asymmetric_pose(device, dtype)+ bad = torch.tensor([[[1.0, 0.5, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 2.0]]], device=device, dtype=dtype)+ rotation = torch.cat([good, bad, good])+ translation = torch.zeros(3, 3, 1, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="not a rotation matrix"):+ fn(rotation, translation, check_rotation=True)++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ def test_check_rotation_integer_input(self, fn, device):+ # Integer R is accepted by these functions; the check converts it to float32 instead of crashing+ # (torch.finfo and det have no integer support). A permutation is an exact integer rotation+ # and passes unchanged; 2 * I is exact there and is not a rotation.+ permutation = torch.tensor(_ASYMMETRIC_R, device=device).to(torch.int64)+ translation = torch.tensor(_ASYMMETRIC_T, device=device).to(torch.int64)+ out_R, out_t = fn(permutation, translation, check_rotation=True)+ expected_R, expected_t = fn(permutation, translation)+ assert out_R.dtype == torch.int64+ assert torch.equal(out_R, expected_R) and torch.equal(out_t, expected_t)+ rotation = 2 * torch.eye(3, device=device, dtype=torch.int64)[None]+ with pytest.raises(ValueError, match="not a rotation matrix"):+ fn(rotation, translation, check_rotation=True)++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ @pytest.mark.parametrize(+ "matrix",+ [+ [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.5]], # scale: R @ R^T - I is NEGATIVE (-0.75)+ [[1.0, 0.5, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], # shear with det = 1+ [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.5, 0.125]], # det = 0.125 > 0+ ],+ ids=["scale", "shear", "near-singular"],+ )+ def test_check_rotation_rejects_non_rotation_with_positive_det(self, fn, matrix, device, dtype):+ # Non-rotations whose determinant is positive, so only the orthogonality test can reject them.+ # Every entry is dyadic, so the matrices are exact in every dtype.+ _skip_if_dtype_unavailable(device, dtype)+ rotation = torch.tensor([matrix], device=device, dtype=dtype)+ translation = torch.zeros(1, 3, 1, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="not a rotation matrix"):+ fn(rotation, translation, check_rotation=True)++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ def test_check_rotation_tolerance_bracket(self, fn, device, dtype):+ # diag(1, 1, 1 + k * eps) deviates from a rotation by max|R @ R^T - I| = 2k eps + (k eps)^2, exact+ # in every dtype. The tolerance is 100 eps (16 eps for float16/bfloat16): a deviation of about+ # half of it passes, one of about 1.5 times it raises.+ _skip_if_dtype_unavailable(device, dtype)+ eps = torch.finfo(dtype).eps+ k_pass, k_fail = (4, 12) if dtype in (torch.float16, torch.bfloat16) else (25, 80)+ translation = torch.zeros(1, 3, 1, device=device, dtype=dtype)+ passing = torch.diag(torch.tensor([1.0, 1.0, 1.0 + k_pass * eps], device=device, dtype=dtype))[None]+ failing = torch.diag(torch.tensor([1.0, 1.0, 1.0 + k_fail * eps], device=device, dtype=dtype))[None]+ fn(passing, translation, check_rotation=True) # must not raise+ with pytest.raises(ValueError, match="not a rotation matrix"):+ fn(failing, translation, check_rotation=True)++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ def test_check_rotation_rejects_nan(self, fn, device, dtype):+ # A NaN entry is not a rotation: the check must raise rather than let it through.+ _skip_if_dtype_unavailable(device, dtype)+ rotation, translation = _asymmetric_pose(device, dtype)+ rotation[0, 0, 0] = float("nan")+ with pytest.raises(ValueError, match="not a rotation matrix"):+ fn(rotation, translation, check_rotation=True)++ @pytest.mark.parametrize("fn", [camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt])+ def test_check_rotation_scripts(self, fn, device, dtype):+ # Both functions stay scriptable with the new argument, checked path included.+ _skip_if_dtype_unavailable(device, dtype)+ rotation, translation = _asymmetric_pose(device, dtype)+ scripted = torch.jit.script(fn)+ for actual, expected in zip(scripted(rotation, translation, True), fn(rotation, translation)):+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)+class TestCARKitToColmap(BaseTester):def test_everything(self, device, dtype):