π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(geometry): per-op Convention blocks for conversions (batch 3a: scalar, point & pixel-coordinate conversions) (#3942)
Dmytro Mishkin8454a81a3bd1
diff --git a/docs/source/geometry.conversions.rst b/docs/source/geometry.conversions.rstindex 1136d8254..0f8f233c3 100644--- a/docs/source/geometry.conversions.rst+++ b/docs/source/geometry.conversions.rst@@ -22,6 +22,7 @@ Coordinates.. autofunction:: convert_points_from_homogeneous.. autofunction:: convert_points_to_homogeneous.. autofunction:: convert_affinematrix_to_homography+.. autofunction:: convert_affinematrix_to_homography3d.. autofunction:: denormalize_pixel_coordinates.. autofunction:: normalize_pixel_coordinates.. autofunction:: denormalize_pixel_coordinates3ddiff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 67985b322..c8b11cf41 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -37,17 +37,25 @@ Coordinates and sizespoints. ``warp_perspective(img, M, dsize=(2, 8))`` produces a 2-row,8-column image.- Normalized coordinates, where used, are ``[-1, 1]`` in both axes,- identical to :func:`torch.nn.functional.grid_sample`.+ identical to :func:`torch.nn.functional.grid_sample` **called with**+ ``align_corners=True`` β not to its default, ``align_corners=False``,+ which places the same values up to half a pixel off β exactly half a+ pixel at the image borders, and identically at the image center.:func:`kornia.geometry.create_meshgrid` returns a normalized grid bydefault (``normalized_coordinates=True``).+- 3D grids and 3D pixel coordinates are ``(d, x, y)`` β depth first, not+ ``(x, y, z)``; :func:`kornia.geometry.grid.create_meshgrid3d` produces this+ order and the ``*_pixel_coordinates3d`` conversions consume it.Angles and rotations--------------------- Angles are **degrees** in the 2D image APIs (``rotate``,- ``get_rotation_matrix2d``, ``RandomRotation``), and **radians** in the- 3D/conversion APIs (``axis_angle_to_rotation_matrix``, ``So3``;- ``rad2deg``/``deg2rad`` exist to convert).+ ``get_rotation_matrix2d``, ``RandomRotation``,+ ``angle_to_rotation_matrix``), and **radians** in the 3D+ rotation-representation APIs (``axis_angle_to_rotation_matrix``, ``So3``)+ and in the polar conversions ``cart2pol``/``pol2cart``+ (``rad2deg``/``deg2rad`` exist to convert).- 2D image rotations: positive angle rotates **counter-clockwise asdisplayed** (top-left origin, matching OpenCV):diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 7a73ec77a..3abd00c1f 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -79,6 +79,24 @@ __all__ = [def rad2deg(tensor: torch.Tensor) -> torch.Tensor:r"""Convert angles from radians to degrees.+ Convention:+ - the input is in **radians** and the output in **degrees**; the+ conversion is elementwise and preserves shape, device and float dtype++ .. warning::+ Two distinct defects, tracked in+ `#3937 <https://github.com/kornia/kornia/issues/3937>`_. A ``float64``+ input is left with only about seven correct significant digits+ (``rad2deg(torch.tensor(math.pi, dtype=torch.float64)) - 180`` is+ ``-5.0e-06``, not ``0``) because ``kornia.constants.pi`` is a+ **float32** tensor β a defect in the constant itself, which several+ other kornia modules also consume (the issue tracks the current+ inventory). Separately, ``rad2deg``/``deg2rad``+ themselves cast that constant to the input dtype, so an integer input+ truncates ``pi`` to ``3``: ``rad2deg(torch.tensor([1, 2, 3]))`` returns+ ``[60., 120., 180.]`` instead of ``[57.2958, 114.5916, 171.8873]``, and+ a ``float64`` constant alone would not fix it.+Args:tensor: torch.Tensor of arbitrary shape.@@ -100,6 +118,18 @@ def rad2deg(tensor: torch.Tensor) -> torch.Tensor:def deg2rad(tensor: torch.Tensor) -> torch.Tensor:r"""Convert angles from degrees to radians.+ Convention:+ - the input is in **degrees** and the output in **radians**; it+ performs the opposite conversion to+ :func:`~kornia.geometry.conversions.rad2deg`++ .. warning::+ Inherits both defects of :func:`~kornia.geometry.conversions.rad2deg`+ β the float32 ``kornia.constants.pi`` and the cast to the input dtype+ (``deg2rad(torch.tensor([180, 90]))`` returns ``[3.0000, 1.5000]``).+ See its warning and+ `#3937 <https://github.com/kornia/kornia/issues/3937>`_.+Args:tensor: torch.Tensor of arbitrary shape.@@ -121,6 +151,14 @@ def deg2rad(tensor: torch.Tensor) -> torch.Tensor:def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:r"""Convert polar coordinates to cartesian coordinates.+ Convention:+ - the arguments are ``(rho, phi)`` and the return is the tuple+ ``(x, y)``, with ``x = rho * cos(phi)`` and ``y = rho * sin(phi)``:+ ``rho = 5``, ``phi = atan2(4, 3)`` gives ``(3., 4.)``+ - ``phi`` is in **radians** (``rho = 2``, ``phi = pi / 6`` gives+ ``(1.7321, 1.)``) and follows the angle convention documented on+ :func:`~kornia.geometry.conversions.cart2pol`+Args:rho: torch.Tensor of arbitrary shape.phi: torch.Tensor of same arbitrary shape.@@ -144,12 +182,49 @@ def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> tuple[torch.Tensor, torch.def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1.0e-8) -> tuple[torch.Tensor, torch.Tensor]:- """Convert cartesian coordinates to polar coordinates.+ r"""Convert cartesian coordinates to polar coordinates.++ Convention:+ - the arguments are ``(x, y)`` and the return is the tuple+ ``(rho, phi)``: ``(3., 4.)`` gives ``(5., 0.9273)``+ - ``phi`` is ``atan2(y, x)`` in **radians**, so it lies in+ :math:`[-\pi, \pi]`, is ``0`` on the ``+x`` axis and grows toward+ ``+y`` (``x = 0``, ``y = 1`` gives ``phi = 1.5708``). Both endpoints+ are attained on the ``-x`` axis, where the sign of ``y``'s zero+ decides between ``-pi`` and ``+pi``+ - kornia's image ``y`` axis points down, so a growing ``phi`` turns+ **clockwise as displayed**. The relation to the other 2-D+ angle op is the opposite sense: applying+ ``angle_to_rotation_matrix(theta)`` to a nonzero point *decreases*+ that point's ``phi`` by ``theta`` degrees **modulo** :math:`2\pi` β+ the result is re-wrapped into :math:`[-\pi, \pi]`, so a point at+ ``phi = -170`` degrees rotated by ``theta = 30`` returns+ ``phi = +160``, not ``-200``. At the origin ``phi`` carries no+ direction and the relation does not apply+ - ``rho`` is ``sqrt(x ** 2 + y ** 2 + eps)``, not+ ``sqrt(x ** 2 + y ** 2)`` β see the warning below++ .. warning::+ ``eps`` is added *inside* the square root, so the expression evaluated+ is ``sqrt(x ** 2 + y ** 2 + eps)`` and ``rho`` is biased high. Whether+ that bias survives the rounding of the working dtype depends on where+ it is measured. Away from the origin it is usually invisible:+ ``cart2pol(3., 4.)`` returns ``5.000000001`` in ``float64`` but rounds+ back to exactly ``5.`` in ``float32`` and ``float16``. At the origin it+ is the whole answer: ``cart2pol(torch.tensor(0.), torch.tensor(0.))``+ returns ``rho = 9.9999997e-05`` in ``float32`` and ``1e-04`` in+ ``float64`` rather than ``0`` (in ``float16``, ``eps`` underflows the+ sum and ``rho`` is ``0.``). Tracked in+ `#3939 <https://github.com/kornia/kornia/issues/3939>`_.Args:x: torch.Tensor of arbitrary shape.y: torch.Tensor of same arbitrary shape.- eps: To avoid division by zero.+ eps: added inside the square root when computing ``rho``. A positive+ ``eps`` that is representable in the working dtype keeps the+ gradient of ``rho`` finite at the origin, where it is ``nan`` with+ ``eps=0``. The default ``1e-8`` underflows in ``float16`` (see the+ warning above), so there the origin gradient is still ``nan``.Returns:- rho: torch.Tensor with same shape as input.@@ -172,12 +247,41 @@ def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1.0e-8) -> tuple[tordef convert_points_from_homogeneous(points: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:r"""Convert points from homogeneous to Euclidean space.+ Convention:+ - the **last** component of the last dimension is the homogeneous+ coordinate ``w`` and is dropped from the output+ - requires rank :math:`\geq 2`: a bare :math:`(D,)` point raises+ ``ValueError``+ - when ``abs(w) > eps`` the remaining components are divided by ``w``+ with its sign kept (``[[2., 4., -2.]]`` gives ``[[-1., -2.]]``), up to+ the bias described in the warning below+ - when ``abs(w) <= eps`` (default ``eps = 1e-8``; the test is a strict+ ``>``) the numerator is instead returned **unchanged**, following+ OpenCV: ``[[2., 4., 0.]]`` gives ``[[2., 4.]]``++ .. warning::+ The division is by ``w + eps`` rather than by ``w``, and ``eps`` is+ added without regard to the sign of ``w``, so the **signed** relative+ error of the result is exactly ``-eps / (w + eps)``. At ``w = 2e-8``+ that is ``-1/3``: the exact result ``[1e8, 2e8]`` comes out as+ ``[6.67e7, 1.33e8]`` (33 % low). At ``w = -2e-8`` it is ``+1``:+ ``[-1e8, -2e8]`` comes out as ``[-2e8, -4e8]`` (100 % high). Only for+ ``abs(w)`` much larger than ``eps`` does it reduce to the familiar+ ``-eps / w``, and there it is usually below the rounding of the working+ dtype β at ``w = 2`` the measured error is ``-5.0e-09`` in ``float64``,+ while in ``float32`` ``2 + eps`` rounds back to ``2`` and the result is+ exact. The numbers above assume ``eps`` is representable: in+ ``float16`` both the default ``eps`` and ``w = 2e-8`` underflow to+ ``0``, so ``[[2., 4., 2e-8]]`` takes the ``abs(w) <= eps`` pass-through+ branch and returns ``[[2., 4.]]``. Tracked in+ `#3938 <https://github.com/kornia/kornia/issues/3938>`_.+Args:- points: the points to be transformed of shape :math:`(B, N, D)`.+ points: the points to be transformed of shape :math:`(*, N, D)`.eps: to avoid division by zero.Returns:- the points in Euclidean space :math:`(B, N, D-1)`.+ the points in Euclidean space :math:`(*, N, D-1)`.Examples:>>> input = torch.tensor([[0., 0., 1.]])@@ -206,6 +310,15 @@ def convert_points_from_homogeneous(points: torch.Tensor, eps: float = 1e-8) ->def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:r"""Convert points from Euclidean to homogeneous space.+ Convention:+ - appends the constant ``1`` as the **last** component of the last+ dimension, which is where+ :func:`~kornia.geometry.conversions.convert_points_from_homogeneous`+ expects it+ - requires rank :math:`\geq 2`: a bare :math:`(D,)` point raises+ ``ValueError``+ - the input dtype is preserved, integer dtypes included+Args:points: the points to be transformed with shape :math:`(*, N, D)`.@@ -235,6 +348,12 @@ def _convert_affinematrix_to_homography_impl(A: torch.Tensor) -> torch.Tensor:def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:r"""Convert batch of affine matrices.+ Convention:+ - appends the row ``[0, 0, 1]`` at the bottom and copies the+ :math:`2 \times 3` block verbatim; the input tensor is not modified+ - the rank is enforced to be exactly 3, so batching is **mandatory**: an+ unbatched :math:`(2, 3)` matrix raises ``ValueError``+Args:A: the affine matrix with shape :math:`(B,2,3)`.@@ -262,6 +381,12 @@ def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:r"""Convert batch of 3d affine matrices.+ Convention:+ - same as+ :func:`~kornia.geometry.conversions.convert_affinematrix_to_homography`,+ except that ``A`` is :math:`(B, 3, 4)` and the appended bottom row is+ ``[0, 0, 0, 1]``+Args:A: the affine matrix with shape :math:`(B,3,4)`.@@ -894,14 +1019,39 @@ def quaternion_from_euler(def normalize_pixel_coordinates(pixel_coordinates: torch.Tensor, height: int, width: int, eps: float = 1e-8) -> torch.Tensor:- r"""Normalize pixel coordinates between -1 and 1.-- Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).+ r"""Map pixel coordinates so that the first and last pixel of each axis become -1 and 1.++ Convention:+ - ``pixel_coordinates`` is :math:`(*, 2)` in ``(x, y)`` order: ``x``+ indexes columns and is scaled by ``width``, ``y`` indexes rows and is+ scaled by ``height``. The positional argument order is the other way+ round β ``(pixel_coordinates, height, width)``+ - the mapping is **corner-aligned**,+ ``x_norm = 2 * x / (width - 1) - 1``: for ``width = 4`` the columns+ ``0``, ``1``, ``3`` map to ``-1``, ``-1/3``, ``+1``. This is the+ ``align_corners=True`` convention;+ :func:`torch.nn.functional.grid_sample` at its default+ ``align_corners=False`` would instead place the first and last of+ those values at pixels ``-0.5`` and ``3.5`` β half a pixel outside+ the image on each side β so ``align_corners=True`` must be passed+ explicitly when feeding this output to it. Note that kornia's own+ :func:`~kornia.geometry.transform.remap` resolves+ ``align_corners=None`` to ``False``+ - the output is **not** clamped: coordinates outside the image+ extrapolate linearly past ``[-1, 1]``, as the example below shows++ .. warning::+ ``height`` and ``width`` are not validated. For a degenerate size (``1``,+ ``0`` or negative) the denominator ``size - 1`` is clamped up to ``eps``,+ so+ ``normalize_pixel_coordinates(torch.tensor([[1., 1.]], dtype=torch.float64), 1, 1)``+ silently returns ``[[199999999.0, 199999999.0]]`` instead of raising.+ Tracked in `#3940 <https://github.com/kornia/kornia/issues/3940>`_.Args:pixel_coordinates: the grid with pixel coordinates. Shape can be :math:`(*, 2)`.- width: the maximum width in the x-axis.height: the maximum height in the y-axis.+ width: the maximum width in the x-axis.eps: safe division by zero.Return:@@ -938,10 +1088,29 @@ def denormalize_pixel_coordinates(The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1).+ Convention:+ - the inverse of+ :func:`~kornia.geometry.conversions.normalize_pixel_coordinates`,+ ``x = (width - 1) * (x_norm + 1) / 2``, with the same ``(x, y)``+ component order and the same ``(pixel_coordinates, height, width)``+ positional order++ .. warning::+ For a degenerate ``height``/``width`` (``1``, ``0`` or negative) the+ clamped denominator collapses that component instead of exploding it:+ ``denormalize_pixel_coordinates(torch.tensor([[0., 0.]], dtype=torch.float64), 4, 1)``+ returns ``[[5e-09, 1.5]]``. This clamp is the exact reciprocal of the one+ in :func:`~kornia.geometry.conversions.normalize_pixel_coordinates`, so a+ normalize-then-denormalize round trip returns the input as long as the+ normalized value is finite β in ``float16`` ``eps`` underflows, the+ normalized component is ``inf`` and the round trip returns ``nan``; it+ is a single call on its own that is wrong. Tracked in+ `#3940 <https://github.com/kornia/kornia/issues/3940>`_.+Args:pixel_coordinates: the normalized grid coordinates. Shape can be :math:`(*, 2)`.- width: the maximum width in the x-axis.height: the maximum height in the y-axis.+ width: the maximum width in the x-axis.eps: safe division by zero.Return:@@ -970,9 +1139,26 @@ def denormalize_pixel_coordinates(def normalize_pixel_coordinates3d(pixel_coordinates: torch.Tensor, depth: int, height: int, width: int, eps: float = 1e-8) -> torch.Tensor:- r"""Normalize pixel coordinates between -1 and 1.-- Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).+ r"""Map 3d pixel coordinates so that the first and last sample of each axis become -1 and 1.++ Convention:+ - ``pixel_coordinates`` is :math:`(*, 3)` in ``(d, x, y)`` order β+ **depth first, then x, then y**, *not* ``(x, y, z)``. This is the+ order :func:`~kornia.geometry.grid.create_meshgrid3d` produces. The+ three components are scaled by ``depth - 1``, ``width - 1`` and+ ``height - 1`` respectively, so with ``depth=3, height=5, width=9``+ the coordinate ``[2., 8., 4.]`` maps to ``[1., 1., 1.]``+ - the positional argument order is+ ``(pixel_coordinates, depth, height, width)``+ - corner-aligned and unclamped in each axis exactly as in+ :func:`~kornia.geometry.conversions.normalize_pixel_coordinates`++ .. warning::+ ``depth``, ``height`` and ``width`` are not validated; a degenerate size+ (``1``, ``0`` or negative) clamps that axis' denominator up to ``eps``+ and blows the corresponding component up by a factor of ``2e8``+ (``inf`` in ``float16``, where ``eps`` underflows). Tracked+ in `#3940 <https://github.com/kornia/kornia/issues/3940>`_.Args:pixel_coordinates: the grid with pixel coordinates. Shape can be :math:`(*, 3)`.@@ -1002,13 +1188,28 @@ def normalize_pixel_coordinates3d(def denormalize_pixel_coordinates3d(pixel_coordinates: torch.Tensor, depth: int, height: int, width: int, eps: float = 1e-8) -> torch.Tensor:- r"""Denormalize pixel coordinates.-- The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1).+ r"""Denormalize 3d pixel coordinates.++ Convention:+ - the inverse of+ :func:`~kornia.geometry.conversions.normalize_pixel_coordinates3d`,+ with the same ``(d, x, y)`` component order and the same+ ``(pixel_coordinates, depth, height, width)`` positional order: with+ ``depth=3, height=5, width=9`` the input ``[0., 0., 0.]`` maps back to+ ``[1., 4., 2.]``++ .. warning::+ For a degenerate ``depth``/``height``/``width`` (``1``, ``0`` or+ negative) the clamped denominator scales that component by ``5e-09``+ (``0`` in ``float16``, where ``eps`` underflows) instead of by+ ``(size - 1) / 2`` β the same reciprocal-clamp behavior as+ :func:`~kornia.geometry.conversions.denormalize_pixel_coordinates`,+ whose warning walks through the round trip. Tracked in+ `#3940 <https://github.com/kornia/kornia/issues/3940>`_.Args:pixel_coordinates: the normalized grid coordinates. Shape can be :math:`(*, 3)`.- depth: the maximum depth in the x-axis.+ depth: the maximum depth in the z-axis.height: the maximum height in the y-axis.width: the maximum width in the x-axis.eps: safe division by zero.@@ -1034,6 +1235,25 @@ def denormalize_pixel_coordinates3d(def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:r"""Create a rotation matrix out of angles in degrees.+ Convention:+ - ``angle`` is in **degrees**, shape :math:`(*)` in and+ :math:`(*, 2, 2)` out+ - the matrix is ``[[cos, sin], [-sin, cos]]`` with ``det = +1``; for+ ``angle = 30`` it is ``[[0.8660, 0.5000], [-0.5000, 0.8660]]``+ - applied on the left to a column vector ``(x, y)``, ``angle = 30`` maps+ ``(1., 0.)`` to ``(0.8660, -0.5000)`` β counter-clockwise **as+ displayed** under kornia's y-down image axes. In the raw coordinate+ plane this is the opposite sense to+ :func:`~kornia.geometry.conversions.cart2pol`, whose Convention block+ spells out the modulo-:math:`2\pi` relation between the two ops++ .. warning::+ The degrees-to-radians step is+ :func:`~kornia.geometry.conversions.deg2rad`, so it inherits both+ defects of :func:`~kornia.geometry.conversions.rad2deg` β the float32+ ``kornia.constants.pi`` and the cast to the input dtype. See its+ warning and `#3937 <https://github.com/kornia/kornia/issues/3937>`_.+Args:angle: tensor of angles in degrees, any shape :math:`(*)`.@@ -1241,13 +1461,24 @@ def normalize_homography3d(def normalize_points_with_intrinsics(point_2d: torch.Tensor, camera_matrix: torch.Tensor) -> torch.Tensor:"""Normalize points with intrinsics. Useful for conversion of keypoints to be used with essential matrix.+ Convention:+ - ``point_2d`` is :math:`(*, 2)` in pixel ``(u, v)`` order and+ ``camera_matrix`` is a row-major pinhole :math:`(*, 3, 3)` with+ ``fx = K[0, 0]``, ``fy = K[1, 1]``, ``cx = K[0, 2]``, ``cy = K[1, 2]``+ - the output is the calibrated camera coordinate+ ``x = (u - cx) / fx``, ``y = (v - cy) / fy``: with+ ``K = [[100., 0., 320.], [0., 200., 240.], [0., 0., 1.]]`` the pixel+ ``(420., 440.)`` maps to ``(1., 1.)``+ - the skew entry ``K[0, 1]`` is **ignored**; only the two diagonal+ entries and the ``[:2, 2]`` column are read+Args:point_2d: tensor containing the 2d points in the image pixel coordinates. The shape of the tensor can be:math:`(*, 2)`.camera_matrix: tensor containing the intrinsics camera matrix. The tensor shape must be :math:`(*, 3, 3)`.Returns:- tensor of (u, v) cam coordinates with shape :math:`(*, 2)`.+ tensor of normalized camera coordinates :math:`(x, y)` with shape :math:`(*, 2)`.Example:>>> _ = torch.manual_seed(0)@@ -1273,15 +1504,22 @@ def normalize_points_with_intrinsics(point_2d: torch.Tensor, camera_matrix: torcdef denormalize_points_with_intrinsics(point_2d_norm: torch.Tensor, camera_matrix: torch.Tensor) -> torch.Tensor:- """Normalize points with intrinsics. Useful for conversion of keypoints to be used with essential matrix.+ """Denormalize points with intrinsics. Useful for converting normalized camera points back to pixels.++ Convention:+ - the inverse of+ :func:`~kornia.geometry.conversions.normalize_points_with_intrinsics`,+ which documents the ``K`` layout: ``u = x * fx + cx`` and+ ``v = y * fy + cy``, and the skew entry ``K[0, 1]`` is ignored here+ tooArgs:- point_2d_norm: tensor containing the 2d points in the image pixel coordinates. The shape of the tensor can be- :math:`(*, 2)`.+ point_2d_norm: tensor containing the 2d points in normalized camera coordinates. The shape of the tensor can+ be :math:`(*, 2)`.camera_matrix: tensor containing the intrinsics camera matrix. The tensor shape must be :math:`(*, 3, 3)`.Returns:- tensor of (u, v) cam coordinates with shape :math:`(*, 2)`.+ tensor of :math:`(u, v)` pixel coordinates with shape :math:`(*, 2)`.Example:>>> _ = torch.manual_seed(0)@@ -1578,11 +1816,19 @@ def vector_to_skew_symmetric_matrix(vec: torch.Tensor) -> torch.Tensor:v3 & 0 & -v1 \\-v2 & v1 & 0\end{bmatrix}+ Convention:+ - the matrix acts on the left as the first cross-product factor:+ ``vector_to_skew_symmetric_matrix(v) @ x`` equals ``cross(v, x)``, not+ its negation β for ``v = (1., 2., 3.)`` and ``x = (4., 5., 6.)`` both+ are ``(-3., 6., -3.)``+ - accepts :math:`(3,)` or :math:`(B, 3)` only; any higher rank raises+ ``ValueError``+Args:- vec: tensor of shape :math:`(B, 3)`.+ vec: tensor of shape :math:`(3,)` or :math:`(B, 3)`.Returns:- tensor of shape :math:`(B, 3, 3)`.+ tensor of shape :math:`(3, 3)` or :math:`(B, 3, 3)` respectively.Example:>>> vec = torch.tensor([1.0, 2.0, 3.0])diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex 92ae7d81c..827836370 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -15,6 +15,7 @@# limitations under the License.#+import inspectimport sysfrom functools import partial@@ -601,6 +602,107 @@ class TestRadDegConversions(BaseTester):x_deg = 180.0 * torch.rand(batch_shape, device=device, dtype=torch.float64)self.gradcheck(kornia.geometry.conversions.deg2rad, (x_deg,))+ @pytest.mark.xfail(+ raises=AssertionError,+ reason="kornia.constants.pi is float32, so f64 loses ~7 digits (angle_to_rotation_matrix "+ "inherits it via deg2rad) β kornia#3937",+ strict=True,+ )+ @pytest.mark.parametrize(+ ("op_name", "arg", "expected"),+ [+ ("rad2deg", torch.pi, 180.0),+ ("deg2rad", 180.0, torch.pi),+ ("angle_to_rotation_matrix", 90.0, [[0.0, 1.0], [-1.0, 0.0]]),+ ],+ )+ def test_convention_float64_results_are_exact_3937(self, device, op_name, arg, expected):+ # Intended behavior: each op is exact to the precision of its input dtype, like+ # torch.rad2deg / torch.deg2rad; angle_to_rotation_matrix(90) is then the exact quarter+ # turn. It is not: all three multiply by kornia.constants.pi, a *float32* tensor merely+ # cast to the input dtype, so a float64 input carries a systematic ~2.8e-8 relative+ # error (#3937). float64 is hardcoded (like test_rad2deg_gradcheck above) because at+ # float32 the biased constant *is* the correctly rounded pi; MPS is skipped visibly+ # below because it has no float64 at all, so without the skip the xfail would be+ # satisfied by a TypeError instead of the precision assert it documents (hence also+ # raises=AssertionError on the mark). Marked xfail(strict=True) so fixing #3937 makes+ # every case XPASS and forces this mark out β a one-place edit.+ # Snippet used to generate expected (stdlib + torch):+ # math.degrees(math.pi) == 180.0 and (180.0 * math.pi) / 180.0 == math.pi exactly+ # kornia rad2deg(tensor(pi, f64)).item() -> 179.99999499104382+ # kornia deg2rad(tensor(180., f64)).item() -> 3.1415927410125732 (math.pi + 8.7e-08)+ # kornia angle_to_rotation_matrix(tensor(90., f64)).flatten().tolist() ->+ # [-4.371139000186241e-08, 0.999999999999999, -0.999999999999999, -4.371139e-08]+ # atol/rtol 1e-12 sits between the current ~4.4e-8 cosine error and the 6.123234e-17+ # an unbiased constant would give.+ if device.type == "mps":+ pytest.skip("MPS has no float64, and this pin is float64-only by construction")++ op = getattr(kornia.geometry.conversions, op_name)++ out = op(torch.tensor(arg, device=device, dtype=torch.float64))++ self.assert_close(out, torch.tensor(expected, device=device, dtype=torch.float64), atol=1e-12, rtol=1e-12)++ def test_convention_angle_to_rotation_matrix_takes_degrees(self, device, dtype):+ # Convention pin: angle_to_rotation_matrix reads its argument in DEGREES (not radians)+ # and returns [[cos, sin], [-sin, cos]] -- the transpose of the textbook math-frame CCW+ # matrix. Pinned on a small non-symmetric angle so a sign flip on the off-diagonal is+ # caught.+ # Snippet used to generate expected (stdlib only):+ # import math+ # c, s = math.cos(math.radians(30.0)), math.sin(math.radians(30.0))+ # [[c, s], [-s, c]] -> [[0.8660254037844387, 0.49999999999999994],+ # [-0.49999999999999994, 0.8660254037844387]]+ out = kornia.geometry.conversions.angle_to_rotation_matrix(torch.tensor(30.0, device=device, dtype=dtype))+ expected = torch.tensor([[0.8660254, 0.5], [-0.5, 0.8660254]], device=device, dtype=dtype)+ self.assert_close(out, expected)++ # A radian-reading implementation would turn pi/2 into the quarter turn [[0, 1], [-1, 0]];+ # this one reads pi/2 as 1.5708 *degrees* and returns a near-identity matrix instead.+ # Snippet used to generate expected:+ # c, s = math.cos(math.radians(math.pi / 2)), math.sin(math.radians(math.pi / 2))+ # [[c, s], [-s, c]] -> [[0.9996242168385687, 0.027412134354665284], ...]+ out_rad = kornia.geometry.conversions.angle_to_rotation_matrix(+ torch.tensor(torch.pi / 2, device=device, dtype=dtype)+ )+ expected_rad = torch.tensor([[0.99962422, 0.02741213], [-0.02741213, 0.99962422]], device=device, dtype=dtype)+ self.assert_close(out_rad, expected_rad)++ @pytest.mark.parametrize(+ ("op_name", "arg", "expected"),+ [+ ("rad2deg", [1, 2, 3], [60.0, 120.0, 180.0]),+ ("deg2rad", [180, 90], [3.0, 1.5]),+ ("angle_to_rotation_matrix", [90], [[[0.07073720, 0.99749500], [-0.99749500, 0.07073720]]]),+ ],+ )+ def test_wart_integer_input_truncates_pi_to_3_3937(self, device, op_name, arg, expected):+ # Wart pins for #3937: assert the CURRENT broken outputs the docstring warnings document.+ # kornia.constants.pi is cast to the *integer* input dtype and truncates to 3, so rad2deg+ # divides by 3, deg2rad multiplies by 3 (90 degrees -> 1.5 radians), and the downstream+ # angle_to_rotation_matrix([90]) is nowhere near the quarter turn. If a case fails, #3937+ # was (partly) fixed -- update or remove the warnings in rad2deg, deg2rad and+ # angle_to_rotation_matrix and flip/remove the strict xfail above. NOT a contract that+ # int inputs must keep these values: what they *should* do (promote to float like+ # torch.rad2deg, or raise) is a maintainer decision, and a strict xfail asserting the+ # promoted-float answer would stay silently XFAIL forever if the fix chose to raise;+ # a wart pin flips loudly under either polarity.+ # Snippet used to generate expected (torch only):+ # kornia rad2deg(torch.tensor([1, 2, 3])) -> tensor([ 60., 120., 180.]), dtype float32+ # (torch.rad2deg gives [ 57.2958, 114.5916, 171.8873])+ # kornia deg2rad(torch.tensor([180, 90])) -> tensor([3.0000, 1.5000]), dtype float32+ # (torch.deg2rad gives [3.1416, 1.5708])+ # kornia angle_to_rotation_matrix(torch.tensor([90])).flatten().tolist() ->+ # [0.07073719799518585, 0.9974949955940247, -0.9974949955940247, 0.07073719799518585]+ # (math.cos(1.5), math.sin(1.5) -> (0.0707372016677029, 0.9974949866040544))+ op = getattr(kornia.geometry.conversions, op_name)++ out = op(torch.tensor(arg, device=device))++ assert out.dtype == torch.float32+ self.assert_close(out, torch.tensor(expected, device=device, dtype=torch.float32), atol=1e-4, rtol=1e-4)+class TestPolCartConversions(BaseTester):def test_smoke(self, device, dtype):@@ -645,10 +747,150 @@ class TestPolCartConversions(BaseTester):self.assert_close(x, x_cart2pol)self.assert_close(y, y_cart2pol)+ def test_convention_pol2cart_takes_rho_phi_returns_x_y(self, device, dtype):+ # Convention pin: pol2cart's argument order is (rho, phi) and its return order is+ # (x, y), with phi in RADIANS measured from the +x axis: x = rho*cos(phi),+ # y = rho*sin(phi). The literal is deliberately off-axis (3 != 4) so that swapping+ # either the arguments or the returns is caught.+ # Snippet used to generate expected (stdlib only):+ # import math+ # phi = math.atan2(4.0, 3.0) # 0.9272952180016122 rad+ # 5.0 * math.cos(phi), 5.0 * math.sin(phi) -> (3.0000000000000004, 4.0)+ rho = torch.tensor(5.0, device=device, dtype=dtype)+ phi = torch.tensor(0.9272952180016122, device=device, dtype=dtype)++ x, y = kornia.geometry.conversions.pol2cart(rho, phi)++ self.assert_close(x, torch.tensor(3.0, device=device, dtype=dtype))+ self.assert_close(y, torch.tensor(4.0, device=device, dtype=dtype))++ def test_convention_cart2pol_takes_x_y_and_phi_is_atan2_y_x(self, device, dtype):+ # Convention pin: cart2pol's argument order is (x, y) and its return order is+ # (rho, phi), with phi = atan2(y, x) in radians -- zero on the +x axis and increasing+ # toward +y (which is clockwise *as displayed* under kornia's y-down image axes).+ # Snippet used to generate expected (stdlib only):+ # import math+ # math.hypot(3.0, 4.0), math.atan2(4.0, 3.0) -> (5.0, 0.9272952180016122)+ # math.atan2(1.0, 0.0) -> 1.5707963267948966 (atan2(x, y) would give 0.0 here)+ rho, phi = kornia.geometry.conversions.cart2pol(+ torch.tensor(3.0, device=device, dtype=dtype), torch.tensor(4.0, device=device, dtype=dtype)+ )+ self.assert_close(rho, torch.tensor(5.0, device=device, dtype=dtype))+ self.assert_close(phi, torch.tensor(0.9272952180016122, device=device, dtype=dtype))++ phi_y_axis = kornia.geometry.conversions.cart2pol(+ torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)+ )[1]+ self.assert_close(phi_y_axis, torch.tensor(1.5707963267948966, device=device, dtype=dtype))++ @pytest.mark.xfail(+ raises=AssertionError,+ reason="cart2pol returns sqrt(x**2 + y**2 + eps), biasing rho β kornia#3939",+ strict=True,+ )+ def test_convention_cart2pol_rho_is_the_exact_radius(self, device, dtype):+ # Intended behavior: rho is the Euclidean radius, so rho(0, 0) == 0. It currently is+ # not: eps is added *inside* the sqrt, so rho = sqrt(x**2 + y**2 + eps) and the origin+ # maps to sqrt(1e-8) = 1e-4 (see #3939; eps belongs in the gradient path, not the+ # value). Marked xfail(strict=True) so fixing #3939 makes this XPASS loudly.+ # Snippet used to generate expected (stdlib only):+ # math.hypot(0.0, 0.0) -> 0.0 ; kornia cart2pol(0., 0.)[0].item() -> 0.0001+ if dtype == torch.float16:+ pytest.skip("float16 cannot represent the default eps=1e-8, so the bias is invisible there")++ rho = kornia.geometry.conversions.cart2pol(+ torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(0.0, device=device, dtype=dtype)+ )[0]+ self.assert_close(rho, torch.tensor(0.0, device=device, dtype=dtype), atol=1e-6, rtol=0.0)++ def test_wart_rho_is_biased_by_eps_inside_the_sqrt_3939(self, device, dtype):+ # Wart pin for kornia#3939, companion to the strict xfail above: assert the CURRENT+ # biased rho. The xfail pins the intended rho(0, 0) == 0 but cannot flip under every fix+ # polarity -- the equally standard sqrt(clamp(x**2 + y**2, min=eps)) (the shape+ # normalize_pixel_coordinates already uses) also returns 1e-4 at the origin, leaving the+ # mark silently XFAIL with a stale reason string. So two cells are pinned: the origin,+ # rho = sqrt(eps) = 1e-4, which flips under a grad-only eps (rho 0) and under eps**2+ # inside the sqrt (rho 1e-8); and a sub-eps point x = 5e-5, whose x**2 = 2.5e-9 < eps+ # gives rho = sqrt(1.25e-8) ~ 1.118e-4, which additionally flips under the clamp shape+ # (rho 1e-4, 10.6 % below, outside rtol 1e-2). If either assert fails, #3939 was+ # (partly) fixed -- update or remove the warning in cart2pol and flip/remove the strict+ # xfail above. eps=1e-8 is passed explicitly so the pinned literals do not silently+ # track a later change to the default.+ # Snippet used to generate expected (torch only, executed at each pinned dtype):+ # c2p = kornia.geometry.conversions.cart2pol+ # c2p(torch.tensor(0., dtype=torch.float64), torch.tensor(0., dtype=torch.float64),+ # eps=1e-8)[0] -> 0.0001 (f32: 9.999999747378752e-05)+ # c2p(torch.tensor(5e-5, dtype=torch.float64), torch.tensor(0., dtype=torch.float64),+ # eps=1e-8)[0] -> 0.00011180339887498949 (f32: 0.00011180339788552374)+ # At bfloat16 the outputs land within 0.3 % of the literals (1.00136e-4, 1.12057e-4),+ # inside rtol 1e-2, so the pin holds there too.+ if dtype == torch.float16:+ pytest.skip("float16 cannot represent eps=1e-8, so rho is 0 at both pinned points and the bias invisible")++ zero = torch.tensor(0.0, device=device, dtype=dtype)++ rho_origin = kornia.geometry.conversions.cart2pol(zero, zero, eps=1e-8)[0]+ rho_sub_eps = kornia.geometry.conversions.cart2pol(+ torch.tensor(5e-5, device=device, dtype=dtype), zero, eps=1e-8+ )[0]++ self.assert_close(rho_origin, torch.tensor(1e-4, device=device, dtype=dtype), atol=0.0, rtol=1e-2)+ self.assert_close(+ rho_sub_eps, torch.tensor(1.1180339887498949e-4, device=device, dtype=dtype), atol=0.0, rtol=1e-2+ )++ def test_convention_positive_rotation_decreases_cart2pol_phi(self, device, dtype):+ # Cross-symbol convention pin: enforces the opposite-sense relation between+ # angle_to_rotation_matrix and cart2pol stated canonically in cart2pol's Convention+ # block (phi decreases by theta modulo 2*pi).+ # First case: no branch-cut crossing, so the raw difference is -theta itself.+ # Snippet used to generate expected (stdlib only):+ # import math+ # -math.radians(30.0) -> -0.5235987755982988+ v = torch.tensor([3.0, 4.0], device=device, dtype=dtype)+ phi0 = kornia.geometry.conversions.cart2pol(v[0], v[1])[1]++ rot = kornia.geometry.conversions.angle_to_rotation_matrix(torch.tensor(30.0, device=device, dtype=dtype))+ v_rot = rot @ v+ phi1 = kornia.geometry.conversions.cart2pol(v_rot[0], v_rot[1])[1]++ expected_delta = torch.tensor(-0.5235987755982988, device=device, dtype=dtype)+ self.assert_close(phi1 - phi0, expected_delta)++ # Second case: crossing the -x branch cut, where the returned phi is re-wrapped into+ # [-pi, pi] and only the difference modulo 2*pi is -theta (the worked -170 + 30 example+ # lives in cart2pol's Convention block).+ # Snippet used to generate expected (stdlib only):+ # import math+ # 5 * math.cos(math.radians(-170.0)), 5 * math.sin(math.radians(-170.0))+ # -> (-4.92403876506104, -0.8682408883346514)+ # math.radians(160.0) -> 2.792526803190927+ w = torch.tensor([-4.9240388, -0.8682409], device=device, dtype=dtype)+ phi0_cut = kornia.geometry.conversions.cart2pol(w[0], w[1])[1]++ w_rot = rot @ w+ phi1_cut = kornia.geometry.conversions.cart2pol(w_rot[0], w_rot[1])[1]++ self.assert_close(phi1_cut, torch.tensor(2.7925268, device=device, dtype=dtype))++ raw_delta = phi1_cut - phi0_cut+ wrapped_delta = torch.atan2(torch.sin(raw_delta), torch.cos(raw_delta))+ # The re-wrap atan2(sin, cos) adds two more transcendental roundings on top of the two+ # atan2 outputs it differences, overshooting the central per-dtype tolerances in the half+ # dtypes. Measured against the dtype-cast expected tensor the assert compares with+ # (-0.5234375 in both halves): |err| is 1.953125e-3 in float16 (wrapped -0.525390625;+ # central allowance atol 1e-3 + rtol 1e-3 * 0.52 = 1.52e-3) and 1.171875e-2 in bfloat16+ # (wrapped -0.53515625; allowance 1.19e-2 -- a 1.4 % margin that torch rounding drift+ # could erase). atol 2.4e-2 is ~2x the bfloat16 error; a sign-flipped or unwrapped delta+ # would still be off by >= 1.0.+ wrap_tol = {"atol": 2.4e-2, "rtol": 0.0} if dtype in (torch.float16, torch.bfloat16) else {}+ self.assert_close(wrapped_delta, expected_delta, **wrap_tol)+class TestConvertPointsToHomogeneous(BaseTester):def test_convert_points(self, device, dtype):- # generate input data+ # Convention pin: the homogeneous 1.0 is appended as the *last* component (the+ # non-symmetric rows catch a prepend or a component reversal).points_h = torch.tensor([[1.0, 2.0, 1.0], [0.0, 1.0, 2.0], [2.0, 1.0, 0.0], [-1.0, -2.0, -1.0], [0.0, 1.0, -2.0]],device=device,@@ -704,14 +946,17 @@ class TestConvertPointsToHomogeneous(BaseTester):class TestConvertAtoH(BaseTester):def test_convert_points(self, device, dtype):- # generate input data- A = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype).view(1, 2, 3)+ # Convention pin and its enforcement point: the (B, 2, 3) affine block is copied+ # verbatim into the top of the (B, 3, 3) result (no transpose, no reordering) and the+ # row [0, 0, 1] is appended at the *bottom*. The literal is non-symmetric so a+ # transpose is caught.+ # Snippet used to generate expected (torch only):+ # convert_affinematrix_to_homography(torch.tensor([[[1., 2., 3.], [4., 5., 6.]]]))+ # -> [[[1., 2., 3.], [4., 5., 6.], [0., 0., 1.]]]+ A = torch.tensor([[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]], device=device, dtype=dtype)- expected = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype).view(- 1, 3, 3- )+ expected = torch.tensor([[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)- # to euclideanH = kornia.geometry.conversions.convert_affinematrix_to_homography(A)self.assert_close(H, expected)@@ -733,6 +978,31 @@ class TestConvertAtoH(BaseTester):self.assert_close(actual, expected)+ def test_convention_homography3d_appends_bottom_row_0_0_0_1(self, device, dtype):+ # Convention pin (3-D sibling, which has no test class of its own): the (B, 3, 4) affine+ # block is copied verbatim and the row [0, 0, 0, 1] is appended at the bottom.+ # Snippet used to generate expected (by hand):+ # [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] gains [0, 0, 0, 1]+ A = torch.tensor(+ [[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]]], device=device, dtype=dtype+ )++ out = kornia.geometry.conversions.convert_affinematrix_to_homography3d(A)++ expected = torch.tensor(+ [+ [+ [1.0, 2.0, 3.0, 4.0],+ [5.0, 6.0, 7.0, 8.0],+ [9.0, 10.0, 11.0, 12.0],+ [0.0, 0.0, 0.0, 1.0],+ ]+ ],+ device=device,+ dtype=dtype,+ )+ self.assert_close(out, expected)+class TestConvertPointsFromHomogeneous(BaseTester):@pytest.mark.parametrize("batch_shape", [(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3)])@@ -742,7 +1012,9 @@ class TestConvertPointsFromHomogeneous(BaseTester):assert points.shape == points.shape[:-1] + (2,)def test_points(self, device, dtype):- # generate input data+ # Convention pins: the [2., 1., 0.] row is the |w| <= eps case (default eps 1e-8) --+ # returned *unchanged*, not zeros, not inf, no exception. The negative-w rows pin that+ # the sign of w is preserved (no abs): [0., 1., -2.] -> [0., -0.5].points_h = torch.tensor([[1.0, 2.0, 1.0], [0.0, 1.0, 2.0], [2.0, 1.0, 0.0], [-1.0, -2.0, -1.0], [0.0, 1.0, -2.0]],device=device,@@ -791,6 +1063,105 @@ class TestConvertPointsFromHomogeneous(BaseTester):self.assert_close(actual, expected)+ @pytest.mark.xfail(+ raises=AssertionError,+ reason="convert_points_from_homogeneous divides by w + eps β kornia#3938",+ strict=True,+ )+ def test_convention_divides_by_exactly_w(self, device, dtype):+ # Intended behavior: for |w| > eps the point is divided by exactly w. It currently is+ # divided by w + eps with no regard for sign, so the signed relative error is exactly+ # -eps / (w + eps): -1/3 at w = +2e-8 (33 % low) and +1 at w = -2e-8 (100 % high) (#3938).+ # Marked xfail(strict=True) so fixing #3938 makes this XPASS and forces the mark out.+ # Snippet used to generate expected (by hand):+ # 2 / 2e-8, 4 / 2e-8 -> [1e8, 2e8] (kornia returns [6.6666667e7, 1.3333333e8])+ # measured signed relative error in float64: -0.3333333333333334, and+ # -eps / (w + eps) = -1e-8 / 3e-8 = -0.3333333333333333+ if dtype == torch.float16:+ pytest.skip("float16 underflows w=2e-8 to 0, which is the |w| <= eps passthrough branch, not the eps bias")++ points = torch.tensor([[2.0, 4.0, 2e-8]], device=device, dtype=dtype)++ out = kornia.geometry.conversions.convert_points_from_homogeneous(points)++ expected = torch.tensor([[1e8, 2e8]], device=device, dtype=dtype)+ self.assert_close(out, expected)++ def test_wart_division_is_by_w_plus_eps_for_both_signs_3938(self, device, dtype):+ # Wart pin for kornia#3938, companion to the strict xfail above: assert the CURRENT+ # biased outputs for both signs of w. The xfail pins the intended behavior but cannot+ # flip under every fix polarity -- a sign-aware eps (w + sign(w) * eps) leaves the+ # positive-w case failing the intended [1e8, 2e8] and the mark silently XFAIL; here the+ # NEGATIVE-w cell (divided by -2e-8 + 1e-8 = -1e-8, doubling the point) flips under that+ # fix too, and both cells flip under an exact division or a grad-only eps. If either+ # assert fails, #3938 was (partly) fixed -- update or remove the warning in+ # convert_points_from_homogeneous and flip/remove the strict xfail above. eps=1e-8 is+ # passed explicitly so the pinned literals do not silently track a later change to the default.+ # Snippet used to generate expected (torch only, executed at each pinned dtype):+ # cpfh = kornia.geometry.conversions.convert_points_from_homogeneous+ # cpfh(torch.tensor([[2., 4., 2e-8]], dtype=torch.float64), eps=1e-8)+ # -> [[66666666.66666666, 133333333.33333331]] (f32: [[66666668.0, 133333336.0]])+ # cpfh(torch.tensor([[2., 4., -2e-8]], dtype=torch.float64), eps=1e-8)+ # -> [[-200000000.0, -400000000.0]] (f32: identical)+ # At bfloat16 the outputs land within 0.15 % of the literals (66584576, -200278016),+ # inside rtol 1e-2, so the pin holds there too.+ if dtype == torch.float16:+ pytest.skip("float16 underflows w=2e-8 to 0, which is the |w| <= eps passthrough branch, not the eps bias")++ cpfh = kornia.geometry.conversions.convert_points_from_homogeneous++ out_pos = cpfh(torch.tensor([[2.0, 4.0, 2e-8]], device=device, dtype=dtype), eps=1e-8)+ out_neg = cpfh(torch.tensor([[2.0, 4.0, -2e-8]], device=device, dtype=dtype), eps=1e-8)++ expected_pos = torch.tensor([[6.6666668e7, 1.33333336e8]], device=device, dtype=dtype)+ expected_neg = torch.tensor([[-2e8, -4e8]], device=device, dtype=dtype)+ self.assert_close(out_pos, expected_pos, atol=0.0, rtol=1e-2)+ self.assert_close(out_neg, expected_neg, atol=0.0, rtol=1e-2)+++def _skip_if_mps_clamp_caching(device):+ # Runtime probe instead of a torch-version pin, so the skip retires itself on any torch+ # build where the two clamps below return different values.+ if device.type == "mps" and torch.equal(+ torch.zeros(2, device=device).clamp(1e-8), torch.zeros(2, device=device).clamp(1e-7)+ ):+ pytest.skip(+ "this torch build caches clamp's scalar min per shape/dtype on MPS -- first value wins "+ "(seen on torch 2.9.1): z = torch.zeros(2, device='mps'); z.clamp(1e-8) then z.clamp(1e-7) "+ "both return 9.99999993922529e-09, while the same pair on cpu returns 1e-08 then "+ "1.0000000116860974e-07. The clamped eps this pin measures is therefore set by whichever "+ "earlier test clamped first, which is a torch defect, not a kornia one"+ )+++def _assert_degenerate_size_cell(+ func_2d, func_3d, fill, ndim, arg_name, degenerate_size, expected, tols, device, dtype+):+ # Shared driver for the two kornia#3940 wart matrices below -- the normalize and+ # denormalize halves differ only in function pair, fill value, tolerances and expected+ # table -- so the eventual #3940 cleanup edits one body and one MPS-skip helper. eps=1e-8 is+ # passed explicitly so the pinned literals do not silently track a later change to the default eps+ # while the clamp bug itself is still present.+ _skip_if_mps_clamp_caching(device)++ if ndim == "2d":+ sizes = {"height": 5, "width": 7}+ func = func_2d+ else:+ sizes = {"depth": 5, "height": 7, "width": 9}+ func = func_3d+ sizes[arg_name] = degenerate_size+ pts = torch.full((1, len(sizes)), fill, device=device, dtype=dtype)++ out = func(pts, *sizes.values(), eps=1e-8)++ expected_t = torch.tensor([expected], device=device, dtype=dtype)+ if tols is None:+ assert_close(out, expected_t)+ else:+ atol, rtol = tols+ assert_close(out, expected_t, atol=atol, rtol=rtol)+class TestNormalizePixelCoordinates(BaseTester):def test_tensor_bhw2(self, device, dtype, atol, rtol):@@ -842,6 +1213,215 @@ class TestNormalizePixelCoordinates(BaseTester):self.assert_close(actual, expected)+ def test_convention_corner_aligned_formula(self, device, dtype):+ # Convention pin: normalize_pixel_coordinates maps x -> 2*x/(W - 1) - 1 (corner-aligned,+ # i.e. the align_corners=True convention). grid_sample's *default* align_corners=False+ # convention, (2*x + 1)/W - 1, would give [-0.75, -0.25, 0.75] for the same input.+ # Snippet used to generate expected (stdlib only, W = 4):+ # [2 * x / (4 - 1) - 1 for x in (0.0, 1.0, 3.0)] -> [-1.0, -0.3333333333333333, 1.0]+ pts = torch.tensor([[0.0, 0.0], [1.0, 1.0], [3.0, 3.0]], device=device, dtype=dtype)++ out = kornia.geometry.conversions.normalize_pixel_coordinates(pts, 4, 4)++ expected = torch.tensor([[-1.0, -1.0], [-0.33333333, -0.33333333], [1.0, 1.0]], device=device, dtype=dtype)+ self.assert_close(out, expected)++ def test_convention_positional_order_is_height_then_width(self, device, dtype):+ # Convention pin: the positional signature is (pixel_coordinates, height, width), which is+ # the reverse of the per-point (x, y) -> (width, height) scaling order: slot 0 is scaled by+ # width and slot 1 by height. Calling with H and W swapped would give [[5.0, -0.3333]].+ # Snippet used to generate expected (stdlib only, H = 2, W = 4):+ # 2 * 3.0 / (4 - 1) - 1, 2 * 1.0 / (2 - 1) - 1 -> (1.0, 1.0)+ pts = torch.tensor([[3.0, 1.0]], device=device, dtype=dtype)++ out = kornia.geometry.conversions.normalize_pixel_coordinates(pts, 2, 4)++ expected = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)+ self.assert_close(out, expected)++ def test_convention_output_is_not_clamped(self, device, dtype):+ # Convention pin: nothing is clamped to [-1, 1] -- out-of-image coordinates extrapolate+ # linearly past it.+ # Snippet used to generate expected (stdlib only, H = W = 4):+ # 2 * 10.0 / (4 - 1) - 1, 2 * 0.0 / (4 - 1) - 1 -> (5.666666666666666, -1.0)+ pts = torch.tensor([[10.0, 0.0]], device=device, dtype=dtype)++ out = kornia.geometry.conversions.normalize_pixel_coordinates(pts, 4, 4)++ expected = torch.tensor([[5.6666667, -1.0]], device=device, dtype=dtype)+ self.assert_close(out, expected)++ def test_convention_grid_sample_needs_align_corners_true(self, device, dtype):+ # Convention pin: feeding normalized coordinates to torch.nn.functional.grid_sample+ # requires align_corners=True to be passed explicitly. With it, the three normalized+ # pixel centres sample back the exact pixel values; grid_sample's own default+ # (align_corners=None -> False) instead places u = -1, -1/3, 1 at pixels+ # ((u + 1) * 4 - 1) / 2 = -0.5, 0.8333, 3.5, i.e. half a pixel outside the image at+ # both ends, so every sampled value would be wrong.+ # Snippet used to generate expected (stdlib only, W = 4, img = arange(16).view(4, 4)):+ # img[0, 0], img[1, 1], img[3, 3] -> 0.0, 5.0, 15.0+ img = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)+ pts = torch.tensor([[0.0, 0.0], [1.0, 1.0], [3.0, 3.0]], device=device, dtype=dtype)+ grid = kornia.geometry.conversions.normalize_pixel_coordinates(pts, 4, 4).view(1, 1, 3, 2)++ sampled_aligned = torch.nn.functional.grid_sample(img, grid, align_corners=True).flatten()++ self.assert_close(sampled_aligned, torch.tensor([0.0, 5.0, 15.0], device=device, dtype=dtype))++ def test_convention_3d_component_order_is_depth_x_y(self, device, dtype):+ # Convention pin (normalize_pixel_coordinates3d has no test class of its own): the+ # component order is (d, x, y) -- depth first, then x scaled by width, then y scaled by+ # height. It is NOT (x, y, z): reading the same three numbers that way sends the point+ # out of range instead of to the far corner.+ # Snippet used to generate expected (stdlib only, D = 3, H = 5, W = 9):+ # 2 * 2 / (3 - 1) - 1, 2 * 8 / (9 - 1) - 1, 2 * 4 / (5 - 1) - 1 -> (1.0, 1.0, 1.0)+ # the (x, y, z) reading [2, 4, 8] gives 2 * 2 / 2 - 1, 2 * 4 / 8 - 1, 2 * 8 / 4 - 1+ # -> (1.0, 0.0, 3.0)+ far_corner = torch.tensor([[2.0, 8.0, 4.0]], device=device, dtype=dtype)+ out = kornia.geometry.conversions.normalize_pixel_coordinates3d(far_corner, 3, 5, 9)+ self.assert_close(out, torch.tensor([[1.0, 1.0, 1.0]], device=device, dtype=dtype))++ swapped = torch.tensor([[2.0, 4.0, 8.0]], device=device, dtype=dtype)+ out_swapped = kornia.geometry.conversions.normalize_pixel_coordinates3d(swapped, 3, 5, 9)+ self.assert_close(out_swapped, torch.tensor([[1.0, 0.0, 3.0]], device=device, dtype=dtype))++ # Wart-pin matrix for kornia#3940, normalizing half: one cell per (size argument x+ # degenerate class) of normalize_pixel_coordinates and normalize_pixel_coordinates3d,+ # asserting the CURRENT broken output that the docstring warnings document. If any cell+ # fails, #3940 was (partly) fixed -- update or remove the degenerate-size warnings in+ # normalize_pixel_coordinates, denormalize_pixel_coordinates, normalize_pixel_coordinates3d+ # and denormalize_pixel_coordinates3d. The cells are NOT a contract that degenerate sizes+ # must keep returning these values.+ # They are regular tests rather than strict xfails on purpose: the intended behavior+ # (raise ValueError, or clamp the *output*, or keep the current pass-through) is a+ # maintainer decision, and a strict xfail asserting one of those answers would stay+ # silently XFAIL forever if a different one were chosen. A wart pin flips loudly under+ # every polarity, and covering the full matrix means any partial fix -- one function, one+ # argument, or one degenerate class -- flips at least one cell.+ # Exactly one size argument is degenerate per cell (the others stay at 5/7 in 2-D and+ # 5/7/9 in 3-D), so the finite components pin which argument was degenerated. All three+ # classes give the same output because the mechanism is `(size - 1).clamp(eps)`: size 1+ # gives 0, size 0 gives -1 and size -3 gives -4, all clamped up to eps = 1e-8, so the+ # factor becomes 2e8.+ # Snippet used to generate expected (torch only; same output for bad in (1, 0, -3)):+ # npc = kornia.geometry.conversions.normalize_pixel_coordinates+ # npc3 = kornia.geometry.conversions.normalize_pixel_coordinates3d+ # npc(torch.tensor([[1., 1.]], dtype=torch.float64), bad, 7, eps=1e-8)+ # -> [[-0.6666666666666667, 199999999.0]]+ # npc(torch.tensor([[1., 1.]], dtype=torch.float64), 5, bad, eps=1e-8) -> [[199999999.0, -0.5]]+ # npc3(torch.tensor([[1., 1., 1.]], dtype=torch.float64), bad, 7, 9, eps=1e-8)+ # -> [[199999999.0, -0.75, -0.6666666666666667]]+ # npc3(torch.tensor([[1., 1., 1.]], dtype=torch.float64), 5, bad, 9, eps=1e-8)+ # -> [[-0.5, -0.75, 199999999.0]]+ # npc3(torch.tensor([[1., 1., 1.]], dtype=torch.float64), 5, 7, bad, eps=1e-8)+ # -> [[-0.5, 199999999.0, -0.6666666666666667]]+ # At float16 2e8 overflows to inf and the literal overflows identically; at bfloat16 both+ # sides round to 200278016.0, so the comparison stays meaningful at every dtype.+ @pytest.mark.parametrize("degenerate_size", [1, 0, -3], ids=["one", "zero", "negative"])+ @pytest.mark.parametrize(+ ("ndim", "arg_name", "expected"),+ [+ ("2d", "height", [-0.6666667, 199999999.0]),+ ("2d", "width", [199999999.0, -0.5]),+ ("3d", "depth", [199999999.0, -0.75, -0.6666667]),+ ("3d", "height", [-0.5, -0.75, 199999999.0]),+ ("3d", "width", [-0.5, 199999999.0, -0.6666667]),+ ],+ ids=["2d-height", "2d-width", "3d-depth", "3d-height", "3d-width"],+ )+ def test_wart_degenerate_size_matrix(self, ndim, arg_name, degenerate_size, expected, device, dtype):+ _assert_degenerate_size_cell(+ kornia.geometry.conversions.normalize_pixel_coordinates,+ kornia.geometry.conversions.normalize_pixel_coordinates3d,+ 1.0,+ ndim,+ arg_name,+ degenerate_size,+ expected,+ None,+ device,+ dtype,+ )++ def test_wart_all_size_arguments_degenerate_together(self, device, dtype):+ # Wart pin for kornia#3940, companion to the matrix above: both sizes degenerate at+ # once also passes silently, exploding every component. Flips together with the matrix+ # when #3940 is fixed -- see the cleanup note above the matrix.+ # Snippet used to generate expected (torch only):+ # npc = kornia.geometry.conversions.normalize_pixel_coordinates+ # npc(torch.tensor([[1., 1.]], dtype=torch.float64), 1, 1, eps=1e-8)+ # -> [[199999999.0, 199999999.0]]+ _skip_if_mps_clamp_caching(device)++ pts = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)++ out = kornia.geometry.conversions.normalize_pixel_coordinates(pts, 1, 1, eps=1e-8)++ expected = torch.tensor([[199999999.0, 199999999.0]], device=device, dtype=dtype)+ self.assert_close(out, expected)+++def test_wart_default_eps_1e_8_backs_the_quoted_warning_numbers():+ # The wart pins in this file pass eps=1e-8 explicitly so their literals do not track the+ # default, which leaves the default itself pinned by nothing while six docstring warnings+ # quote numbers that hold only for eps=1e-8: cart2pol (rho = 1e-04 at the origin),+ # convert_points_from_homogeneous (the -1/3 and +1 relative errors at w = +/-2e-8),+ # normalize_pixel_coordinates and normalize_pixel_coordinates3d (the 199999999.0 / 2e8+ # blow-up factor) and denormalize_pixel_coordinates / denormalize_pixel_coordinates3d (the+ # 5e-09 collapse factor). If this fails, the default moved -- rework those warnings'+ # numbers together with this list.+ for op_name in (+ "cart2pol",+ "convert_points_from_homogeneous",+ "normalize_pixel_coordinates",+ "denormalize_pixel_coordinates",+ "normalize_pixel_coordinates3d",+ "denormalize_pixel_coordinates3d",+ ):+ op = getattr(kornia.geometry.conversions, op_name)+ assert inspect.signature(op).parameters["eps"].default == 1e-8, op_name+++def test_wart_float16_underflowed_default_eps_flips_branches(device):+ # Wart pins for the float16 sentences of the #3939 and #3938 warnings. float16 is+ # hardcoded (no dtype fixture) so the pins run in every test configuration: the float16+ # legs of the wart pins above are skipped because the default eps=1e-8 underflows to 0+ # there, which is exactly the behavior pinned here. eps is left at its default on purpose+ # -- the underflow of the *default* is the claim. atol=rtol=0.0 because both claims are+ # exactness claims: with the float16 default tolerance (1e-3) the eps-biased+ # rho = 1e-4 of the other branch would still compare equal to 0.+ # Snippet used to generate expected (torch only, executed on cpu float16):+ # cart2pol(torch.tensor(0., dtype=torch.float16), torch.tensor(0., dtype=torch.float16))[0]+ # -> 0.0 (not sqrt(eps) = 1e-4: eps underflows the sum inside the sqrt)+ # convert_points_from_homogeneous(torch.tensor([[2., 4., 2e-8]], dtype=torch.float16))+ # -> [[2., 4.]] (w underflows to 0 and takes the abs(w) <= eps passthrough branch)+ zero = torch.tensor(0.0, device=device, dtype=torch.float16)+ rho = kornia.geometry.conversions.cart2pol(zero, zero)[0]+ assert_close(rho, zero, atol=0.0, rtol=0.0)++ out = kornia.geometry.conversions.convert_points_from_homogeneous(+ torch.tensor([[2.0, 4.0, 2e-8]], device=device, dtype=torch.float16)+ )+ assert_close(out, torch.tensor([[2.0, 4.0]], device=device, dtype=torch.float16), atol=0.0, rtol=0.0)+++def test_wart_float16_degenerate_roundtrip_is_inf_then_nan(device):+ # Wart pin for the float16 sentence of the #3940 warnings, float16-hardcoded like the test+ # above: with the default eps underflowed to 0, the clamp keeps the degenerate denominator+ # at 0, the normalized component is inf (not the 2e8 the other dtypes pin) and the+ # denormalize round trip of that is nan, not the input.+ # Snippet used to generate expected (torch only, executed on cpu float16):+ # normalize_pixel_coordinates(torch.ones(1, 2, dtype=torch.float16), 1, 1) -> [[inf, inf]]+ # denormalize_pixel_coordinates(<that>, 1, 1) -> [[nan, nan]]+ _skip_if_mps_clamp_caching(device)++ ones = torch.ones(1, 2, device=device, dtype=torch.float16)+ norm = kornia.geometry.conversions.normalize_pixel_coordinates(ones, 1, 1)+ assert (norm == torch.inf).all()++ denorm = kornia.geometry.conversions.denormalize_pixel_coordinates(norm, 1, 1)+ assert torch.isnan(denorm).all()+class TestDenormalizePixelCoordinates(BaseTester):def test_tensor_bhw2(self, device, dtype):@@ -891,6 +1471,100 @@ class TestDenormalizePixelCoordinates(BaseTester):self.assert_close(actual, expected)+ def test_convention_corner_aligned_inverse(self, device, dtype):+ # Convention pin: denormalize_pixel_coordinates is the corner-aligned inverse,+ # x = (W - 1) * (x_norm + 1) / 2, taken positionally as (coords, height, width) with+ # (x, y) points. grid_sample's align_corners=False convention, ((x_norm + 1) * W - 1)/2,+ # would give [[3.5, -0.5]] for the same input.+ # Snippet used to generate expected (stdlib only, H = 2, W = 4):+ # (4 - 1) * (1.0 + 1) / 2, (2 - 1) * (-1.0 + 1) / 2 -> (3.0, 0.0)+ pts_norm = torch.tensor([[1.0, -1.0]], device=device, dtype=dtype)++ out = kornia.geometry.conversions.denormalize_pixel_coordinates(pts_norm, 2, 4)++ expected = torch.tensor([[3.0, 0.0]], device=device, dtype=dtype)+ self.assert_close(out, expected)++ def test_convention_roundtrip_denormalize_of_normalize(self, device, dtype):+ # Convention pin: denormalize(normalize(p)) == p on a non-degenerate, non-square,+ # non-identity image size, so the two formulas are exact mutual inverses.+ # Snippet used to generate expected (by hand): the input itself.+ pts = torch.tensor([[1.0, 2.0], [3.0, 0.0]], device=device, dtype=dtype)++ norm = kornia.geometry.conversions.normalize_pixel_coordinates(pts, 5, 7)+ out = kornia.geometry.conversions.denormalize_pixel_coordinates(norm, 5, 7)++ self.assert_close(out, pts)++ def test_convention_3d_component_order_and_roundtrip(self, device, dtype):+ # Convention pin (denormalize_pixel_coordinates3d has no test class of its own): same+ # (d, x, y) order as the 3-D normalizer, so the normalized origin maps to the per-axis+ # centres ((D - 1)/2, (W - 1)/2, (H - 1)/2), and the pair round-trips exactly.+ # Snippet used to generate expected (stdlib only, D = 3, H = 5, W = 9):+ # (3 - 1) / 2, (9 - 1) / 2, (5 - 1) / 2 -> (1.0, 4.0, 2.0)+ centre = kornia.geometry.conversions.denormalize_pixel_coordinates3d(+ torch.tensor([[0.0, 0.0, 0.0]], device=device, dtype=dtype), 3, 5, 9+ )+ self.assert_close(centre, torch.tensor([[1.0, 4.0, 2.0]], device=device, dtype=dtype))++ pts = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)+ norm = kornia.geometry.conversions.normalize_pixel_coordinates3d(pts, 3, 5, 9)+ out = kornia.geometry.conversions.denormalize_pixel_coordinates3d(norm, 3, 5, 9)+ self.assert_close(out, pts)++ # Wart-pin matrix for kornia#3940, denormalizing half: one cell per (size argument x+ # degenerate class) of denormalize_pixel_coordinates and denormalize_pixel_coordinates3d,+ # asserting the CURRENT broken output that the docstring warnings document. If any cell+ # fails, #3940 was (partly) fixed -- update or remove the degenerate-size warnings in+ # normalize_pixel_coordinates, denormalize_pixel_coordinates, normalize_pixel_coordinates3d+ # and denormalize_pixel_coordinates3d. The cells are NOT a contract that degenerate sizes+ # must keep returning these values; see the polarity note on the normalize wart matrix,+ # which also explains why exactly one argument is degenerate per cell and why all three+ # classes (1, 0, -3) give the same output.+ # Here the clamped denominator multiplies instead of divides, so the degenerate axis+ # collapses to eps / 2 = 5e-09 rather than exploding to 2e8. The tolerance is tight+ # (rtol 1e-6, atol 0) on purpose: at atol 1e-2 the collapsed component would compare+ # equal to any small number, including the 0.0 a "clamp the output" fix might return.+ # It still holds at every dtype -- at float16 5e-09 underflows to 0.0 on both the+ # measured and the literal side, at bfloat16 both round to 5.005858838558197e-09, and the+ # finite components 2.0/3.0/4.0 are exact in every dtype.+ # Snippet used to generate expected (torch only; same output for bad in (1, 0, -3)):+ # dpc = kornia.geometry.conversions.denormalize_pixel_coordinates+ # dpc3 = kornia.geometry.conversions.denormalize_pixel_coordinates3d+ # dpc(torch.tensor([[0., 0.]], dtype=torch.float64), bad, 7, eps=1e-8) -> [[3.0, 5e-09]]+ # dpc(torch.tensor([[0., 0.]], dtype=torch.float64), 5, bad, eps=1e-8) -> [[5e-09, 2.0]]+ # dpc3(torch.tensor([[0., 0., 0.]], dtype=torch.float64), bad, 7, 9, eps=1e-8)+ # -> [[5e-09, 4.0, 3.0]]+ # dpc3(torch.tensor([[0., 0., 0.]], dtype=torch.float64), 5, bad, 9, eps=1e-8)+ # -> [[2.0, 4.0, 5e-09]]+ # dpc3(torch.tensor([[0., 0., 0.]], dtype=torch.float64), 5, 7, bad, eps=1e-8)+ # -> [[2.0, 5e-09, 3.0]]+ @pytest.mark.parametrize("degenerate_size", [1, 0, -3], ids=["one", "zero", "negative"])+ @pytest.mark.parametrize(+ ("ndim", "arg_name", "expected"),+ [+ ("2d", "height", [3.0, 5e-09]),+ ("2d", "width", [5e-09, 2.0]),+ ("3d", "depth", [5e-09, 4.0, 3.0]),+ ("3d", "height", [2.0, 4.0, 5e-09]),+ ("3d", "width", [2.0, 5e-09, 3.0]),+ ],+ ids=["2d-height", "2d-width", "3d-depth", "3d-height", "3d-width"],+ )+ def test_wart_degenerate_size_matrix(self, ndim, arg_name, degenerate_size, expected, device, dtype):+ _assert_degenerate_size_cell(+ kornia.geometry.conversions.denormalize_pixel_coordinates,+ kornia.geometry.conversions.denormalize_pixel_coordinates3d,+ 0.0,+ ndim,+ arg_name,+ degenerate_size,+ expected,+ (0.0, 1e-6),+ device,+ dtype,+ )+class TestProjectPoints(BaseTester):def test_smoke(self, device, dtype):@@ -987,6 +1661,22 @@ class TestDenormalizePointsWithIntrinsics(BaseTester):self.assert_close(actual, expected)+ def test_convention_maps_normalized_camera_points_to_pixels(self, device, dtype):+ # Convention pin: the input is in *normalized camera* coordinates and the output is in+ # *pixel* coordinates, using the pinhole layout u = x * fx + cx, v = y * fy + cy.+ # fx != fy and cx != cy so a transposed or swapped read of K is caught.+ # Snippet used to generate expected (stdlib only, fx=100, fy=200, cx=320, cy=240):+ # 1.0 * 100 + 320, 1.0 * 200 + 240 -> (420.0, 440.0)+ points_norm = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)+ camera_matrix = torch.tensor(+ [[[100.0, 0.0, 320.0], [0.0, 200.0, 240.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype+ )++ out = kornia.geometry.conversions.denormalize_points_with_intrinsics(points_norm, camera_matrix)++ expected = torch.tensor([[420.0, 440.0]], device=device, dtype=dtype)+ self.assert_close(out, expected)+class TestNormalizePointsWithIntrinsics(BaseTester):def test_smoke(self, device, dtype):@@ -1046,6 +1736,39 @@ class TestNormalizePointsWithIntrinsics(BaseTester):self.assert_close(actual, expected)+ def test_convention_intrinsics_layout_fx_fy_cx_cy(self, device, dtype):+ # Convention pin: K is the standard row-major pinhole matrix, fx = K[..., 0, 0],+ # fy = K[..., 1, 1], cx = K[..., 0, 2], cy = K[..., 1, 2], and the point is (u, v) in+ # pixels, so x = (u - cx)/fx, y = (v - cy)/fy. fx != fy and cx != cy, so swapping the+ # two focal lengths would give [[0.5, 2.0]] and a transposed K would not divide at all.+ # Snippet used to generate expected (stdlib only, fx=100, fy=200, cx=320, cy=240):+ # (420.0 - 320) / 100, (440.0 - 240) / 200 -> (1.0, 1.0)+ points_2d = torch.tensor([[420.0, 440.0]], device=device, dtype=dtype)+ camera_matrix = torch.tensor(+ [[[100.0, 0.0, 320.0], [0.0, 200.0, 240.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype+ )++ out = kornia.geometry.conversions.normalize_points_with_intrinsics(points_2d, camera_matrix)++ expected = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)+ self.assert_close(out, expected)++ def test_convention_skew_term_is_ignored(self, device, dtype):+ # Convention pin: only the diagonal fx, fy and the [:2, 2] column of K are read -- the+ # skew entry K[..., 0, 1] is silently ignored, so a skewed K gives the same answer as+ # the skew-free one. A skew-aware implementation would return (1.0 - 7/100, 1.0).+ # Snippet used to generate expected (stdlib only): identical to the skew-free result,+ # (420.0 - 320) / 100, (440.0 - 240) / 200 -> (1.0, 1.0)+ points_2d = torch.tensor([[420.0, 440.0]], device=device, dtype=dtype)+ camera_matrix = torch.tensor(+ [[[100.0, 7.0, 320.0], [0.0, 200.0, 240.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype+ )++ out = kornia.geometry.conversions.normalize_points_with_intrinsics(points_2d, camera_matrix)++ expected = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)+ self.assert_close(out, expected)+class TestRt2Extrinsics(BaseTester):@pytest.mark.parametrize("batch_size", [1, 2, 3])@@ -1322,6 +2045,17 @@ def test_vector_to_skew_symmetric_matrix(batch_size, device, dtype):assert_close(skew_symmetric_matrix[..., 1, 2], -vector[..., 0])assert_close(skew_symmetric_matrix[..., 2, 1], vector[..., 0])+ # Convention's enforcement point: [v]x @ x == cross(v, x) -- the vector is the LEFT factor+ # of the cross product, NOT cross(x, v), which is the negation.+ # Snippet used to generate expected (stdlib only):+ # v, x = (1, 2, 3), (4, 5, 6)+ # cross(v, x) = (2*6 - 3*5, 3*4 - 1*6, 1*5 - 2*4) -> (-3, 6, -3)+ v = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)+ x = torch.tensor([4.0, 5.0, 6.0], device=device, dtype=dtype)+ skew = kornia.geometry.conversions.vector_to_skew_symmetric_matrix(v)+ expected_cross = torch.tensor([-3.0, 6.0, -3.0], device=device, dtype=dtype)+ assert_close(skew @ x, expected_cross)+class TestAxisAngleToRotationMatrix:def test_identity_rotation(self):