π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(geometry): add denormalize_homography3d and ColmapQTVecs_to_ARKitQTVecs (#5938)
Dmytro Mishkin4214b2b96ffb
diff --git a/changelog.d/5938.added.md b/changelog.d/5938.added.mdnew file mode 100644index 000000000..354fa8784--- /dev/null+++ b/changelog.d/5938.added.md@@ -0,0 +1,3 @@+`kornia.geometry.conversions.denormalize_homography3d`, the inverse of `normalize_homography3d`, and+`kornia.geometry.conversions.ColmapQTVecs_to_ARKitQTVecs`, the reverse of `ARKitQTVecs_to_ColmapQTVecs`, so both+conversions can now be round-tripped through the public API.diff --git a/docs/source/geometry.conversions.rst b/docs/source/geometry.conversions.rstindex cdec975f7..9b7b16cff 100644--- a/docs/source/geometry.conversions.rst+++ b/docs/source/geometry.conversions.rst@@ -36,6 +36,7 @@ Homography.. autofunction:: normalize_homography.. autofunction:: denormalize_homography.. autofunction:: normalize_homography3d+.. autofunction:: denormalize_homography3d.. autofunction:: normal_transform_pixel.. autofunction:: normal_transform_pixel3d@@ -83,3 +84,4 @@ Pose.. autofunction:: camtoworld_graphics_to_vision_Rt.. autofunction:: camtoworld_vision_to_graphics_Rt.. autofunction:: ARKitQTVecs_to_ColmapQTVecs+.. autofunction:: ColmapQTVecs_to_ARKitQTVecsdiff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 5a041ee77..58166efcc 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -26,10 +26,12 @@ import torch.nn.functional as Ffrom kornia.core._compat import deprecatedfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, ShapeError, are_checks_enabled+from kornia.core.exceptions import TypeCheckErrorfrom kornia.core.utils import _inverse_3x3_closed_form, _torch_inverse_cast, is_compiling__all__ = ["ARKitQTVecs_to_ColmapQTVecs",+ "ColmapQTVecs_to_ARKitQTVecs","Rt_to_matrix4x4","angle_axis_to_quaternion","angle_axis_to_rotation_matrix",@@ -48,6 +50,7 @@ __all__ = ["convert_points_to_homogeneous","deg2rad","denormalize_homography",+ "denormalize_homography3d","denormalize_pixel_coordinates","denormalize_pixel_coordinates3d","denormalize_points_with_intrinsics",@@ -2322,9 +2325,9 @@ def normalize_homography3d(:func:`~kornia.geometry.conversions.normal_transform_pixel3d` in placeof the 2-D helper. Unlike the 2-D function it has no ``align_corners``parameter, so its frames are corner-aligned unconditionally. It is- **not** the 2-D function with wider matrices, though: the shapes, the- missing inverse and β least visibly β the inversion routine all- differ, as the bullets below record+ **not** the 2-D function with wider matrices, though: the shapes and+ β least visibly β the inversion routine differ, as the bullets below+ record- it inverts ``N_src`` with ``torch.linalg.inv`` (so ``cusolver`` on``cuda``, and a ``float32`` upcast for ``float16``/``bfloat16``),where the 2-D function uses a closed-form adjugate in the working@@ -2332,9 +2335,8 @@ def normalize_homography3d(- the matrices are :math:`(B, 4, 4)` and act on ``(x, y, z, 1)`` columnvectors, while both ``dsize`` arguments are``(depth, height, width)`` triples- - there is **no** ``denormalize_homography3d``; compose the inverse from- :func:`~kornia.geometry.conversions.normal_transform_pixel3d`.- Tracked in `#3962 <https://github.com/kornia/kornia/issues/3962>`_+ - :func:`~kornia.geometry.conversions.denormalize_homography3d`+ computes the reverse ``inv(N_dst) @ H @ N_src``- the shape guard is the 2-D function's for 4x4 matrices: :math:`(4, 4)`(returned as ``(1, 4, 4)``) or :math:`(B, 4, 4)`, anything else raises``ValueError``@@ -2381,6 +2383,85 @@ def normalize_homography3d(return dst_norm_trans_src_norm+def denormalize_homography3d(+ dst_pix_trans_src_pix: torch.Tensor, dsize_src: tuple[int, int, int], dsize_dst: tuple[int, int, int]+) -> torch.Tensor:+ r"""De-normalize a given 3D homography from [-1, 1] to actual depth, height and width.++ Convention:+ - the mirror of+ :func:`~kornia.geometry.conversions.normalize_homography3d`: the+ composition is ``inv(N_dst) @ H @ N_src``, so the input maps+ normalized source to normalized destination and the output maps+ source voxels to destination voxels. The ``(depth, height, width)``+ ``dsize`` roles, the ``(x, y, z, 1)`` column vectors, per-sample+ batching, the corner-aligned frames and the shape guard are as+ documented there+ - ``inv(N_dst)`` goes through ``torch.linalg.inv`` (so ``cusolver`` on+ ``cuda``, and a ``float32`` upcast for ``float16``/``bfloat16``), the+ same routine :func:`~kornia.geometry.conversions.normalize_homography3d`+ uses for ``inv(N_src)``+ - the two functions invert each other to a small multiple of the+ working dtype's ``eps`` times the largest entry, not bitwise in+ general+ - only real floating point homographies are accepted (``float16``,+ ``bfloat16``, ``float32``, ``float64``): an integer, bool or complex+ ``dst_pix_trans_src_pix`` raises ``TypeCheckError`` (also a+ ``TypeError``) instead of being promoted, so cast it first. Integers+ would truncate the normalization matrices (the 2-D function still+ does, `#3959 <https://github.com/kornia/kornia/issues/3959>`_), and+ complex dtypes would be inverted in ``float32``+ (``_torch_inverse_cast``), losing ``complex128`` precision++ Args:+ dst_pix_trans_src_pix: homography/ies from source to destination to be+ denormalized. :math:`(B, 4, 4)`, or an unbatched :math:`(4, 4)`, which+ is promoted to :math:`(1, 4, 4)`+ dsize_src: size of the source image (depth, height, width).+ dsize_dst: size of the destination image (depth, height, width).++ Returns:+ the denormalized homography.++ Shape:+ Output: :math:`(B, 4, 4)`++ """+ if not isinstance(dst_pix_trans_src_pix, torch.Tensor):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(dst_pix_trans_src_pix)}")++ # An integer or bool homography would cast the normalization matrices back to integers+ # (truncating the 2/(size - 1) scales to 0, or failing on a singular inverse), and a complex one+ # would be inverted in float32 by _torch_inverse_cast, so the dtype is rejected rather than+ # promoted: the caller casts. Raised directly, not through KORNIA_CHECK,+ # which python -O and disable_checks() switch off.+ if not dst_pix_trans_src_pix.is_floating_point():+ raise TypeCheckError(+ "Input dst_pix_trans_src_pix must be a real floating point tensor. "+ f"Got dtype {dst_pix_trans_src_pix.dtype}.",+ actual_type=dst_pix_trans_src_pix.dtype,+ )++ if not (dst_pix_trans_src_pix.ndim in (2, 3) and dst_pix_trans_src_pix.shape[-2:] == (4, 4)):+ raise ValueError(f"Input dst_pix_trans_src_pix must be a Bx4x4 tensor. Got {dst_pix_trans_src_pix.shape}")++ # source and destination sizes+ src_d, src_h, src_w = dsize_src+ dst_d, dst_h, dst_w = dsize_dst+ # compute the transformation pixel/norm for src/dst+ normalization_dtype = dst_pix_trans_src_pix.dtype+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel3d(+ src_d, src_h, src_w, device=dst_pix_trans_src_pix.device, dtype=normalization_dtype+ ).to(dst_pix_trans_src_pix)++ dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel3d(+ dst_d, dst_h, dst_w, device=dst_pix_trans_src_pix.device, dtype=normalization_dtype+ ).to(dst_pix_trans_src_pix)+ dst_pix_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_dst_pix)+ # compute chain transformations+ return dst_pix_trans_dst_norm @ (dst_pix_trans_src_pix @ src_norm_trans_src_pix)++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.@@ -2991,10 +3072,8 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: torch.Tensor, tvec: torch.Tensor) -> tuple- worked literal: ``q = [0., 1., 0., 1.]``, ``t = (1, 1, 1)`` gives``q = [0.7071, 0., 0.7071, 0.]`` and ``t = (-1, -1, 1)``, the examplebelow- - there is **no** ``ColmapQTVecs_to_ARKitQTVecs``; compose the inverse- from :func:`~kornia.geometry.conversions.worldtocam_to_camtoworld_Rt`- and :func:`~kornia.geometry.conversions.camtoworld_vision_to_graphics_Rt`.- Tracked in `#3962 <https://github.com/kornia/kornia/issues/3962>`_+ - :func:`~kornia.geometry.conversions.ColmapQTVecs_to_ARKitQTVecs`+ computes the reverse conversion.. warning::The zero quaternion is not rejected: ``torch.zeros(1, 4)`` with@@ -3028,6 +3107,84 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: torch.Tensor, tvec: torch.Tensor) -> tuplereturn q_colmap, t_colmap+def ColmapQTVecs_to_ARKitQTVecs(qvec: torch.Tensor, tvec: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ r"""Convert a Colmap world-to-camera pose to an Apple ARKit camera-to-world screen pose.++ Both poses in quaternion representation.++ Convention:+ See :doc:`camera and world conventions </get-started/camera-conventions>` for the camera frames and+ extrinsics conventions composed by this conversion.++ - the reverse of+ :func:`~kornia.geometry.conversions.ARKitQTVecs_to_ColmapQTVecs`,+ with the same layouts and the frames exchanged+ - **input**: ``qvec`` :math:`(B, 4)` in ``(w, x, y, z)`` order β+ ``[1., 0., 0., 0.]`` is the identity β and ``tvec`` :math:`(B, 3, 1)`,+ read as a **world-to-camera** pose in the **vision** frame (``+y``+ down, ``+z`` forward) β Colmap's ``images.txt``+ ``QW QX QY QZ TX TY TZ``+ - **output**: ``(q, t)`` in the same layouts, a **camera-to-world**+ pose in the **graphics** frame (``+y`` up, ``-z`` forward), so ``t``+ is the camera centre in world coordinates. The pipeline is+ :func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`,+ :func:`~kornia.geometry.conversions.worldtocam_to_camtoworld_Rt`,+ :func:`~kornia.geometry.conversions.camtoworld_vision_to_graphics_Rt`,+ then :func:`~kornia.geometry.conversions.rotation_matrix_to_quaternion`+ - the output is ``(w, x, y, z)``; ARKit's ``simd_quatf`` stores+ ``(ix, iy, iz, r)``, i.e. ``xyzw``, so reorder it before handing it+ to ARKit+ - the input quaternion need not be unit and ``q`` and ``-q`` give the+ same output, within the same normalisation range as+ :func:`~kornia.geometry.conversions.ARKitQTVecs_to_ColmapQTVecs`+ - only real floating point ``qvec`` and ``tvec`` are accepted: an+ integer, bool or complex one raises ``TypeCheckError`` (also a+ ``TypeError``) naming the argument, so cast it first+ - the **sign of the output quaternion is not canonical**: a round trip+ through both functions returns the input rotation, but not+ necessarily the input quaternion's sign. Compare rotations, never raw+ components+ - worked literal: the reverse of the+ :func:`~kornia.geometry.conversions.ARKitQTVecs_to_ColmapQTVecs`+ example, ``q = [0.7071, 0., 0.7071, 0.]``, ``t = (-1, -1, 1)``, gives+ ``q = [0., 0.7071, 0., 0.7071]`` and ``t = (1, 1, 1)``, the unit form+ of that example's input; see the example below++ .. warning::+ The zero quaternion is not rejected: ``torch.zeros(1, 4)`` with+ ``t = (1, 1, 1)`` returns ``q = [0., 1., 0., 0.]``, ``t = (-1, -1, -1)``,+ the same answer as the identity input. Tracked in+ `#3952 <https://github.com/kornia/kornia/issues/3952>`_.++ Args:+ qvec: Colmap rotation quaternion :math:`(B, 4)`, [w, x, y, z] format.+ tvec: translation vector :math:`(B, 3, 1)`, [x, y, z]++ Returns:+ qvec: ARKit rotation quaternion :math:`(B, 4)`, [w, x, y, z] format.+ tvec: translation vector :math:`(B, 3, 1)`, [x, y, z]++ Example:+ >>> q, t = torch.tensor([0, 1, 0, 1.])[None], torch.ones(3).reshape(1, 3, 1)+ >>> ColmapQTVecs_to_ARKitQTVecs(*ARKitQTVecs_to_ColmapQTVecs(q, t))+ (tensor([[0.0000, 0.7071, 0.0000, 0.7071]]), tensor([[[1.0000],+ [1.0000],+ [1.0000]]]))++ """+ for name, value in (("qvec", qvec), ("tvec", tvec)):+ if isinstance(value, torch.Tensor) and not value.is_floating_point(): # complex is not floating point+ raise TypeCheckError(+ f"Input {name} must be a real floating point tensor. Got dtype {value.dtype}.", actual_type=value.dtype+ )+ R_colmap = quaternion_to_rotation_matrix(qvec)+ Rcv, Tcv = worldtocam_to_camtoworld_Rt(R_colmap, tvec)+ Rcg, Tcg = camtoworld_vision_to_graphics_Rt(Rcv, Tcv)+ t_arkit = Tcg.reshape(-1, 3, 1)+ q_arkit = rotation_matrix_to_quaternion(Rcg.contiguous())+ return q_arkit, t_arkit++def vector_to_skew_symmetric_matrix(vec: torch.Tensor) -> torch.Tensor:r"""Convert a vector to a skew symmetric matrix.diff --git a/tests/api_surface.json b/tests/api_surface.jsonindex 5324f73a3..770458106 100644--- a/tests/api_surface.json+++ b/tests/api_surface.json@@ -442,6 +442,7 @@"BaseModel","BaseWarper","CenterCrop2D",+ "ColmapQTVecs_to_ARKitQTVecs","ConvQuadInterp3d","ConvSoftArgmax2d","ConvSoftArgmax3d",@@ -534,6 +535,7 @@"decompose_essential_matrix_no_svd","deg2rad","denormalize_homography",+ "denormalize_homography3d","denormalize_pixel_coordinates","denormalize_pixel_coordinates3d","denormalize_points_with_intrinsics",@@ -765,6 +767,7 @@],"kornia.geometry.conversions": ["ARKitQTVecs_to_ColmapQTVecs",+ "ColmapQTVecs_to_ARKitQTVecs","Rt_to_matrix4x4","angle_axis_to_quaternion","angle_axis_to_rotation_matrix",@@ -783,6 +786,7 @@"convert_points_to_homogeneous","deg2rad","denormalize_homography",+ "denormalize_homography3d","denormalize_pixel_coordinates","denormalize_pixel_coordinates3d","denormalize_points_with_intrinsics",diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex 85326874a..c014f05e2 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -31,10 +31,11 @@ import torchimport korniafrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, are_checks_enabled, disable_checks, enable_checks-from kornia.core.exceptions import BaseError, ShapeError+from kornia.core.exceptions import BaseError, ShapeError, TypeCheckErrorfrom kornia.core.ops import eye_likefrom kornia.geometry.conversions import (ARKitQTVecs_to_ColmapQTVecs,+ ColmapQTVecs_to_ARKitQTVecs,Rt_to_matrix4x4,axis_angle_to_rotation_matrix,camtoworld_graphics_to_vision_4x4,@@ -283,6 +284,7 @@ _WRONG_SIZE_CASES = [("normalize_homography", 4),("denormalize_homography", 4),("normalize_homography3d", 3),+ ("denormalize_homography3d", 3),]_WRONG_SIZE_IDS = [op_name.replace("_homography", "") for op_name, _ in _WRONG_SIZE_CASES]@@ -327,6 +329,10 @@ def _asymmetric_pose(device: torch.device, dtype: torch.dtype) -> tuple[torch.Te# worked example cannot leave one pin silently testing a different pose._DIRECTION_H = [[[2.0, 0.5, 2.0], [-0.25, 1.0, 1.0], [0.0, 0.0, 1.0]]]_ROUND_TRIP_H = [[[1.25, 0.25, 4.0], [-0.5, 0.75, 2.0], [0.0625, 0.125, 1.0]]]+_DIRECTION_H3D = [[[2.0, 0.5, 0.25, 2.0], [-0.25, 1.0, 0.5, 1.0], [0.125, -0.5, 2.0, 3.0], [0.0, 0.0, 0.0, 1.0]]]+_ROUND_TRIP_H3D = [+ [[1.25, 0.25, 0.5, 4.0], [-0.5, 0.75, 0.25, 2.0], [0.25, -0.125, 1.5, 1.0], [0.0625, 0.125, 0.03125, 1.0]]+]_ARKIT_WORKED_QVEC = [[0.0, 1.0, 0.0, 1.0]]_ARKIT_WORKED_TVEC = [[[1.0], [1.0], [1.0]]]@@ -3713,10 +3719,10 @@ class TestNormalTransformPixel(BaseTester):class TestNormalizeHomography(BaseTester):- # normalize_homography, denormalize_homography and normalize_homography3d have no test class of- # their own in this file -- their existing coverage lives in- # tests/geometry/transform/test_homography_warper.py. The convention pins live here, next to- # normal_transform_pixel, whose corner-aligned convention all three inherit.+ # normalize_homography, denormalize_homography, normalize_homography3d and+ # denormalize_homography3d have no test class of their own in this file -- their existing+ # coverage lives in tests/geometry/transform/test_homography_warper.py. The convention pins live+ # here, next to normal_transform_pixel, whose corner-aligned convention all four inherit.# The CONVENTION pins below (composition, direction, round-trip, batching, 3-D) use sizes of# the form 2**k + 1 (3, 5, 9, 17) so that every 2/(size - 1) is exact in every dtype and those# pins compare at atol=rtol=0. The exactness invariant is theirs alone -- the numerical pins below@@ -3727,24 +3733,23 @@ class TestNormalizeHomography(BaseTester):# pivots -- surviving BOTH inverse routes actually in play (the functions do NOT share one):# normalize_homography inverts through _inverse_3x3_closed_form (cofactor arithmetic, in# float32 for half dtypes -- products and sums of dyadic values, then division by a- # power-of-two determinant, all exact), while denormalize_homography and- # normalize_homography3d go through _torch_inverse_cast (torch.linalg.inv in eager mode,+ # power-of-two determinant, all exact), while denormalize_homography and both 3-D functions+ # go through _torch_inverse_cast (torch.linalg.inv in eager mode,# rounding-free on such triangular matrices, with a float32 upcast for half dtypes and a# closed-form 3x3 fallback under tracing -- each exactness-preserving on these values). A# future non-triangular normalization (a #3904 align_corners variant, say) voids the atol=0# claim on EVERY route and needs a tolerance instead.- # No pin asserts anything about kornia#3962 (no denormalize_homography3d, no- # ColmapQTVecs_to_ARKitQTVecs) -- a missing symbol is a scope question, not a defect.# NOTE: kornia#3904 landed and moved none of these. normalize_homography and# denormalize_homography now take an align_corners argument and forward it to# normal_transform_pixel, but it defaults to True, so the composition, direction, round-trip,# batching and 3-D pins here -- and the #3957 singleton pin -- still see the# corner-aligned 2/(size - 1) constants they were written against. normalize_homography3d has no- # such argument at all. A change to that default, not the parameter, is what would flip them.+ # such argument at all, and neither has denormalize_homography3d. A change to that default, not+ # the parameter, is what would flip them.# They record current default behavior; none of them ratifies that choice as contract.def test_gradcheck(self, device):- # The three functions are on the warp_perspective path and are differentiable in their+ # The four functions are on the warp paths and are differentiable in their# homography argument, and nothing in the suite checked that: neither this file nor# test_homography_warper.py had a gradcheck for any of them before this pin# (`grep -rn "normalize_homography" tests/ | grep gradcheck` was empty). Each is linear in@@ -3771,6 +3776,46 @@ class TestNormalizeHomography(BaseTester):partial(kornia.geometry.conversions.normalize_homography3d, dsize_src=(2, 4, 5), dsize_dst=(3, 8, 9)),(homography3d,),)+ self.gradcheck(+ partial(kornia.geometry.conversions.denormalize_homography3d, dsize_src=(2, 4, 5), dsize_dst=(3, 8, 9)),+ (homography3d,),+ )++ @pytest.mark.parametrize("int_dtype", [torch.int64, torch.int32, torch.uint8, torch.bool])+ @pytest.mark.parametrize("dsize_dst", [(2, 2, 2), (2, 2, 5)])+ def test_exception_denormalize_homography3d_rejects_integer_homography(self, device, int_dtype, dsize_dst):+ # An integer homography used to cast the normalization matrices back to integers:+ # torch.eye(4, dtype=int64) with sizes (2, 2, 2) returned diag(0, 0, 0, 1) and with+ # dst (2, 2, 5) raised a singular-matrix error from the integer-truncated inverse.+ # The function rejects the dtype up front; the caller casts (see #3959 for the siblings).+ # Snippet used to generate the old behaviour (torch only):+ # denormalize_homography3d(torch.eye(4, dtype=torch.int64), (2, 2, 2), (2, 2, 2)) -> diag(0, 0, 0, 1)+ # denormalize_homography3d(torch.eye(4, dtype=torch.int64), (2, 2, 2), (2, 2, 5)) -> _LinAlgError+ homography = torch.eye(4, device=device).to(int_dtype)+ with pytest.raises(TypeCheckError, match=r"dst_pix_trans_src_pix.*floating point.*" + str(int_dtype)):+ kornia.geometry.conversions.denormalize_homography3d(homography, (2, 2, 2), dsize_dst)+ with pytest.raises(TypeError):+ kornia.geometry.conversions.denormalize_homography3d(homography[None], (2, 2, 2), dsize_dst)++ @pytest.mark.parametrize("complex_dtype", [torch.complex64, torch.complex128])+ def test_exception_denormalize_homography3d_rejects_complex_homography(self, complex_dtype):+ # CPU tensors: the guard runs before any arithmetic and MPS has no complex128.+ # _torch_inverse_cast inverts complex matrices in float32, so complex128 lost ~7e-8 on an+ # identity transform (equal sizes, (8, 8, 8)). Only real floating point is accepted.+ # Snippet used to generate the old behaviour (torch only):+ # H = torch.eye(4, dtype=torch.complex128)+ # (denormalize_homography3d(H, (8, 8, 8), (8, 8, 8)) - H).abs().max() -> 6.8e-08+ homography = torch.eye(4, dtype=complex_dtype)+ with pytest.raises(TypeCheckError, match=r"dst_pix_trans_src_pix.*real floating point.*" + str(complex_dtype)):+ kornia.geometry.conversions.denormalize_homography3d(homography, (8, 8, 8), (8, 8, 8))++ def test_dynamo_denormalize_homography3d(self, device, dtype, torch_optimizer):+ homography = torch.eye(4, device=device, dtype=dtype)[None] + 0.125+ op = partial(kornia.geometry.conversions.denormalize_homography3d, dsize_src=(3, 5, 9), dsize_dst=(5, 9, 17))+ actual = torch_optimizer(op)(homography)+ expected = op(homography)++ self.assert_close(actual, expected)def test_convention_maps_normalized_src_to_normalized_dst(self, device, dtype):# Convention pin: the returned matrix has the SAME src -> dst direction as its input,@@ -3940,18 +3985,7 @@ class TestNormalizeHomography(BaseTester):# -> [[4.0, 0.5, 0.125, 4.125], [-1.0, 2.0, 0.5, 1.0],# [1.0, -2.0, 4.0, 5.0], [0.0, 0.0, 0.0, 1.0]]_skip_if_dtype_unavailable(device, dtype)- homography = torch.tensor(- [- [- [2.0, 0.5, 0.25, 2.0],- [-0.25, 1.0, 0.5, 1.0],- [0.125, -0.5, 2.0, 3.0],- [0.0, 0.0, 0.0, 1.0],- ]- ],- device=device,- dtype=dtype,- )+ homography = torch.tensor(_DIRECTION_H3D, device=device, dtype=dtype)normalized = kornia.geometry.conversions.normalize_homography3d(homography, (3, 5, 9), (5, 9, 17))swapped = kornia.geometry.conversions.normalize_homography3d(homography, (5, 9, 17), (3, 5, 9))@@ -3991,6 +4025,84 @@ class TestNormalizeHomography(BaseTester):rtol=0.0,)+ def test_convention_3d_denormalize_is_the_mirror_composition(self, device, dtype):+ # Convention pin: denormalize_homography3d(H, dsize_src, dsize_dst) composes+ # N(dsize_dst)^-1 @ H @ N(dsize_src) -- the mirror of normalize_homography3d, with the same+ # (depth, height, width) argument roles. Pinned on the same input and sizes as the 3-D+ # normalize pin above, and with the size arguments exchanged, so the pin is about direction+ # as well as values.+ # Snippet used to generate expected (torch only, executed on cpu float64; the closed form+ # inv(N_dst) @ H @ N_src with N = normal_transform_pixel3d matches it to 0.0):+ # H = [[2, 0.5, 0.25, 2], [-0.25, 1, 0.5, 1], [0.125, -0.5, 2, 3], [0, 0, 0, 1]]+ # denormalize_homography3d(H, (3, 5, 9), (5, 9, 17))+ # -> [[4.0, 2.0, 2.0, 2.0], [-0.25, 2.0, 2.0, 3.0],+ # [0.0625, -0.5, 4.0, 4.75], [0.0, 0.0, 0.0, 1.0]]+ # denormalize_homography3d(H, (5, 9, 17), (3, 5, 9))+ # -> [[1.0, 0.5, 0.5, 1.0], [-0.0625, 0.5, 0.5, 1.5],+ # [0.015625, -0.125, 1.0, 2.375], [0.0, 0.0, 0.0, 1.0]]+ _skip_if_dtype_unavailable(device, dtype)+ homography = torch.tensor(_DIRECTION_H3D, device=device, dtype=dtype)++ denormalized = kornia.geometry.conversions.denormalize_homography3d(homography, (3, 5, 9), (5, 9, 17))+ swapped = kornia.geometry.conversions.denormalize_homography3d(homography, (5, 9, 17), (3, 5, 9))++ self.assert_close(+ denormalized,+ torch.tensor(+ [[[4.0, 2.0, 2.0, 2.0], [-0.25, 2.0, 2.0, 3.0], [0.0625, -0.5, 4.0, 4.75], [0.0, 0.0, 0.0, 1.0]]],+ device=device,+ dtype=dtype,+ ),+ atol=0.0,+ rtol=0.0,+ )+ self.assert_close(+ swapped,+ torch.tensor(+ [+ [+ [1.0, 0.5, 0.5, 1.0],+ [-0.0625, 0.5, 0.5, 1.5],+ [0.015625, -0.125, 1.0, 2.375],+ [0.0, 0.0, 0.0, 1.0],+ ]+ ],+ device=device,+ dtype=dtype,+ ),+ atol=0.0,+ rtol=0.0,+ )++ def test_convention_3d_normalize_and_denormalize_round_trip(self, device, dtype):+ # Convention pin: the 3-D leg of test_convention_normalize_and_denormalize_round_trip, with+ # the same two-leg structure and the same tolerance reasoning -- both compositions, bitwise+ # at dyadic sizes on a literal whose intermediates are exact, and within atol = 32 * eps,+ # rtol = 8 * eps at non-dyadic sizes, where each entry passes through four matrix products+ # and two 4x4 inverses (both through _torch_inverse_cast here). Measured float32 deviations+ # against a bound of 3.8e-06: 4.77e-07 for denormalize(normalize(H)) and 2.38e-07 for the+ # reverse.+ # Snippet used to generate expected (torch only, executed on cpu at every dtype):+ # H = [[1.25, 0.25, 0.5, 4], [-0.5, 0.75, 0.25, 2], [0.25, -0.125, 1.5, 1],+ # [0.0625, 0.125, 0.03125, 1]]+ # denormalize_homography3d(normalize_homography3d(H, s, d), s, d) == H (bitwise)+ # normalize_homography3d(denormalize_homography3d(H, s, d), s, d) == H (bitwise)+ # with s = (3, 5, 9), d = (5, 9, 17)+ _skip_if_dtype_unavailable(device, dtype)+ normalize_homography3d = kornia.geometry.conversions.normalize_homography3d+ denormalize_homography3d = kornia.geometry.conversions.denormalize_homography3d+ homography = torch.tensor(_ROUND_TRIP_H3D, device=device, dtype=dtype)++ for src, dst, atol, rtol in (+ ((3, 5, 9), (5, 9, 17), 0.0, 0.0),+ ((4, 5, 7), (6, 8, 11), 32.0 * torch.finfo(dtype).eps, 8.0 * torch.finfo(dtype).eps),+ ):+ denorm_of_norm = denormalize_homography3d(normalize_homography3d(homography, src, dst), src, dst)+ norm_of_denorm = normalize_homography3d(denormalize_homography3d(homography, src, dst), src, dst)++ self.assert_close(denorm_of_norm, homography, atol=atol, rtol=rtol)+ self.assert_close(norm_of_denorm, homography, atol=atol, rtol=rtol)+def test_convention_float64_input_gets_float64_normalization_constants(self, device):# A float64 homography is normalized with float64 constants, so the entries carry float64# accuracy. For sizes (4, 4) -> (6, 6) the (0, 0) entry is mathematically@@ -4015,6 +4127,7 @@ class TestNormalizeHomography(BaseTester):("normalize_homography", (4, 4), (6, 6)),("denormalize_homography", (4, 4), (6, 6)),("normalize_homography3d", (4, 4, 7), (6, 6, 9)),+ ("denormalize_homography3d", (4, 4, 7), (6, 6, 9)),],)def test_scripted_normalization_constants_match_eager(self, device, dtype, op_name, src, dst):@@ -4055,7 +4168,7 @@ class TestNormalizeHomography(BaseTester):@pytest.mark.parametrize(("op_name", "wrong_size"), _WRONG_SIZE_CASES, ids=_WRONG_SIZE_IDS)def test_convention_the_shape_guard_accepts_rank_2_and_3_only_3960(self, op_name, wrong_size, device):- # Each of the three functions carries its own copy of the shape guard. It accepts an+ # Each of the four functions carries its own copy of the shape guard. It accepts an# unbatched (N, N) or a batched (B, N, N) matrix -- both come back as (1, N, N) here -- and# rejects a wrong-sized matrix and a rank-4 one itself, with a ValueError naming the# argument and the expected BxNxN shape. _raised_by_a_kornia_guard tells that apart from a@@ -4088,6 +4201,8 @@ class TestNormalizeHomography(BaseTester):kornia.geometry.conversions.denormalize_homography(identity, (4, 5), (4, 1)),kornia.geometry.conversions.normalize_homography3d(identity3d, (1, 4, 5), (3, 8, 9)),kornia.geometry.conversions.normalize_homography3d(identity3d, (3, 8, 9), (1, 4, 5)),+ kornia.geometry.conversions.denormalize_homography3d(identity3d, (1, 4, 5), (3, 8, 9)),+ kornia.geometry.conversions.denormalize_homography3d(identity3d, (3, 8, 9), (1, 4, 5)),]assert all(torch.isfinite(output).all() for output in outputs)@@ -5309,31 +5424,182 @@ class TestCARKitToColmap(BaseTester):self.assert_close(q_colmap[1:], single_q, atol=0.0, rtol=0.0)self.assert_close(t_colmap[1:], single_t, atol=0.0, rtol=0.0)- def test_convention_shapes_are_strictly_batched(self, device):+ @pytest.mark.parametrize("op", [ARKitQTVecs_to_ColmapQTVecs, ColmapQTVecs_to_ARKitQTVecs])+ def test_convention_shapes_are_strictly_batched(self, op, device):# Convention pin: the inputs are strictly qvec (B, 4) and tvec (B, 3, 1) -- an unbatched# (4,) quaternion is rejected, and so is a flat (B, 3) translation. The two rejections come- # from different guards, which the pin keeps visible: both ShapeErrors are raised by- # camtoworld_graphics_to_vision_Rt's OWN KORNIA_CHECK_SHAPE guards (traceback-verified:- # ARKitQTVecs_to_ColmapQTVecs -> camtoworld_graphics_to_vision_Rt -> KORNIA_CHECK_SHAPE;+ # from different guards, which the pin keeps visible: both ShapeErrors are raised by the+ # first Rt conversion's OWN KORNIA_CHECK_SHAPE guards (traceback-verified:+ # ARKitQTVecs_to_ColmapQTVecs -> camtoworld_graphics_to_vision_Rt -> KORNIA_CHECK_SHAPE, and+ # ColmapQTVecs_to_ARKitQTVecs -> worldtocam_to_camtoworld_Rt -> KORNIA_CHECK_SHAPE;# Rt_to_matrix4x4 is never reached -- its guards do not back these rejections and cannot be# deduplicated on the strength of this pin), while a (B, 3) quaternion is caught even# earlier by quaternion_to_rotation_matrix's own "(*, 4)" ValueError.# float32 is hardcoded and the dtype fixture dropped because these guards run before any# arithmetic and cannot depend on the dtype.- # Snippet used to generate expected (torch only, executed on cpu float32):- # ARKitQTVecs_to_ColmapQTVecs(torch.zeros(4), torch.ones(1, 3, 1)) -> ShapeError- # ARKitQTVecs_to_ColmapQTVecs(torch.zeros(1, 4), torch.ones(1, 3)) -> ShapeError- # ARKitQTVecs_to_ColmapQTVecs(torch.zeros(1, 3), torch.ones(1, 3, 1))+ # Snippet used to generate expected (torch only, executed on cpu float32), for either op:+ # op(torch.zeros(4), torch.ones(1, 3, 1)) -> ShapeError+ # op(torch.zeros(1, 4), torch.ones(1, 3)) -> ShapeError+ # op(torch.zeros(1, 3), torch.ones(1, 3, 1))# -> ValueError: Input must be a tensor of shape (*, 4). Got torch.Size([1, 3])quaternion = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=torch.float32)translation = torch.ones(1, 3, 1, device=device, dtype=torch.float32)with pytest.raises(ShapeError):- ARKitQTVecs_to_ColmapQTVecs(quaternion[0], translation)+ op(quaternion[0], translation)with pytest.raises(ShapeError):- ARKitQTVecs_to_ColmapQTVecs(quaternion, translation[..., 0])+ op(quaternion, translation[..., 0])with pytest.raises(ValueError, match=r"shape \(\*, 4\)"):- ARKitQTVecs_to_ColmapQTVecs(quaternion[:, :3], translation)+ op(quaternion[:, :3], translation)++ @pytest.mark.parametrize("int_dtype", [torch.int64, torch.int32, torch.bool])+ @pytest.mark.parametrize("which", ["qvec", "tvec"])+ def test_exception_colmap_to_arkit_rejects_non_floating_inputs(self, device, int_dtype, which):+ # Integer or bool inputs used to surface as a bare torch RuntimeError from linalg.vector_norm+ # ("Expected a floating point or complex tensor") or from the matmul dtype mismatch, naming+ # no kornia argument. Both arguments are now rejected up front by name.+ # Snippet used to generate the old behaviour (torch only):+ # ColmapQTVecs_to_ARKitQTVecs(torch.tensor([[1, 0, 0, 0]]), torch.ones(1, 3, 1)) -> RuntimeError+ # ColmapQTVecs_to_ARKitQTVecs(torch.tensor([[1., 0, 0, 0]]), torch.ones(1, 3, 1, dtype=torch.int64))+ # -> RuntimeError: expected scalar type Float but found Long+ qvec = torch.tensor([[1, 0, 0, 0]], device=device).to(torch.float32)+ tvec = torch.ones(1, 3, 1, device=device, dtype=torch.float32)+ if which == "qvec":+ qvec = qvec.to(int_dtype)+ else:+ tvec = tvec.to(int_dtype)+ with pytest.raises(TypeCheckError, match=rf"{which}.*floating point.*{int_dtype}"):+ ColmapQTVecs_to_ARKitQTVecs(qvec, tvec)++ @pytest.mark.parametrize("complex_dtype", [torch.complex64, torch.complex128])+ @pytest.mark.parametrize("which", ["qvec", "tvec"])+ def test_exception_colmap_to_arkit_rejects_complex_inputs(self, complex_dtype, which):+ # CPU tensors: the guard runs before any arithmetic and MPS has no complex128.+ qvec = torch.tensor([[1.0, 0.0, 0.0, 0.0]])+ tvec = torch.ones(1, 3, 1)+ if which == "qvec":+ qvec = qvec.to(complex_dtype)+ else:+ tvec = tvec.to(complex_dtype)+ with pytest.raises(TypeCheckError, match=rf"{which}.*real floating point.*{complex_dtype}"):+ ColmapQTVecs_to_ARKitQTVecs(qvec, tvec)++ def test_dynamo_colmap_to_arkit(self, device, dtype, torch_optimizer):+ qvec = torch.tensor([[0.7071, 0.0, 0.7071, 0.0], [1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)+ tvec = torch.tensor([[[1.0], [2.0], [3.0]], [[-1.0], [0.5], [2.0]]], device=device, dtype=dtype)+ actual = torch_optimizer(ColmapQTVecs_to_ARKitQTVecs)(qvec, tvec)+ expected = ColmapQTVecs_to_ARKitQTVecs(qvec, tvec)++ self.assert_close(actual[0], expected[0])+ self.assert_close(actual[1], expected[1])++ def test_convention_reverse_input_is_worldtocam_vision_and_output_is_camtoworld_graphics(self, device, dtype):+ # Convention pin for ColmapQTVecs_to_ARKitQTVecs: the frames are the forward's, exchanged.+ # The input is a WORLDTOCAM pose in the VISION frame and the output a CAMTOWORLD pose in+ # the GRAPHICS frame, so the output translation is the camera centre -R^T @ t and the+ # output rotation is R^T @ diag(1, -1, -1). The input rotation is the 120-degree turn about+ # (1, 1, 1) -- q = [0.5, 0.5, 0.5, 0.5], exact in every dtype and NOT symmetric, so a+ # missing transpose or a flip on the wrong side gives a different matrix -- and the+ # translation is asymmetric. The output quaternion is not asserted: its sign is not part of+ # the contract (see test_convention_output_quaternion_sign_is_not_canonical).+ # Snippet used to generate expected (stdlib only, q = [0.5]*4 wxyz, t = (1, 2, 3)):+ # R_colmap = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]+ # R_arkit = R_colmap.T @ diag(1, -1, -1) = [[0, -1, 0], [0, 0, -1], [1, 0, 0]]+ # t_arkit = -R_colmap.T @ (1, 2, 3) = (-2, -3, -1)+ _skip_if_dtype_unavailable(device, dtype)+ qvec = torch.tensor([[0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype)+ tvec = torch.tensor([[[1.0], [2.0], [3.0]]], device=device, dtype=dtype)++ q_arkit, t_arkit = ColmapQTVecs_to_ARKitQTVecs(qvec, tvec)+ rotation = kornia.geometry.conversions.quaternion_to_rotation_matrix(q_arkit)++ self.assert_close(+ rotation,+ torch.tensor([[[0.0, -1.0, 0.0], [0.0, 0.0, -1.0], [1.0, 0.0, 0.0]]], device=device, dtype=dtype),+ )+ self.assert_close(t_arkit, torch.tensor([[[-2.0], [-3.0], [-1.0]]], device=device, dtype=dtype))+ _assert_proper_rotation(rotation)++ @pytest.mark.parametrize("batch_size", [1, 3])+ def test_round_trip(self, batch_size, device, dtype):+ # The two conversions invert each other in both orders. Rotations are compared, not raw+ # quaternions: the output sign is not canonical, and a random pose comes back with the+ # opposite sign about half the time (35 of 64 at float64).+ _skip_if_dtype_unavailable(device, dtype)+ q_arkit = kornia.geometry.axis_angle_to_quaternion(+ torch.tensor([[0.4, -0.6, 0.8]], device=device, dtype=dtype).repeat(batch_size, 1)+ )+ t_arkit = torch.tensor([[[1.0], [-2.0], [3.0]]], device=device, dtype=dtype).repeat(batch_size, 1, 1)++ q_colmap, t_colmap = ARKitQTVecs_to_ColmapQTVecs(q_arkit, t_arkit)+ q_arkit_back, t_arkit_back = ColmapQTVecs_to_ARKitQTVecs(q_colmap, t_colmap)++ assert q_arkit_back.shape == (batch_size, 4)+ assert t_arkit_back.shape == (batch_size, 3, 1)+ self.assert_close(+ kornia.geometry.quaternion_to_rotation_matrix(q_arkit_back),+ kornia.geometry.quaternion_to_rotation_matrix(q_arkit),+ )+ self.assert_close(t_arkit_back, t_arkit)++ q_colmap_back, t_colmap_back = ARKitQTVecs_to_ColmapQTVecs(q_arkit_back, t_arkit_back)+ self.assert_close(+ kornia.geometry.quaternion_to_rotation_matrix(q_colmap_back),+ kornia.geometry.quaternion_to_rotation_matrix(q_colmap),+ )+ self.assert_close(t_colmap_back, t_colmap)++ def test_wart_reverse_zero_quaternion_is_absorbed_3952(self, device, dtype):+ # Wart pin for kornia#3952's reach into ColmapQTVecs_to_ARKitQTVecs, companion to its+ # zero-quaternion warning; same mechanism and same structure as+ # test_wart_zero_quaternion_is_absorbed_3952 above. The documented pose t = (-1, -1, -1) is+ # exact in every dtype.+ # If this fails, #3952 was (partly) fixed, or this function grew a guard -- check which.+ # NOT a contract that absorbing the zero quaternion is correct.+ # Snippet used to generate expected (torch only, executed on cpu):+ # ColmapQTVecs_to_ARKitQTVecs(torch.zeros(1, 4), torch.ones(1, 3, 1))+ # -> q [0., 1., 0., 0.], t [-1., -1., -1.]+ _skip_if_dtype_unavailable(device, dtype)+ zeros = torch.zeros(1, 4, device=device, dtype=dtype)+ identity = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)+ tvec = torch.tensor(_ARKIT_WORKED_TVEC, device=device, dtype=dtype)++ q_zero, t_zero = ColmapQTVecs_to_ARKitQTVecs(zeros, tvec)+ q_identity, t_identity = ColmapQTVecs_to_ARKitQTVecs(identity, tvec)++ assert_close(+ q_zero,+ q_identity,+ atol=0.0,+ rtol=0.0,+ msg=_issue_msg("kornia#3952: the zero quaternion no longer gives the identity input's rotation"),+ )+ assert_close(+ t_zero,+ t_identity,+ atol=0.0,+ rtol=0.0,+ msg=_issue_msg("kornia#3952: the zero quaternion no longer gives the identity input's translation"),+ )+ assert_close(+ t_zero,+ torch.tensor([[[-1.0], [-1.0], [-1.0]]], device=device, dtype=dtype),+ atol=0.0,+ rtol=0.0,+ msg=_issue_msg("kornia#3952: the absorbed zero quaternion no longer produces the documented pose"),+ )++ @pytest.mark.parametrize("op", [ARKitQTVecs_to_ColmapQTVecs, ColmapQTVecs_to_ARKitQTVecs])+ def test_gradcheck(self, op, device):+ # Both conversions are differentiable in the quaternion and the translation; the pose is+ # the generic axis-angle one of test_round_trip.+ _skip_if_dtype_unavailable(device, torch.float64)+ qvec = kornia.geometry.axis_angle_to_quaternion(+ torch.tensor([[0.4, -0.6, 0.8]], device=device, dtype=torch.float64)+ )+ tvec = torch.tensor([[[1.0], [-2.0], [3.0]]], device=device, dtype=torch.float64)++ self.gradcheck(op, (qvec, tvec))def _euler_roundtrip_rotation_error(quaternion, euler) -> torch.Tensor:diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.pyindex b21e67b95..cc647737b 100644--- a/tests/geometry/transform/test_homography_warper.py+++ b/tests/geometry/transform/test_homography_warper.py@@ -594,6 +594,33 @@ class TestHomographyWarper3D(BaseTester):).expand(batch_size, -1, -1)self.assert_close(norm_homo, res)+ @pytest.mark.parametrize("batch_size", [1, 3])+ def test_denormalize_homography_general(self, batch_size, device, dtype):+ # The inverse of test_normalize_homography_general: denormalizing its expected result gives+ # back its input. Every entry and normalization constant is dyadic, so the values are exact+ # in every dtype.+ norm_homo = torch.tensor(+ [[[0.5, 0.0, 0.0, 0.0], [0.0, 0.5, 0.0, 3.5], [0.0, 0.0, 2.0, 7.0], [0.0, 0.0, 0.0, 1.0]]],+ device=device,+ dtype=dtype,+ ).expand(batch_size, -1, -1)++ dst_homo_src = kornia.geometry.conversions.denormalize_homography3d(norm_homo, (2, 2, 5), (2, 2, 5))+ res = torch.tensor(+ [[[0.5, 0.0, 0.0, 1.0], [0.0, 0.5, 0.0, 2.0], [0.0, 0.0, 2.0, 3.0], [0.0, 0.0, 0.0, 1.0]]],+ device=device,+ dtype=dtype,+ ).expand(batch_size, -1, -1)+ assert dst_homo_src.shape == (batch_size, 4, 4)+ self.assert_close(dst_homo_src, res)++ def test_denormalize_homography_invalid_input(self, device):+ with pytest.raises(TypeError, match=r"Input type is not a torch.Tensor"):+ kornia.geometry.conversions.denormalize_homography3d([[1.0]], (3, 5, 7), (6, 8, 11))++ with pytest.raises(ValueError, match="must be a Bx4x4 tensor"):+ kornia.geometry.conversions.denormalize_homography3d(torch.ones(2, 2, device=device), (3, 5, 7), (6, 8, 11))+@pytest.mark.parametrize("offset", [1, 3, 7])@pytest.mark.parametrize("shape", [(4, 5, 6), (2, 4, 6), (4, 3, 9), (5, 7, 8)])def test_warp_grid_translation(self, shape, offset, device, dtype):