🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(geometry): convention blocks and pins for linalg transforms and NamedPose (batch 9c) (#4978)
Dmytro Mishkin87f349d0f0fe
diff --git a/changelog.d/4978.added.md b/changelog.d/4978.added.mdnew file mode 100644index 000000000..449fd9fa3--- /dev/null+++ b/changelog.d/4978.added.md@@ -0,0 +1 @@+Convention blocks for `relative_transformation` and its linalg siblings (frame naming, rigid-only inputs, the contrast with `relative_camera_motion`) and for `NamedPose`, an API page for `kornia.geometry.pose`, and 12 convention and wart pins; the warts are documented and linked (#4881, #4937), not fixed.diff --git a/docs/source/geometry.linalg.rst b/docs/source/geometry.linalg.rstindex a0c5fb43b..3a936359a 100644--- a/docs/source/geometry.linalg.rst+++ b/docs/source/geometry.linalg.rst@@ -12,6 +12,7 @@ kornia.geometry.linalg.. autofunction:: inverse_transformation.. autofunction:: transform_points.. autofunction:: point_line_distance+.. autofunction:: batched_squared_norm.. autofunction:: squared_norm.. autofunction:: batched_dot_product.. autofunction:: euclidean_distancediff --git a/docs/source/geometry.pose.rst b/docs/source/geometry.pose.rstnew file mode 100644index 000000000..bfd441a5f--- /dev/null+++ b/docs/source/geometry.pose.rst@@ -0,0 +1,11 @@+kornia.geometry.pose+====================++.. meta::+ :description: The kornia.geometry.pose module provides NamedPose, a rigid SE(2) or SE(3) transform that carries the names of its source and destination frames, so that composing two poses checks that their frames chain.++.. currentmodule:: kornia.geometry.pose++.. autoclass:: NamedPose+ :members:+ :special-members: __init__, __mul__diff --git a/docs/source/geometry.rst b/docs/source/geometry.rstindex 406b451cd..584bcd9a1 100644--- a/docs/source/geometry.rst+++ b/docs/source/geometry.rst@@ -23,7 +23,8 @@ This module, the original core of the library, consists of the following main suand calibrated cameras, per-pixel surface normals, and warping frames given a calibrated camera setup.The remaining submodules, listed below, cover bounding boxes and keypoints, calibration, epipolar geometry,-homographies, Lie groups, lines, point clouds, quaternions, RANSAC, polynomial solvers and sub-pixel refinement.+homographies, Lie groups, named poses, lines, point clouds, quaternions, RANSAC, polynomial solvers and sub-pixel+refinement... admonition:: About ``align_corners``@@ -55,6 +56,7 @@ homographies, Lie groups, lines, point clouds, quaternions, RANSAC, polynomial sransac <geometry.ransac>calibration <geometry.calibration>liegroup <geometry.liegroup>+ pose <geometry.pose>quaternion <geometry.quaternion>line <geometry.line>bbox <geometry.bbox>diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rstindex f30eb4cfd..e2005c1a3 100644--- a/docs/source/get-started/precision.rst+++ b/docs/source/get-started/precision.rst@@ -116,7 +116,7 @@ precision, so the table says nothing about those backends.- ⚠️ Partial- ⚠️ Partial- 8 / 17- - Accuracy in boxes, depth and line utilities; bfloat16 ``NamedPose`` construction raises.+ - Accuracy in boxes, depth and line utilities; a bfloat16 ``NamedPose`` of an ``Se2`` pose cannot be built (``So2`` stores a complex number).* - ``kornia.image``- ⚠️ Partial- ⚠️ Partialdiff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex c0e680c44..bde21cfcb 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -879,7 +879,9 @@ def relative_camera_motion(Convention:- Inputs are world-to-camera extrinsics, :math:`x_{cam} = R X + t` (see :doc:`camera and worldconventions </get-started/camera-conventions>`); the result is :math:`R = R_2 R_1^\top` and- :math:`t = t_2 - R_2 R_1^\top t_1`, the motion from camera 1 to camera 2.+ :math:`t = t_2 - R_2 R_1^\top t_1`, the motion from camera 1 to camera 2. As 4x4 matrices this is+ :math:`E_2 E_1^{-1}`, whereas :func:`~kornia.geometry.linalg.relative_transformation` of :math:`E_1` and+ :math:`E_2` returns :math:`E_1^{-1} E_2`.Args:R1: The first camera rotation matrix with shape :math:`(*, 3, 3)`.diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.pyindex aa6e2524c..8224d55b7 100644--- a/kornia/geometry/liegroup/se3.py+++ b/kornia/geometry/liegroup/se3.py@@ -43,7 +43,7 @@ class Se3(nn.Module):Convention:- The tangent vector is :math:`[\upsilon, \omega]`, translation first- (:doc:`Conventions </get-started/conventions>` maps it onto Sophus and GTSAM): ``exp`` rotates by+ (:ref:`Rotations and rigid motions <rotation-conventions>` maps it onto Sophus and GTSAM): ``exp`` rotates by``So3.exp(omega)`` and translates by :math:`V(\omega) \upsilon`, ``hat`` is:math:`[[\hat\omega, \upsilon], [0, 0]]`, and ``log`` is principal, with :math:`|\omega| \le \pi`.- ``matrix()`` is the 4x4 :math:`[[R, t], [0, 1]]`. When both rotations are unit, ``a * b`` isdiff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex 82c928db3..0ccc14ab4 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -39,15 +39,21 @@ def compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> tr"""Compose two homogeneous transformations... math::- T_0^{2} = \begin{bmatrix} R_0^1 R_1^{2} & R_0^{1} t_1^{2} + t_0^{1} \- \\mathbf{0} & 1\end{bmatrix}+ T_0^{2} = \begin{bmatrix} R_0^{1} R_1^{2} & R_0^{1} t_1^{2} + t_0^{1} \\+ \mathbf{0} & 1 \end{bmatrix}++ Convention:+ - The result is the matrix product ``trans_01 @ trans_12``, with the frame naming of+ :func:`relative_transformation`. Only the top three rows of each input are read and the last row of the+ result is always :math:`[0, 0, 0, 1]`: any affine pair composes exactly, and a projective input is used as+ if its last row were :math:`[0, 0, 0, 1]`.Args:trans_01: tensor with the homogeneous transformation from- a reference frame 1 respect to a frame 0. The tensor has must have a+ a reference frame 1 respect to a frame 0. The tensor must have ashape of :math:`(N, 4, 4)` or :math:`(4, 4)`.trans_12: tensor with the homogeneous transformation from- a reference frame 2 respect to a frame 1. The tensor has must have a+ a reference frame 2 respect to a frame 1. The tensor must have ashape of :math:`(N, 4, 4)` or :math:`(4, 4)`. A batch of one broadcasts against a batch of:math:`N` in either argument.@@ -95,9 +101,9 @@ def compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> tdef inverse_transformation(trans_12: torch.Tensor) -> torch.Tensor:- r"""Invert a 4x4 homogeneous transformation.+ r"""Invert a 4x4 rigid homogeneous transformation.- :math:`T_1^{2} = \begin{bmatrix} R_1 & t_1 \\ \mathbf{0} & 1 \end{bmatrix}`+ :math:`T_1^{2} = \begin{bmatrix} R_1 & t_1 \\ \mathbf{0} & 1 \end{bmatrix}`The inverse transformation is computed as follows:@@ -106,6 +112,12 @@ def inverse_transformation(trans_12: torch.Tensor) -> torch.Tensor:T_2^{1} = (T_1^{2})^{-1} = \begin{bmatrix} R_1^T & -R_1^T t_1 \\\mathbf{0} & 1\end{bmatrix}+ Convention:+ - The input must be a rigid :math:`[R|t]`, and this is not validated: the rotation block is transposed, not+ inverted, and the last row is read as :math:`[0, 0, 0, 1]`, so a scaled, sheared or projective matrix+ returns a result that is not its inverse. Use :func:`torch.linalg.inv` for a general matrix. Frame naming+ is on :func:`relative_transformation`.+Args:trans_12: transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`.@@ -113,8 +125,12 @@ def inverse_transformation(trans_12: torch.Tensor) -> torch.Tensor:tensor with inverted transformations with shape :math:`(N, 4, 4)` or :math:`(4, 4)`.Example:- >>> trans_12 = torch.rand(1, 4, 4) # Nx4x4+ >>> trans_12 = torch.eye(4)[None] # Nx4x4: a rotation of 90 degrees about z and a translation+ >>> trans_12[:, :3, :3] = torch.tensor([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])+ >>> trans_12[:, :3, 3] = torch.tensor([1.0, 2.0, 3.0])>>> trans_21 = inverse_transformation(trans_12) # Nx4x4+ >>> trans_21[:, :3, 3]+ tensor([[-2., 1., -3.]])"""KORNIA_CHECK_IS_TENSOR(trans_12)@@ -140,15 +156,27 @@ def inverse_transformation(trans_12: torch.Tensor) -> torch.Tensor:def relative_transformation(trans_01: torch.Tensor, trans_02: torch.Tensor) -> torch.Tensor:r"""Compute the relative homogeneous transformation from a reference transformation.- :math:`T_1^{0} = \begin{bmatrix} R_1 & t_1 \\ \mathbf{0} & 1 \end{bmatrix}` to destination :math:`T_2^{0} =- \begin{bmatrix} R_2 & t_2 \\ \mathbf{0} & 1 \end{bmatrix}`.-- The relative transformation is computed as follows:+ Given the reference :math:`T_0^{1} = \begin{bmatrix} R_1 & t_1 \\ \mathbf{0} & 1 \end{bmatrix}` and the+ destination :math:`T_0^{2} = \begin{bmatrix} R_2 & t_2 \\ \mathbf{0} & 1 \end{bmatrix}`, the relative+ transformation is computed as follows:.. math::T_1^{2} = (T_0^{1})^{-1} \cdot T_0^{2}+ Convention:+ - ``trans_ab`` (:math:`T_a^{b}`) maps points in frame ``b`` to frame ``a``, :math:`p_a = T_a^{b} p_b`:+ ``transform_points(trans_01, points_1)`` returns ``points_0``, and+ ``compose_transformations(trans_01, trans_12)`` returns ``trans_02``.+ :ref:`Rotations and rigid motions <rotation-conventions>` maps this onto other libraries.+ - ``trans_01`` must be a rigid :math:`[R|t]`, as for :func:`inverse_transformation`, and the last row of+ ``trans_02`` is read as :math:`[0, 0, 0, 1]`, as in :func:`compose_transformations`. Neither is validated:+ a scaled, sheared or projective ``trans_01``, or a projective ``trans_02``, gives a wrong result silently.+ - :func:`~kornia.geometry.epipolar.relative_camera_motion` takes world-to-camera extrinsics+ :math:`E_1, E_2` and returns the :math:`[R|t]` of :math:`E_2 E_1^{-1}`, which is+ ``relative_transformation`` of :math:`E_2^{-1}` and :math:`E_1^{-1}`, in this order, not of :math:`E_1` and+ :math:`E_2`.+Args:trans_01: reference transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`.trans_02: destination transformation tensor of shape :math:`(N, 4, 4)` or :math:`(4, 4)`. A batch@@ -257,11 +285,19 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Tedef point_line_distance(point: torch.Tensor, line: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:r"""Return the distance from points to lines.+ Convention:+ - ``line`` need not be normalised. The geometric distance is :math:`|ax + by + c| / \|(a, b)\|` for+ :math:`(a, b) \ne (0, 0)`; kornia instead divides by :math:`\|(a, b)\| + \epsilon`.+ - Known defect: this ``eps`` biases the distance when the line coefficients are small and returns+ :math:`|c| / \epsilon` for a line with :math:`a = b = 0`; in ``float16`` the default ``eps`` rounds to+ zero, so that line gives ``inf``, or ``nan`` when :math:`c = 0` as well+ (`#4881 <https://github.com/kornia/kornia/issues/4881>`_).+Args:point: points :math:`(*, N, 2)`, or homogeneous points :math:`(*, N, 3)` whose last coordinate is theweight :math:`w`; a point at infinity (:math:`w = 0`) is at distance ``inf`` from every line.line: lines coefficients :math:`(a, b, c)` with shape :math:`(*, N, 3)`, where :math:`ax + by + c = 0`.- eps: Small constant for safe sqrt.+ eps: small constant added to :math:`\|(a, b)\|` in the denominator.Returns:the computed distance with shape :math:`(*, N)`.diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.pyindex 046c77fd5..b296ee722 100644--- a/kornia/geometry/pose.py+++ b/kornia/geometry/pose.py@@ -44,6 +44,19 @@ class NamedPose:Internally represented by either Se2 or Se3.+ Convention:+ - ``NamedPose(pose, frame_src="a", frame_dst="b")`` is ``b_from_a``: :meth:`transform_points` maps points in+ frame ``a`` to frame ``b``, so ``NamedPose(pose, frame_src="1", frame_dst="0")`` is ``trans_01`` in the+ notation of :func:`~kornia.geometry.linalg.relative_transformation`, for an ``Se2`` and an ``Se3`` pose alike.+ - ``c_from_b * b_from_a`` is ``c_from_a``. For valid rigid poses, its matrix is+ ``c_from_b.pose.matrix() @ b_from_a.pose.matrix()``; an ``Se3`` pose with a non-unit quaternion is not+ guaranteed to satisfy this identity (`#4942 <https://github.com/kornia/kornia/issues/4942>`_).+ The left operand's ``frame_src`` must equal the right operand's ``frame_dst``, otherwise ``*`` raises+ ``ValueError``; :meth:`inverse` inverts the pose and swaps the frame names.+ - Known defect: the pose type is not validated, so an ``So3``, ``So2``, ``Quaternion`` or tensor is accepted+ and :attr:`rotation` then raises ``AttributeError``; a product of an ``Se3`` pose and an ``Se2`` pose also+ raises ``AttributeError`` instead of ``ValueError`` (`#4937 <https://github.com/kornia/kornia/issues/4937>`_).+Example:>>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")>>> b_from_a@@ -60,8 +73,8 @@ class NamedPose:Args:dst_from_src: Pose from source frame to destination frame.- frame_src: Name of frame a.- frame_dst: Name of frame b.+ frame_src: Name of the source frame; a random unique name when omitted or empty.+ frame_dst: Name of the destination frame; a random unique name when omitted or empty."""self._dst_from_src = dst_from_src@@ -140,8 +153,8 @@ class NamedPose:Args:rotation: Rotation part of the pose.translation: Translation part of the pose.- frame_src: Name of the source frame.- frame_dst: Name of the destination frame.+ frame_src: Name of the source frame; a random unique name when omitted or empty.+ frame_dst: Name of the destination frame; a random unique name when omitted or empty.Returns:NamedPose constructed from rotation and translation.@@ -190,8 +203,8 @@ class NamedPose:Args:matrix: Matrix representation of the pose.- frame_src: Name of the source frame.- frame_dst: Name of the destination frame.+ frame_src: Name of the source frame; a random unique name when omitted or empty.+ frame_dst: Name of the destination frame; a random unique name when omitted or empty.Returns:NamedPose constructed from a matrix.diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.pyindex 9b11b3688..92d232239 100644--- a/tests/geometry/test_linalg.py+++ b/tests/geometry/test_linalg.py@@ -495,3 +495,165 @@ class TestEuclideanDistance(BaseTester):def test_module(self, device, dtype):pass+++# Two rigid, non-commuting transforms (T01 T02 != T02 T01 by 0.854), neither the identity nor a pure translation.+# Generated in float64:+# from kornia.geometry.liegroup import Se3+# T01 = Se3.exp(torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], dtype=torch.float64)).matrix()+# T02 = Se3.exp(torch.tensor([0.3, 0.1, -0.2, -0.1, 0.3, 0.05], dtype=torch.float64)).matrix()+_T01 = [+ [0.9365557269934556, 0.32475143364814213, 0.13190859175670216, 0.8932266973410873],+ [-0.24666617456316434, 0.8779917826797222, -0.4102270442977377, -2.6663426561315666],+ [-0.24903648038416887, 0.35166309998400436, 0.9023934261437778, 2.4134071590337385],+ [0.0, 0.0, 0.0, 1.0],+]+_T02 = [+ [0.9541437047897824, -0.06402251222932676, 0.2924224829555252, 0.26284367361699246],+ [0.034277888309185565, 0.9938032033499706, 0.10573655651854763, 0.09532423813367488],+ [-0.2973799202755487, -0.09086424455847703, 0.9504256267997647, -0.24625808156806428],+ [0.0, 0.0, 0.0, 1.0],+]+++class TestLinalgConventions(BaseTester):+ @staticmethod+ def _fixture(device, dtype):+ t01 = torch.tensor(_T01, device=device, dtype=dtype)+ t02 = torch.tensor(_T02, device=device, dtype=dtype)+ # precondition: the pair does not commute, so an operand swap changes every result below, and neither+ # transform is a pure translation+ assert (t01 @ t02 - t02 @ t01).abs().max() > 0.5+ eye = torch.eye(3, device=device, dtype=dtype)+ assert (t01[:3, :3] - eye).abs().max() > 0.1 and (t02[:3, :3] - eye).abs().max() > 0.1+ return t01, t02++ def test_convention_relative_transformation_is_inverse_first_times_second(self, device, dtype):+ t01, t02 = self._fixture(device, dtype)+ # trans_12 = trans_01^-1 @ trans_02, generated in float64 as torch.linalg.inv(T01) @ T02+ expected = torch.tensor(+ [+ [0.9592120041966407, -0.2824697732662307, 0.01109766624060022, -0.6092449687748074],+ [0.23537769566281422, 0.8198060415906909, 0.5220300705475368, 1.2846969255319278],+ [-0.15655564949731832, -0.49812536711386907, 0.8528548805325243, -3.6161278131582963],+ [0.0, 0.0, 0.0, 1.0],+ ],+ device=device,+ dtype=dtype,+ )+ trans_12 = kgl.relative_transformation(t01, t02)+ self.assert_close(trans_12, expected)+ # and composing it back onto trans_01 recovers trans_02+ self.assert_close(kgl.compose_transformations(t01, trans_12), t02)++ def test_convention_compose_transformations_order(self, device, dtype):+ t01, t02 = self._fixture(device, dtype)+ # compose(a, b) = a @ b, generated in float64 as T01 @ T02+ expected = torch.tensor(+ [+ [0.8655135779661945, 0.25079259002638926, 0.4335773554326974, 1.1378675714180575],+ [-0.08326598765280734, 0.9256182047971615, -0.3691852031816589, -2.5464616769031294],+ [-0.4939160066816611, 0.28343255941393825, 0.8220176169691901, 2.1592498388088193],+ [0.0, 0.0, 0.0, 1.0],+ ],+ device=device,+ dtype=dtype,+ )+ self.assert_close(kgl.compose_transformations(t01, t02), expected)++ def test_convention_transform_points_maps_frame1_to_frame0(self, device, dtype):+ t01, _ = self._fixture(device, dtype)+ points_1 = torch.tensor([[[1.0, 2.0, 3.0]]], device=device, dtype=dtype)+ # points_0 = R01 p1 + t01, generated in float64 as (T01 @ [1, 2, 3, 1])[:3]; the inverse direction,+ # inv(T01) @ p1, is [-1.197, 4.338, -1.371]+ expected = torch.tensor(+ [[[2.8750110669009334, -2.3877063982284996, 5.5748771570489115]]], device=device, dtype=dtype+ )+ self.assert_close(kgl.transform_points(t01[None], points_1), expected)++ def test_convention_transform_points_projective_division(self, device, dtype):+ # A homography with a non-trivial last row: w = 0.1 * 2 + 2 = 2.2, and the result is (x, y) / w.+ trans = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.1, 0.0, 2.0]]], device=device, dtype=dtype)+ points = torch.tensor([[[2.0, 3.0]]], device=device, dtype=dtype)+ expected = torch.tensor([[[2.0 / 2.2, 3.0 / 2.2]]], device=device, dtype=dtype)+ self.assert_close(kgl.transform_points(trans, points), expected)++ def test_convention_inverse_transformation_assumes_rigid(self, device, dtype):+ t01, t02 = self._fixture(device, dtype)+ # A non-rigid matrix: the rotation block of T01 scaled by 2.+ m = t01.clone()+ m[:3, :3] = 2.0 * m[:3, :3]+ eye3 = torch.eye(3, device=device, dtype=dtype)+ # precondition: m is not rigid (M^T M = 4 I)+ assert (m[:3, :3].T @ m[:3, :3] - eye3).abs().max() > 1.0+ inv = kgl.inverse_transformation(m)+ # The rigid formula [M^T, -M^T t; 0, 1] is applied without validation: the rotation block is the transpose+ # to the bit, and the result is not the inverse of m (inv @ m = [4 I, ...], residual 3).+ assert torch.equal(inv[:3, :3], m[:3, :3].T)+ # generated in float64 as -(2 R01)^T t01+ expected_t = torch.tensor(+ [-1.7864533946821743, 2.4044880965764657, -6.778945795191922], device=device, dtype=dtype+ )+ self.assert_close(inv[:3, 3], expected_t)+ assert (inv @ m - torch.eye(4, device=device, dtype=dtype)).abs().max() > 1.0+ # relative_transformation inverts its first argument the same way, without validation.+ self.assert_close(kgl.relative_transformation(m, t02), inv @ t02)++ def test_convention_transform_helpers_read_the_top_three_rows(self, device, dtype):+ t01, t02 = self._fixture(device, dtype)+ # compose, relative and inverse read only the top three rows of each input and write [0, 0, 0, 1] as the+ # last row of the result, so a projective last row is used as if it were [0, 0, 0, 1].+ row = torch.tensor([0.1, -0.2, 0.05, 1.3], device=device, dtype=dtype)+ p02, p01 = t02.clone(), t01.clone()+ p02[3], p01[3] = row, row+ # precondition: the projective row changes the full product+ assert (t01 @ p02 - t01 @ t02).abs().max() > 0.5+ self.assert_close(kgl.compose_transformations(t01, p02), t01 @ t02)+ self.assert_close(kgl.relative_transformation(t01, p02), kgl.inverse_transformation(t01) @ t02)+ self.assert_close(kgl.inverse_transformation(p01), kgl.inverse_transformation(t01))++ def test_convention_relative_transformation_vs_relative_camera_motion(self, device, dtype):+ # Read as world-to-camera extrinsics E1 = T01, E2 = T02, relative_camera_motion returns E2 E1^-1, which is+ # relative_transformation(E2^-1, E1^-1) and not relative_transformation(E1, E2).+ e1, e2 = self._fixture(device, dtype)+ # generated in float64 as (T02 @ torch.linalg.inv(T01))[:3]+ expected = torch.tensor(+ [+ [0.9113903863880556, -0.4115258281569324, 0.0037491811348190907, -1.6575517215108124],+ [0.36878972792479336, 0.8207198555059045, 0.4363634441099808, 0.9011091069599761],+ [-0.18265185511400522, -0.39631478844236734, 0.8997626844258959, -3.311313297965872],+ ],+ device=device,+ dtype=dtype,+ )+ rot, t = kornia.geometry.epipolar.relative_camera_motion(+ e1[None, :3, :3], e1[None, :3, 3:], e2[None, :3, :3], e2[None, :3, 3:]+ )+ self.assert_close(torch.cat([rot, t], -1)[0], expected)+ inv_e1, inv_e2 = kgl.inverse_transformation(e1), kgl.inverse_transformation(e2)+ self.assert_close(kgl.relative_transformation(inv_e2, inv_e1)[:3], expected)+ # control: the same-order call is off by more than 1 on this pair+ assert (kgl.relative_transformation(e1, e2)[:3] - expected).abs().max() > 0.5++ def test_wart_point_line_distance_eps_bias_4881(self, device, dtype):+ # https://github.com/kornia/kornia/issues/4881: eps is added to the line norm,+ # |ax + by + c| / (||(a, b)|| + eps), so the distance depends on the scale of the line. The point (1.5, -0.7)+ # is 2.34 from 3x + 4y + 10 = 0 at every scale (11.7 / 5); at scale 1e-9 the norm is 5e-9 and the result is+ # 2.34 * 5 / 6 = 1.95 (-16.7 %).+ point = torch.tensor([[1.5, -0.7]], device=device, dtype=dtype)+ line = torch.tensor([[3.0, 4.0, 10.0]], device=device, dtype=dtype)+ exact = torch.tensor([2.34], device=device, dtype=dtype)+ self.assert_close(kgl.point_line_distance(point, line), exact)+ degenerate = kgl.point_line_distance(point, torch.tensor([[0.0, 0.0, 1.0]], device=device, dtype=dtype))+ zero_line = kgl.point_line_distance(point, torch.zeros(1, 3, device=device, dtype=dtype))+ if dtype == torch.float16:+ # The default eps=1e-9 rounds to zero in float16 (and a 1e-9-scaled line underflows), so the degenerate+ # line gives inf and the all-zero line 0 / 0 = nan.+ assert torch.isinf(degenerate).all() and torch.isnan(zero_line).all()+ return+ scaled = kgl.point_line_distance(point, 1e-9 * line)+ assert ((scaled - exact) / exact).max() < -0.1+ # A degenerate line (0, 0, 1) returns |c| / eps = 1e9 instead of flagging the singular case, and the all-zero+ # line returns 0 / eps = 0.+ assert torch.isfinite(degenerate).all() and (degenerate > 1e8).all()+ assert torch.equal(zero_line, torch.zeros_like(zero_line))diff --git a/tests/geometry/test_pose.py b/tests/geometry/test_pose.pyindex 993fe00f1..69f5ad4d1 100644--- a/tests/geometry/test_pose.py+++ b/tests/geometry/test_pose.py@@ -199,3 +199,120 @@ class TestNamedPose(BaseTester):shift_x = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)self.assert_close(points_in_b, (points_in_a + shift_x) @ rot_z.T, low_tolerance=low_tolerance)self.assert_close(a_from_b.transform_points(points_in_b), points_in_a, low_tolerance=low_tolerance)+++class TestNamedPoseConventions(BaseTester):+ @staticmethod+ def _poses(device, dtype):+ # Two rigid, non-commuting poses (M1 M2 != M2 M1 by 0.854), neither the identity nor a pure translation.+ g1 = Se3.exp(torch.tensor([1.0, -2.0, 3.0, 0.4, 0.2, -0.3], device=device, dtype=dtype))+ g2 = Se3.exp(torch.tensor([0.3, 0.1, -0.2, -0.1, 0.3, 0.05], device=device, dtype=dtype))+ m1, m2 = g1.matrix(), g2.matrix()+ assert (m1 @ m2 - m2 @ m1).abs().max() > 0.5+ eye = torch.eye(3, device=device, dtype=dtype)+ assert (m1[:3, :3] - eye).abs().max() > 0.1 and (m2[:3, :3] - eye).abs().max() > 0.1+ return g1, g2++ def test_convention_named_pose_composition_order(self, device, dtype):+ g1, g2 = self._poses(device, dtype)+ # The matrix product rule applies to unit rotations; Se3 accepts non-unit quaternions under #4942.+ self.assert_close(g1.r.q.norm(), torch.ones((), device=device, dtype=dtype))+ self.assert_close(g2.r.q.norm(), torch.ones((), device=device, dtype=dtype))+ b_from_a = NamedPose(g1, frame_src="a", frame_dst="b")+ c_from_b = NamedPose(g2, frame_src="b", frame_dst="c")+ # c_from_b * b_from_a is c_from_a, whose matrix is M2 @ M1; generated in float64 as+ # Se3.exp([0.3, 0.1, -0.2, -0.1, 0.3, 0.05]).matrix() @ Se3.exp([1.0, -2.0, 3.0, 0.4, 0.2, -0.3]).matrix()+ expected = torch.tensor(+ [+ [0.8365770733327115, 0.3564824932541303, 0.41600364466840206, 1.991550772972204],+ [-0.23936674171706684, 0.9208664847598445, -0.30774742924320647, -2.2686923473188667],+ [-0.4927903847822421, 0.15787700671524751, 0.85570584163999, 2.0241534574197697],+ [0.0, 0.0, 0.0, 1.0],+ ],+ device=device,+ dtype=dtype,+ )+ c_from_a = c_from_b * b_from_a+ assert (c_from_a.frame_src, c_from_a.frame_dst) == ("a", "c")+ self.assert_close(c_from_a.pose.matrix(), expected)+ # The source frame of the left operand must be the destination frame of the right one.+ with pytest.raises(ValueError, match="Cannot compose"):+ b_from_a * c_from_b++ def test_convention_named_pose_inverse_swaps_frames(self, device, dtype):+ g1, _ = self._poses(device, dtype)+ a_from_b = NamedPose(g1, frame_src="a", frame_dst="b").inverse()+ assert (a_from_b.frame_src, a_from_b.frame_dst) == ("b", "a")+ # generated in float64 as torch.linalg.inv(Se3.exp([1.0, -2.0, 3.0, 0.4, 0.2, -0.3]).matrix())+ expected = torch.tensor(+ [+ [0.9365557269934554, -0.24666617456316428, -0.2490364803841689, -0.893226697341087],+ [0.32475143364814213, 0.8779917826797222, 0.35166309998400447, 1.2022440482882328],+ [0.13190859175670216, -0.41022704429773776, 0.9023934261437778, -3.3894728975959616],+ [0.0, 0.0, 0.0, 1.0],+ ],+ device=device,+ dtype=dtype,+ )+ # half precision: the quaternion inverse and the matrix rebuild round twice (up to 0.7 of the default+ # half tolerance on this fixture)+ low = dtype in (torch.float16, torch.bfloat16)+ self.assert_close(a_from_b.pose.matrix(), expected, low_tolerance=low)++ def test_convention_named_pose_se2_composition_and_inverse(self, device, dtype):+ if dtype not in (torch.float32, torch.float64):+ pytest.skip(+ "torch.complex has no bfloat16 overload, and So2.inverse needs a ComplexHalf reciprocal the CPU lacks"+ )+ # The Se2 half of the block: two non-commuting planar poses (M1 M2 != M2 M1 by 0.611), neither the identity.+ g1 = Se2.exp(torch.tensor([0.5, -1.0, 0.3], device=device, dtype=dtype))+ g2 = Se2.exp(torch.tensor([-0.2, 0.4, -0.7], device=device, dtype=dtype))+ m1, m2 = g1.matrix(), g2.matrix()+ assert (m1 @ m2 - m2 @ m1).abs().max() > 0.5+ b_from_a = NamedPose(g1, frame_src="a", frame_dst="b")+ c_from_b = NamedPose(g2, frame_src="b", frame_dst="c")+ c_from_a = c_from_b * b_from_a+ assert (c_from_a.frame_src, c_from_a.frame_dst) == ("a", "c")+ # generated in float64 as Se2.exp([-0.2, 0.4, -0.7]).matrix() @ Se2.exp([0.5, -1.0, 0.3]).matrix()+ expected = torch.tensor(+ [+ [0.9210609940028851, 0.3894183423086504, -0.14575008421958802],+ [-0.3894183423086504, 0.9210609940028851, -0.6743834884300649],+ [0.0, 0.0, 1.0],+ ],+ device=device,+ dtype=dtype,+ )+ self.assert_close(c_from_a.pose.matrix(), expected)+ with pytest.raises(ValueError, match="Cannot compose"):+ b_from_a * c_from_b+ a_from_b = b_from_a.inverse()+ assert (a_from_b.frame_src, a_from_b.frame_dst) == ("b", "a")+ # generated in float64 as torch.linalg.inv(Se2.exp([0.5, -1.0, 0.3]).matrix())+ expected_inv = torch.tensor(+ [+ [0.955336489125606, 0.29552020666133955, -0.34365530818758616],+ [-0.29552020666133955, 0.9553364891256061, 1.0595065403284554],+ [0.0, 0.0, 1.0],+ ],+ device=device,+ dtype=dtype,+ )+ self.assert_close(a_from_b.pose.matrix(), expected_inv)++ def test_wart_named_pose_mixed_groups_4937(self, device, dtype):+ if dtype == torch.bfloat16:+ pytest.skip("torch.complex has no bfloat16 overload, so So2 (and an Se2 pose) cannot be built at all")+ # https://github.com/kornia/kornia/issues/4937: NamedPose validates no types. Composing an Se3 pose with an+ # Se2 pose fails inside the dispatch with an AttributeError; the ValueError branch meant for it is never+ # reached.+ g1, _ = self._poses(device, dtype)+ se2 = Se2.exp(torch.tensor([0.5, -1.0, 0.3], device=device, dtype=dtype))+ with pytest.raises(AttributeError):+ NamedPose(g1, frame_src="b", frame_dst="c") * NamedPose(se2, frame_src="a", frame_dst="b")+ with pytest.raises(AttributeError):+ NamedPose(se2, frame_src="b", frame_dst="c") * NamedPose(g1, frame_src="a", frame_dst="b")+ # A rotation-only group is accepted at construction, and its rotation then raises.+ so3_pose = NamedPose(So3.identity(device=device, dtype=dtype), frame_src="a", frame_dst="b")+ with pytest.raises(AttributeError):+ _ = so3_pose.rotation