π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(geometry): add opt-in check_rotation to rotation_matrix_to_axis_angle/quaternion (#4840)
Miral Amin6888c0398435
diff --git a/changelog.d/4792.fixed.md b/changelog.d/4792.fixed.mdindex 082e3e3e5..feda126b6 100644--- a/changelog.d/4792.fixed.md+++ b/changelog.d/4792.fixed.md@@ -1 +1 @@-`kornia.geometry.conversions` docstrings no longer claim that the deprecated aliases break `-W error::DeprecationWarning` (fixed in #3956), state the float64 axis-angle round-trip accuracy correctly (roundoff, about `2e-10` on the low-angle branch), and document two defects: `rotation_matrix_to_axis_angle` returns the identity for a reflection (#4773), and `Rt_to_matrix4x4` and `camtoworld_to_worldtocam_Rt` handle an `R`/`t` batch-size mismatch differently (#4774).+`kornia.geometry.conversions` docstrings no longer claim that the deprecated aliases break `-W error::DeprecationWarning` (fixed in #3956), state the float64 axis-angle round-trip accuracy correctly (roundoff, about `2e-10` on the low-angle branch), and document a defect: `Rt_to_matrix4x4` and `camtoworld_to_worldtocam_Rt` handle an `R`/`t` batch-size mismatch differently (#4774).diff --git a/changelog.d/4840.added.md b/changelog.d/4840.added.mdnew file mode 100644index 000000000..88fb51c22--- /dev/null+++ b/changelog.d/4840.added.md@@ -0,0 +1,7 @@+`rotation_matrix_to_axis_angle`, `rotation_matrix_to_quaternion`, `Quaternion.from_matrix`,+`So3.from_matrix` and `Se3.from_matrix` take `check_rotation` (default `False`). With+`check_rotation=True` they raise a `ValueError` unless every input is a rotation:+`max|R @ R^T - I|` within 100 eps of the input dtype (16 eps for float16 and bfloat16) and+`det(R) > 0`. Without it the behaviour is unchanged, so a reflection such as `diag(-1, 1, 1)`+is still reported as the identity rotation `[0., 0., 0.]`, and `Se3.from_matrix` still accepts+a reflection block. (#4773)diff --git a/changelog.d/4976.added.md b/changelog.d/4976.added.mdindex 90405fff2..e0060b982 100644--- a/changelog.d/4976.added.md+++ b/changelog.d/4976.added.md@@ -1 +1 @@-Convention blocks for `Quaternion`, `average_quaternions` and `So3` (storage, product order, principal `log`, Jacobian sides), a "Rotations and rigid motions" section on the Conventions & Pitfalls page with the scipy / Sophus / Eigen mapping, and 19 convention and wart pins; the warts are documented and linked (#3950, #3952, #3953, #4773, #4923, #4942), not fixed.+Convention blocks for `Quaternion`, `average_quaternions` and `So3` (storage, product order, principal `log`, Jacobian sides), a "Rotations and rigid motions" section on the Conventions & Pitfalls page with the scipy / Sophus / Eigen mapping, and 19 convention and wart pins; the warts are documented and linked (#3950, #3952, #3953, #4923, #4942), not fixed.diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 537046596..761e32049 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -504,7 +504,7 @@ def angle_axis_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor: #return axis_angle_to_rotation_matrix(axis_angle)-def rotation_matrix_to_axis_angle(rotation_matrix: torch.Tensor) -> torch.Tensor:+def rotation_matrix_to_axis_angle(rotation_matrix: torch.Tensor, check_rotation: bool = False) -> torch.Tensor:r"""Convert 3x3 rotation matrix to Rodrigues vector in radians.Convention:@@ -520,19 +520,24 @@ def rotation_matrix_to_axis_angle(rotation_matrix: torch.Tensor) -> torch.Tensoris accurate to roundoff, except that the low-angle Taylor branch(``theta <= 1e-3``) leaves a truncation error of up to about``2e-10``- - the input is **not** checked for being a rotation matrix:+ - by default the input is **not** checked for being a rotation matrix:``zeros(3, 3)`` returns ``[0., 0., 3.1416]`` and ``2 * eye(3)``- returns ``[0., 0., 0.]``+ returns ``[0., 0., 0.]``. Pass ``check_rotation=True`` to reject+ such an input instead- ``rotation_matrix_to_angle_axis`` is the deprecated alias of thisfunction since 0.7.0.. warning::- A reflection (``det = -1``) is returned as a rotation:- ``diag(-1, 1, 1)`` gives ``[0., 0., 0.]``, the identity. Tracked in- `#4773 <https://github.com/kornia/kornia/issues/4773>`_.+ By default a reflection (``det = -1``) is returned as a rotation:+ ``diag(-1, 1, 1)`` gives ``[0., 0., 0.]``, the identity. Pass+ ``check_rotation=True`` to raise a ``ValueError`` instead.Args:rotation_matrix: rotation matrix of shape :math:`(*, 3, 3)`.+ check_rotation: if ``True``, raise ``ValueError`` unless every input+ is a rotation: ``max|R @ R^T - I|`` within 100 eps of the dtype of+ ``rotation_matrix`` (16 eps for float16 and bfloat16) and+ ``det(R) > 0``. Defaults to ``False`` (unchecked).Returns:Rodrigues vector transformation of shape :math:`(*, 3)`.@@ -556,6 +561,10 @@ def rotation_matrix_to_axis_angle(rotation_matrix: torch.Tensor) -> torch.Tensorif not rotation_matrix.shape[-2:] == (3, 3):raise ValueError(f"Input size must be a (*, 3, 3) tensor. Got {rotation_matrix.shape}")++ if check_rotation:+ _check_is_rotation(rotation_matrix, "rotation_matrix_to_axis_angle")+quaternion: torch.Tensor = rotation_matrix_to_quaternion(rotation_matrix)return quaternion_to_axis_angle(quaternion)@@ -565,7 +574,9 @@ def rotation_matrix_to_angle_axis(rotation_matrix: torch.Tensor) -> torch.Tensorreturn rotation_matrix_to_axis_angle(rotation_matrix)-def rotation_matrix_to_quaternion(rotation_matrix: torch.Tensor, eps: float = 1.0e-8) -> torch.Tensor:+def rotation_matrix_to_quaternion(+ rotation_matrix: torch.Tensor, eps: float = 1.0e-8, check_rotation: bool = False+) -> torch.Tensor:r"""Convert 3x3 rotation matrix to 4d quaternion vector.The quaternion vector has components in (w, x, y, z) format.@@ -580,9 +591,10 @@ def rotation_matrix_to_quaternion(rotation_matrix: torch.Tensor, eps: float = 1.non-negative and ``w`` may be negative: 170 degrees about``(1, 2, -3)/sqrt(14)`` (``trace = -0.9696``) returns``[-0.0872, -0.2662, -0.5325, 0.7987]``- - the input is **not** checked for being a rotation matrix; see the- degenerate inputs listed on- :func:`~kornia.geometry.conversions.rotation_matrix_to_axis_angle`+ - by default the input is **not** checked for being a rotation matrix;+ see the degenerate inputs listed on+ :func:`~kornia.geometry.conversions.rotation_matrix_to_axis_angle`.+ Pass ``check_rotation=True`` to reject such an input insteadArgs:rotation_matrix: the rotation matrix to convert with shape :math:`(*, 3, 3)`.@@ -593,6 +605,10 @@ def rotation_matrix_to_quaternion(rotation_matrix: torch.Tensor, eps: float = 1.zero gradient. For an exact rotation matrix the selected radicand isat least ``1``, so ``eps`` does not change the result. The divisionsare separately guarded against a zero denominator.+ check_rotation: if ``True``, raise ``ValueError`` unless every input+ is a rotation: ``max|R @ R^T - I|`` within 100 eps of the dtype of+ ``rotation_matrix`` (16 eps for float16 and bfloat16) and+ ``det(R) > 0``. Defaults to ``False`` (unchecked).Return:the rotation in quaternion with shape :math:`(*, 4)`.@@ -611,6 +627,9 @@ def rotation_matrix_to_quaternion(rotation_matrix: torch.Tensor, eps: float = 1.if not rotation_matrix.shape[-2:] == (3, 3):raise ValueError(f"Input size must be a (*, 3, 3) tensor. Got {rotation_matrix.shape}")+ if check_rotation:+ _check_is_rotation(rotation_matrix, "rotation_matrix_to_quaternion")+def safe_zero_division(numerator: torch.Tensor, denominator: torch.Tensor) -> torch.Tensor:eps: float = torch.finfo(numerator.dtype).tinyreturn numerator / torch.clamp(denominator, min=eps)diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.pyindex 8224d55b7..3ec49d887 100644--- a/kornia/geometry/liegroup/se3.py+++ b/kornia/geometry/liegroup/se3.py@@ -339,11 +339,15 @@ class Se3(nn.Module):return rt_4x4@classmethod- def from_matrix(cls, matrix: torch.Tensor) -> Se3:+ def from_matrix(cls, matrix: torch.Tensor, check_rotation: bool = False) -> Se3:"""Create a Se3 group from a matrix.Args:matrix: torch.Tensor of shape :math:`(B, 4, 4)`.+ check_rotation: if ``True``, raise ``ValueError`` unless the rotation+ block of every input is a rotation matrix. The default ``False``+ keeps the unchecked behaviour, under which a reflection block+ such as ``diag(-1, 1, 1)`` yields a non-unit quaternion.Example:>>> s = Se3.from_matrix(torch.eye(4))@@ -355,7 +359,7 @@ class Se3(nn.Module):"""KORNIA_CHECK_SHAPE(matrix, ["*", "4", "4"])- r = So3.from_matrix(matrix[..., :3, :3])+ r = So3.from_matrix(matrix[..., :3, :3], check_rotation=check_rotation)t = matrix[..., :3, -1]return cls(r, t)diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.pyindex 454549b72..e4d04a736 100644--- a/kornia/geometry/liegroup/so3.py+++ b/kornia/geometry/liegroup/so3.py@@ -94,11 +94,12 @@ class So3(nn.Module)::math:`\exp(\omega + \delta) \approx \exp(\omega) \exp(J_r \delta) = \exp(J_l \delta) \exp(\omega)`,with :math:`J_r` = ``right_jacobian(omega)`` and :math:`J_l` = ``left_jacobian(omega)`` =``right_jacobian(-omega)``.+ - ``from_matrix`` does not check its input by default: a reflection (det :math:`-1`) is accepted without+ error and returns an ``So3`` whose ``matrix()`` is not the input. ``check_rotation=True`` raises+ ``ValueError`` instead.- Known defects: the quaternion is stored as given, so with a non-unit ``q`` the ``matrix()`` is not arotation and ``s * p`` scales ``p`` by :math:`|q|^2`- (`#4942 <https://github.com/kornia/kornia/issues/4942>`_); ``from_matrix`` accepts a reflection- (det :math:`-1`) without error and returns an ``So3`` whose ``matrix()`` is not the input- (`#4773 <https://github.com/kornia/kornia/issues/4773>`_); ``exp``, ``identity``, ``random``,+ (`#4942 <https://github.com/kornia/kornia/issues/4942>`_); ``exp``, ``identity``, ``random``,``from_matrix`` and every operation store the quaternion as a plain tensor, which has no ``state_dict()``entry and which ``.to()`` leaves unchanged; only a quaternion built on an ``nn.Parameter`` is saved and moved(`#4923 <https://github.com/kornia/kornia/issues/4923>`_).@@ -307,11 +308,17 @@ class So3(nn.Module):return torch.stack((row0, row1, row2), -2)@classmethod- def from_matrix(cls, matrix: torch.Tensor) -> So3:+ def from_matrix(cls, matrix: torch.Tensor, check_rotation: bool = False) -> So3:"""Create So3 from a rotation matrix.Args:matrix: the rotation matrix to convert of shape :math:`(B,3,3)`.+ check_rotation: if ``True``, raise ``ValueError`` unless every input+ is a rotation matrix. The default ``False`` keeps the unchecked+ behaviour, under which a reflection such as ``diag(-1, 1, 1)``+ is silently turned into the identity. Note that+ ``So2.from_matrix`` rejects the 2D reflection ``diag(1, -1)``+ regardless.Example:>>> m = torch.eye(3)@@ -320,7 +327,7 @@ class So3(nn.Module):tensor([1., 0., 0., 0.])"""- return cls(Quaternion.from_matrix(matrix))+ return cls(Quaternion.from_matrix(matrix, check_rotation=check_rotation))@classmethoddef from_wxyz(cls, wxyz: torch.Tensor) -> So3:diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.pyindex 353d414b2..586ca80d6 100644--- a/kornia/geometry/quaternion.py+++ b/kornia/geometry/quaternion.py@@ -447,11 +447,16 @@ class Quaternion(nn.Module):return quaternion_to_rotation_matrix(self.data)@classmethod- def from_matrix(cls, matrix: torch.Tensor) -> "Quaternion":+ def from_matrix(cls, matrix: torch.Tensor, check_rotation: bool = False) -> "Quaternion":"""Create a quaternion from a rotation matrix.Args:matrix: the rotation matrix to convert of shape :math:`(B, 3, 3)`.+ check_rotation: if ``True``, raise ``ValueError`` unless every input+ is a rotation matrix. The default ``False`` keeps the unchecked+ behaviour, under which a reflection such as+ ``diag(-1, 1, 1)`` returns a non-unit quaternion rather than+ being reported as invalid.Example:>>> m = torch.eye(3)[None]@@ -460,7 +465,7 @@ class Quaternion(nn.Module):tensor([[1., 0., 0., 0.]])"""- return cls(rotation_matrix_to_quaternion(matrix))+ return cls(rotation_matrix_to_quaternion(matrix, check_rotation=check_rotation))@classmethoddef from_euler(cls, roll: torch.Tensor, pitch: torch.Tensor, yaw: torch.Tensor) -> "Quaternion":diff --git a/tests/geometry/liegroup/test_se3.py b/tests/geometry/liegroup/test_se3.pyindex efda0cafe..b6b6440b4 100644--- a/tests/geometry/liegroup/test_se3.py+++ b/tests/geometry/liegroup/test_se3.py@@ -288,6 +288,34 @@ class TestSe3(BaseTester):self.assert_close(s.r.matrix(), matrix[..., 0:3, 0:3])self.assert_close(s.t, matrix[..., 0:3, 3])+ @pytest.mark.parametrize("batch_size", (None, 1, 2))+ def test_from_matrix_check_rotation(self, device, dtype, batch_size):+ # kornia#4773: the rotation block reaches rotation_matrix_to_quaternion, so a reflection+ # block is accepted by default and yields a non-unit quaternion. check_rotation=True has+ # to pass through Se3 -> So3 -> Quaternion to reject it.+ matrix = torch.eye(4, device=device, dtype=dtype)+ matrix[0, 0] = -1.0+ if batch_size is not None:+ matrix = matrix.repeat(batch_size, 1, 1)++ Se3.from_matrix(matrix) # default is unchecked, must not raise+ with pytest.raises(ValueError, match="reflection"):+ Se3.from_matrix(matrix, check_rotation=True)++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_from_matrix_check_rotation_accepts_rotation(self, device, dtype, batch_size):+ # A genuine rotation block passes, and the flag leaves both parts of the group element+ # alone. Comparing the checked call against the unchecked one rather than against the+ # input keeps this about the check: the round trip loses too much in half precision.+ rotation = So3(Quaternion.random(batch_size, device, dtype))+ translation = self._make_rand_data(device, dtype, batch_size, dims=3)+ matrix = Se3(rotation, translation).matrix()++ checked = Se3.from_matrix(matrix, check_rotation=True)+ unchecked = Se3.from_matrix(matrix)+ self.assert_close(checked.r.q.data, unchecked.r.q.data)+ self.assert_close(checked.t, unchecked.t)+@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))def test_from_qxyz(self, device, dtype, batch_size):qxyz = self._make_rand_data(device, dtype, batch_size, dims=7)diff --git a/tests/geometry/liegroup/test_so3.py b/tests/geometry/liegroup/test_so3.pyindex 89fb76f76..5ff59d514 100644--- a/tests/geometry/liegroup/test_so3.py+++ b/tests/geometry/liegroup/test_so3.py@@ -410,6 +410,31 @@ class TestSo3(BaseTester):self.assert_close(rp_, qp_.vec) # p_ = R*p = q*p*q_invself.assert_close(rp_.norm(), pvec.norm())+ @pytest.mark.parametrize("batch_size", (None, 1, 2))+ def test_from_matrix_check_rotation(self, device, dtype, batch_size):+ # kornia#4773: from_matrix delegates to rotation_matrix_to_quaternion, so by default the+ # reflection diag(-1, 1, 1) becomes the identity instead of being rejected. So2.from_matrix+ # rejects the 2D reflection regardless; check_rotation=True gives So3 the same rejection as an opt-in.+ reflection = torch.diag(torch.tensor([-1.0, 1.0, 1.0], device=device, dtype=dtype))+ if batch_size is not None:+ reflection = reflection.repeat(batch_size, 1, 1)++ self.assert_close(+ So3.from_matrix(reflection).matrix(),+ torch.eye(3, device=device, dtype=dtype).expand_as(reflection),+ )+ with pytest.raises(ValueError, match="reflection"):+ So3.from_matrix(reflection, check_rotation=True)++ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))+ def test_from_matrix_check_rotation_accepts_rotation(self, device, dtype, batch_size):+ # A genuine rotation passes the check, and the flag does not alter the result. Comparing+ # the two calls rather than the matrix round trip keeps this about the check itself: the+ # round trip loses too much in float16 and bfloat16 to say anything there.+ q = Quaternion.random(batch_size, device, dtype)+ matrix = So3(q).matrix()+ self.assert_close(So3.from_matrix(matrix, check_rotation=True).q.data, So3.from_matrix(matrix).q.data)+@pytest.mark.parametrize("batch_size", (None, 1, 2, 5))def test_from_wxyz(self, device, dtype, batch_size):wxyz = self._make_rand_data(device, dtype, batch_size, dims=4)@@ -631,10 +656,10 @@ class TestSo3Conventions(BaseTester):# log() is outside the defect: it reads only the direction of qself.assert_close(s.log(), So3(Quaternion(data).normalize()).log())- def test_wart_so3_from_matrix_accepts_a_reflection_4773(self, device, dtype):- # #4773 https://github.com/kornia/kornia/issues/4773: from_matrix silently returns an apparently valid- # result for an improper matrix (det = -1), whose matrix() is not the input. This turns red if it rejects- # the input or signals NaN.+ def test_convention_so3_from_matrix_is_unchecked_by_default(self, device, dtype):+ # kornia#4773: with the default check_rotation=False, from_matrix returns an apparently valid result for an+ # improper matrix (det = -1), whose matrix() is not the input. This turns red if the default rejects the+ # input or signals NaN; the opt-in raise is pinned by test_from_matrix_check_rotation.flip = torch.diag(torch.tensor([-1.0, 1.0, 1.0], device=device, dtype=dtype))s = So3.from_matrix(flip)assert isinstance(s, So3)diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex 6dbb6e24f..970a8e80c 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -2465,10 +2465,12 @@ class TestRotationMatrixToAngleAxis(BaseTester):assert multi_batched.shape == (2, 5, 3)self.assert_close(multi_batched[1, 4], expected)- def test_wart_reflection_is_returned_as_the_identity_4773(self, device, dtype):- # Wart pin for kornia#4773: an improper matrix (det = -1) is not rejected, and the- # reflection diag(-1, 1, 1) comes back as the zero vector -- "no rotation". Flips when the- # function raises or returns anything else for it.+ def test_convention_reflection_is_returned_as_the_identity_by_default(self, device, dtype):+ # kornia#4773: with the default check_rotation=False an improper matrix+ # (det = -1) is still not rejected, and the reflection diag(-1, 1, 1) comes back as the+ # zero vector -- "no rotation". The call below deliberately omits the argument; passing+ # check_rotation=True raises instead, which TestRotationMatrixToAxisAngleCheckRotation+ # covers. Flips when the default raises or returns anything else for it.reflection = torch.diag(torch.tensor([-1.0, 1.0, 1.0], device=device, dtype=dtype))out = kornia.geometry.conversions.rotation_matrix_to_axis_angle(reflection)@@ -2478,7 +2480,7 @@ class TestRotationMatrixToAngleAxis(BaseTester):torch.zeros(3, device=device, dtype=dtype),atol=0.0,rtol=0.0,- msg=_issue_msg("kornia#4773: a reflection is no longer returned as the identity rotation"),+ msg=_issue_msg("kornia#4773: the default no longer returns a reflection as the identity rotation"),)def test_convention_axis_angle_matrix_roundtrip_is_accurate_in_float64(self, device):@@ -6061,3 +6063,62 @@ def test_convention_deprecated_alias_leaves_the_global_warning_filters_alone_395after = list(warnings.filters)assert after == [], f"kornia#3956: {alias_name} mutated the global DeprecationWarning filters; got {after}"+++class TestRotationMatrixToAxisAngleCheckRotation:+ # kornia#4773: by default an improper matrix is reported as a rotation, and check_rotation=True+ # rejects it, following the opt-in introduced in kornia#3961 for camtoworld/worldtocam Rt.+ fns = [+ kornia.geometry.conversions.rotation_matrix_to_axis_angle,+ kornia.geometry.conversions.rotation_matrix_to_quaternion,+ ]++ @pytest.mark.parametrize("fn", fns)+ def test_default_is_unchanged(self, fn, device, dtype):+ # The default path still accepts the reflection, so the flag is opt-in only.+ _skip_if_dtype_unavailable(device, dtype)+ reflection = torch.diag(torch.tensor([-1.0, 1.0, 1.0], device=device, dtype=dtype))+ fn(reflection) # must not raise++ @pytest.mark.parametrize("fn", fns)+ def test_check_rotation_accepts_rotation_unchanged(self, fn, device, dtype):+ # A genuine rotation passes and the result is bitwise the unchecked one.+ _skip_if_dtype_unavailable(device, dtype)+ rotation = torch.tensor(_ASYMMETRIC_R, device=device, dtype=dtype)+ assert_close(fn(rotation, check_rotation=True), fn(rotation), atol=0.0, rtol=0.0)++ @pytest.mark.parametrize("fn", fns)+ def test_check_rotation_accepts_rounding_error(self, fn, device, dtype):+ # Rotations carrying only their dtype's rounding must pass.+ _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)+ fn(rotation, check_rotation=True) # must not raise++ @pytest.mark.parametrize("fn", fns)+ 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)+ reflection = torch.diag(torch.tensor([-1.0, 1.0, 1.0], device=device, dtype=dtype))+ with pytest.raises(ValueError, match="reflection"):+ fn(reflection, check_rotation=True)++ @pytest.mark.parametrize("fn", fns)+ def test_check_rotation_rejects_non_orthogonal(self, fn, device, dtype):+ # 2 * I is exact in every dtype and has det = 8, so it fails the orthogonality test first.+ _skip_if_dtype_unavailable(device, dtype)+ scaled = 2.0 * torch.eye(3, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="not a rotation matrix"):+ fn(scaled, check_rotation=True)++ @pytest.mark.parametrize("fn", fns)+ def test_check_rotation_rejects_one_bad_matrix_in_batch(self, fn, device, dtype):+ # One improper matrix among good ones is enough to raise, at any batch rank.+ _skip_if_dtype_unavailable(device, dtype)+ good = torch.tensor(_ASYMMETRIC_R, device=device, dtype=dtype)+ bad = torch.diag(torch.tensor([-1.0, 1.0, 1.0], device=device, dtype=dtype))[None]+ batch = torch.cat([good, bad, good]).reshape(3, 1, 3, 3)+ with pytest.raises(ValueError, match="reflection"):+ fn(batch, check_rotation=True)diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.pyindex a26439210..1ea8e8339 100644--- a/tests/geometry/test_quaternion.py+++ b/tests/geometry/test_quaternion.py@@ -363,6 +363,23 @@ class TestQuaternion(BaseTester):except Exception:self.assert_close(qq1, -qq2)+ @pytest.mark.parametrize("batch_size", (1, 2))+ def test_from_matrix_check_rotation(self, device, dtype, batch_size):+ # kornia#4773: the reflection diag(-1, 1, 1) is orthogonal but has det = -1, and by default+ # comes back as the non-unit quaternion [0.7071, 0, 0, 0] rather than being rejected.+ reflection = torch.diag(torch.tensor([-1.0, 1.0, 1.0], device=device, dtype=dtype))+ reflection = reflection.repeat(batch_size, 1, 1)++ assert Quaternion.from_matrix(reflection).data.shape == (batch_size, 4)+ with pytest.raises(ValueError, match="reflection"):+ Quaternion.from_matrix(reflection, check_rotation=True)++ rotation = Quaternion.random(batch_size, device, dtype).matrix()+ self.assert_close(+ Quaternion.from_matrix(rotation, check_rotation=True).data,+ Quaternion.from_matrix(rotation).data,+ )+@pytest.mark.parametrize("batch_size", (1, 2, 5))def test_getitem(self, device, dtype, batch_size):q = Quaternion.random(batch_size, device, dtype)