π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(geometry): Convention blocks for camera (batch 5b: distortion and calibration) (#4312)
Dmytro Mishkin1af0be0e0ff2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1616aaa42..b6926dcb3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+* Documented camera distortion and calibration conventions (normalized versus pixel inputs, the+ coefficient layout, the `new_K`/`K` roles, the iterative inverses) and added executable pins for+ `kornia.geometry.camera`'s distortion models and `kornia.geometry.calibration`, with the+ tilt-projection, Kannala-Brandt Jacobian and float16 defects tracked in dedicated issues. (#4312)* Documented camera projection-core conventions (`PinholeCamera` frames, integer pixel centres, the twomeanings of depth, the `z = 0` policies) and added executable pins for `kornia.geometry.camera`'sprojection core, with the known scale-rule, aliasing, guard and legacy-API limitations tracked indiff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.pyindex 74a084c83..1e36b8bf1 100644--- a/kornia/geometry/calibration/distort.py+++ b/kornia/geometry/calibration/distort.py@@ -27,13 +27,36 @@ from kornia.core.utils import is_exportingdef tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool = False) -> torch.Tensor:r"""Estimate the tilt projection matrix or the inverse tilt projection matrix.+ Convention:+ - the rotation is ``R = Ry(tauy) @ Rx(taux)`` and ``Pz`` is built from the third column of ``R``. Both+ branches return exactly ``eye(3)`` when ``taux`` and ``tauy`` are zero, which is the case for a+ ``dist`` vector whose 13th and 14th entries are zero.+ - ``return_inverse=True`` returns the inverse of ``Pz @ R``. That is the branch+ :func:`~kornia.geometry.calibration.undistort_points` applies, and it is what reproduces OpenCV's+ ``undistortPoints`` on this repository's own reference values.+ - ``return_inverse=False`` returns ``Pz @ R.T``, so the two branches are not inverses of each other.+ - Scalar angles return :math:`(3, 3)`. For any non-scalar angle shape, all input dimensions+ are flattened and the result is ``(taux.numel(), 3, 3)``; multiple batch axes are not preserved.+ This is tracked as `#4324 <https://github.com/kornia/kornia/issues/4324>`_.++ .. warning::+ OpenCV's ``computeTiltProjectionMatrix``, which this implementation cites, returns ``Pz @ R`` for the+ forward branch, and so does the tilt step written out at the top of the ``kornia.geometry.calibration``+ documentation page; the branch here returns ``Pz @ R.T``. Tracked as+ `#4276 <https://github.com/kornia/kornia/issues/4276>`_. The consequence is silent while both angles+ are zero and otherwise makes+ :func:`~kornia.geometry.calibration.distort_points` and+ :func:`~kornia.geometry.calibration.undistort_points` stop being inverses. The behaviour is documented+ as it is by regression tests.+Args:- taux: Rotation angle in radians around the :math:`x`-axis with shape :math:`(*, 1)`.- tauy: Rotation angle in radians around the :math:`y`-axis with shape :math:`(*, 1)`.+ taux: Rotation angle in radians around the :math:`x`-axis with any shape, matching the other angle.+ tauy: Rotation angle in radians around the :math:`y`-axis with any shape, matching the other angle.return_inverse: False to obtain the tilt projection matrix. True for the inverse matrix.Returns:- torch.Tensor: Inverse tilt projection matrix with shape :math:`(*, 3, 3)`.+ torch.Tensor: Tilt projection matrix, or the inverse tilt projection matrix when ``return_inverse`` is+ True, with shape :math:`(3, 3)` for scalar angles or ``(taux.numel(), 3, 3)`` otherwise."""if taux.shape != tauy.shape:@@ -82,21 +105,52 @@ def distort_points() -> torch.Tensor:r"""Distortion of a set of 2D points based on the lens distortion model.- Radial :math:`(k_1, k_2, k_3, k_4, k_4, k_6)`,+ Radial :math:`(k_1, k_2, k_3, k_4, k_5, k_6)`,tangential :math:`(p_1, p_2)`, thin prism :math:`(s_1, s_2, s_3, s_4)`, and tilt :math:`(\tau_x, \tau_y)`distortion models are considered in this function.+ Convention:+ - ``points`` are **pixel** coordinates in ``(u, v)`` order and so is the result. Pixel centres lie at+ integer coordinates: the top-left centre is ``(0, 0)``.+ :func:`~kornia.geometry.camera.distort_points_affine` and+ :func:`~kornia.geometry.camera.distort_points_kannala_brandt` are the counterparts that take a point+ on the normalized :math:`z = 1` plane and a flat parameter vector instead of ``K`` and ``dist``.+ - ``dist`` is OpenCV's coefficient vector in the order listed under ``Args``. The lengths 4, 5, 8, 12+ and 14 are accepted and every other length raises :class:`ValueError`; an accepted shorter vector is+ zero-padded to 14 internally, so a 4-element vector and its 14-element zero padding give the same+ answer.+ - ``new_K`` and ``K`` play opposite roles: ``new_K`` maps the incoming pixel onto the normalized+ plane and ``K`` maps the distorted normalized point back to pixels. ``new_K`` defaults to ``K``.+ - :func:`~kornia.geometry.calibration.undistort_points` is the inverse map and takes the same+ coefficient layout, with the two intrinsics in the mirrored roles.+ - In eager execution, arbitrary matching leading dimensions work while the tilt path is inactive.+ With non-zero tilt, only unbatched inputs or one leading batch dimension are supported; two or more leading+ dimensions are flattened by :func:`~kornia.geometry.calibration.tilt_projection`. ONNX export always+ takes that path, including for zero tilt. Tracked as `#4324 <https://github.com/kornia/kornia/issues/4324>`_.++ .. warning::+ Non-zero tilt uses the forward branch of :func:`tilt_projection` and breaks the inverse round trip;+ see that function and `#4276 <https://github.com/kornia/kornia/issues/4276>`_ for the explanation.++ .. warning::+ ``torch.compile(fullgraph=True)`` fails on this function because the tilt test reads the coefficient+ values on the host; ONNX export is already routed around it by ``is_exporting()``. Tracked as+ `#4286 <https://github.com/kornia/kornia/issues/4286>`_.+Args:points: Input image points with shape :math:`(*, N, 2)`.K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.dist: Distortion coefficients:math:`(k_1,k_2,p_1,p_2[,k_3[,k_4,k_5,k_6[,s_1,s_2,s_3,s_4[,\tau_x,\tau_y]]]])`. This isa vector with 4, 5, 8, 12 or 14 elements with shape :math:`(*, n)`.- new_K: Intrinsic camera matrix of the distorted image. By default, it is the same as K but you may additionally- scale and shift the result by using a different matrix. Shape: :math:`(*, 3, 3)`. Default: None.+ new_K: Intrinsic camera matrix used to map the incoming ``points`` from pixels onto the normalized+ :math:`z = 1` plane -- the opposite of what the argument order suggests, since ``K`` is the one+ that maps the distorted normalized point back to pixels. By default it is the same as ``K``, in+ which case both steps use the same camera; a different matrix rescales and shifts the **input**,+ not the result. Shape: :math:`(*, 3, 3)`. Default: None.Returns:- Undistorted 2D points with shape :math:`(*, N, 2)`.+ Distorted 2D points with shape :math:`(*, N, 2)`.Example:>>> points = torch.rand(1, 1, 2)diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.pyindex 509fdd4b6..fe0df0368 100644--- a/kornia/geometry/calibration/pnp.py+++ b/kornia/geometry/calibration/pnp.py@@ -83,6 +83,19 @@ def solve_pnp_dlt(Another bad condition occurs when the camera and the points lie on atwisted cubic. However, this function does not check for this condition.+ Convention:+ - the returned :math:`(B, 3, 4)` matrix is the **world-to-camera** ``[R | t]``: it maps a world point+ into the camera frame, rather than storing a camera-to-world pose. If the camera frame is the world+ frame shifted so that ``X_cam = X_world + (1, 0, 0)``, the recovered ``t`` is ``(+1, 0, 0)`` and not+ ``(-1, 0, 0)``.+ - ``intrinsics`` is the :math:`(B, 3, 3)` ``K``; the :math:`(B, 4, 4)` matrix that a+ ``PinholeCamera`` stores is rejected by the shape check.+ - ``weights`` scales the two rows each point contributes to the linear system. That system is+ homogeneous, so a uniform ``weights`` leaves the answer unchanged up to rounding, and a zero weight+ drops that point from the fit.+ - too few points raise a ``BaseError`` whose message names no argument, while a degenerate+ ``world_points`` raises :class:`AssertionError` from the singular-value check described above.+Args:world_points : A torch.Tensor with shape :math:`(B, N, 3)` representingthe points in the world space.diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.pyindex f800b766e..39f7dc8ed 100644--- a/kornia/geometry/calibration/undistort.py+++ b/kornia/geometry/calibration/undistort.py@@ -41,14 +41,51 @@ def undistort_points(tangential :math:`(p_1, p_2)`, thin prism :math:`(s_1, s_2, s_3, s_4)`, and tilt :math:`(\tau_x, \tau_y)`distortion models are considered in this function.+ Convention:+ - ``points`` are **pixel** coordinates in ``(u, v)`` order and so is the result. Pixel centres lie at+ integer coordinates: the top-left centre is ``(0, 0)``.+ - ``dist`` follows the coefficient layout documented on+ :func:`~kornia.geometry.calibration.distort_points`, which is the forward map this function inverts;+ the accepted lengths and the internal zero-padding are the same.+ - ``K`` and ``new_K`` play the mirror image of their roles in the forward map: ``K`` maps the incoming+ pixel onto the normalized plane and ``new_K`` maps the undistorted normalized point back to pixels.+ - the inverse is a fixed-point iteration of ``num_iters`` steps, not a closed form, so the round trip+ through :func:`~kornia.geometry.calibration.distort_points` closes only to the accuracy that+ iteration has reached. Within its convergence region, increasing ``num_iters`` can improve the+ result until it reaches the working dtype's rounding floor; ``float16`` can reach that floor at the+ default count, while ``float32`` and ``float64`` can continue to improve.+ - In eager execution, arbitrary matching leading dimensions work while the tilt path is inactive.+ With non-zero tilt, use one explicit leading batch dimension; multiple leading dimensions and+ unbatched intrinsics can fail. ONNX export always takes that path, including for zero tilt, so+ even unbatched inputs with four coefficients can fail. Tracked as `#4324 <https://github.com/kornia/kornia/issues/4324>`_.++ .. warning::+ The iteration has no convergence test and no valid-radius guard. Outside the iteration+ convergence region it can enter a two-point cycle, so the answer depends on whether ``num_iters``+ is odd or even and no count converges. Tracked as `#4285 <https://github.com/kornia/kornia/issues/4285>`_.++ .. warning::+ Non-zero tilt breaks the forward/inverse round trip; see+ :func:`~kornia.geometry.calibration.tilt_projection` and+ `#4276 <https://github.com/kornia/kornia/issues/4276>`_ for the explanation.++ .. warning::+ This function has the same ``torch.compile(fullgraph=True)`` limitation as+ :func:`~kornia.geometry.calibration.distort_points`; see that function for the explanation. Tracked as+ `#4286 <https://github.com/kornia/kornia/issues/4286>`_.+Args:points: Input image points with shape :math:`(*, N, 2)`.K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.dist: Distortion coefficients:math:`(k_1,k_2,p_1,p_2[,k_3[,k_4,k_5,k_6[,s_1,s_2,s_3,s_4[,\tau_x,\tau_y]]]])`. This isa vector with 4, 5, 8, 12 or 14 elements with shape :math:`(*, n)`.- new_K: Intrinsic camera matrix of the distorted image. By default, it is the same as K but you may additionally- scale and shift the result by using a different matrix. Shape: :math:`(*, 3, 3)`. Default: None.+ new_K: Intrinsic camera matrix used to map the undistorted normalized point back to pixels, while ``K``+ is the one that maps the incoming distorted ``points`` from pixels onto the normalized+ :math:`z = 1` plane -- the mirror image of the two roles in+ :func:`~kornia.geometry.calibration.distort_points`. By default it is the same as ``K``, in which+ case both steps use the same camera; a different matrix rescales and shifts the **result**.+ Shape: :math:`(*, 3, 3)`. Default: None.num_iters: Number of undistortion iterations. Default: 5.Returns:@@ -140,10 +177,34 @@ def undistort_points(def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) -> torch.Tensor:r"""Compensate an image for lens distortion.- Radial :math:`(k_1, k_2, k_3, k_4, k_4, k_6)`,+ Radial :math:`(k_1, k_2, k_3, k_4, k_5, k_6)`,tangential :math:`(p_1, p_2)`, thin prism :math:`(s_1, s_2, s_3, s_4)`, and tilt :math:`(\tau_x, \tau_y)`distortion models are considered in this function.+ Convention:+ - In eager execution while the tilt path is inactive, the leading dimensions of ``image`` (everything+ in front of ``C, H, W``), of ``K`` (in front of its :math:`3 \times 3` block) and of ``dist`` (in+ front of its ``n`` coefficients) must match exactly. They may be empty, a single batch axis, or+ several axes deep. The one exception is the legacy unbatched call -- a :math:`(1, C, H, W)` image+ with a :math:`(3, 3)` ``K`` and an :math:`(n,)` ``dist``. With non-zero tilt, at most one leading batch+ axis is supported; ONNX export always takes the tilt path, including for zero tilt. Tracked as+ `#4324 <https://github.com/kornia/kornia/issues/4324>`_.+ - the sampling map is built by applying :func:`~kornia.geometry.calibration.distort_points` to the+ grid of integer pixel centres that :func:`~kornia.geometry.grid.create_meshgrid` enumerates: the+ top-left centre is ``(0, 0)``.+ - the map is resampled with ``align_corners=True``; the flag is baked in and the function exposes no+ way to change it.+ - with every coefficient zero the map is the pixel grid up to floating-point rounding, but the image+ still goes through the bilinear sampler, so the output is equal to the input at the working dtype's+ tolerance and is not bit-identical to it.++ .. warning::+ The sampling map is built with :func:`~kornia.geometry.calibration.distort_points`, so a non-zero+ :math:`\tau_x` or :math:`\tau_y` carries the tilt defect tracked in+ `#4276 <https://github.com/kornia/kornia/issues/4276>`_ into the resampled image, which is visibly+ different from the untilted one. See :func:`~kornia.geometry.calibration.tilt_projection` for the full+ explanation.+Args:image: Input image with shape :math:`(*, C, H, W)`.K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.diff --git a/kornia/geometry/camera/distortion_affine.py b/kornia/geometry/camera/distortion_affine.pyindex 7487680e7..978d12c82 100644--- a/kornia/geometry/camera/distortion_affine.py+++ b/kornia/geometry/camera/distortion_affine.py@@ -32,6 +32,15 @@ def distort_points_affine(projected_points_in_camera_z1_plane: torch.Tensor, par\begin{bmatrix} x \\ y \end{bmatrix} +\begin{bmatrix} c_x \\ c_y \end{bmatrix}+ Convention:+ - ``projected_points_in_camera_z1_plane`` is a point on the **normalized** :math:`z = 1` plane, not a+ pixel, and ``params`` is the flat vector ``[fx, fy, cx, cy]``; the result is in pixels.+ Pixel centres lie at integer coordinates: the top-left centre is ``(0, 0)``.+ - :func:`~kornia.geometry.calibration.distort_points` is the same camera parametrized by a+ :math:`(*, 3, 3)` ``K`` and an OpenCV coefficient vector; it takes a **pixel** input instead.+ - :func:`undistort_points_affine` inverts this map in closed form -- one subtraction and one division+ per axis, with no iteration; the Kannala-Brandt pair needs a Gauss-Newton solve for the same step.+Args:projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).params: torch.Tensor representing the parameters of the affine distortion model with shape (..., 4).@@ -66,9 +75,17 @@ def undistort_points_affine(distorted_points_in_camera: torch.Tensor, params: to.. math::\begin{bmatrix} x \\ y \end{bmatrix} =- \begin{bmatrix} u \\ v \end{bmatrix} -- \begin{bmatrix} c_x \\ c_y \end{bmatrix}\begin{bmatrix} f_x & 0 \\ 0 & f_y \end{bmatrix}^{-1}+ \left( \begin{bmatrix} u \\ v \end{bmatrix} -+ \begin{bmatrix} c_x \\ c_y \end{bmatrix} \right)++ Convention:+ - ``distorted_points_in_camera`` is a **pixel** coordinate and the result is a point on the normalized+ :math:`z = 1` plane; ``params`` is the same ``[fx, fy, cx, cy]`` vector that+ :func:`distort_points_affine` takes, and this function is its closed-form inverse.+ - a zero ``fx`` or ``fy`` is not rejected: that axis divides by zero and comes back as an infinity+ carrying the numerator's sign, or as ``nan`` for a point that sits exactly on the corresponding+ principal-point coordinate.Args:distorted_points_in_camera: torch.Tensor representing the points to undistort with shape (..., 2).@@ -100,19 +117,25 @@ def undistort_points_affine(distorted_points_in_camera: torch.Tensor, params: todef dx_distort_points_affine(projected_points_in_camera_z1_plane: torch.Tensor, params: torch.Tensor) -> torch.Tensor:- r"""Compute the derivative of the x distortion with respect to the x coordinate.+ r"""Compute the Jacobian of the affine distortion with respect to the point... math::- \frac{\partial u}{\partial x} =+ \frac{\partial (u, v)}{\partial (x, y)} =\begin{bmatrix} f_x & 0 \\ 0 & f_y \end{bmatrix}+ Convention:+ - the result is the :math:`(..., 2, 2)` Jacobian of :func:`distort_points_affine` with respect to the+ **point**: rows are the output components ``(u, v)``, columns the input components ``(x, y)``. It+ agrees with :func:`torch.autograd.functional.jacobian` of the same function.+ - the map is affine, so that Jacobian is ``diag(fx, fy)`` and does not depend on the point.+Args:projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).params: torch.Tensor representing the parameters of the affine distortion model with shape (..., 4).Returns:- torch.Tensor representing the derivative of the x distortion with respect to the x coordinate- with shape (..., 2).+ torch.Tensor representing the Jacobian of the distortion with respect to the point+ with shape (..., 2, 2).Example:>>> points = torch.tensor([319.5, 239.5]) # center of a 640x480 imagediff --git a/kornia/geometry/camera/distortion_kannala_brandt.py b/kornia/geometry/camera/distortion_kannala_brandt.pyindex e155cbe9b..cdfbfb304 100644--- a/kornia/geometry/camera/distortion_kannala_brandt.py+++ b/kornia/geometry/camera/distortion_kannala_brandt.py@@ -64,6 +64,16 @@ def distort_points_kannala_brandt() -> torch.Tensor:r"""Distort points from the canonical z=1 plane into the camera frame using the Kannala-Brandt model.+ Convention:+ - ``projected_points_in_camera_z1_plane`` is a point on the **normalized** :math:`z = 1` plane, not a+ pixel, and the result is in pixels.+ Pixel centres lie at integer coordinates: the top-left centre is ``(0, 0)``.+ - ``params`` is the flat vector ``[fx, fy, cx, cy, k0, k1, k2, k3]``: the first four are the affine+ part that :func:`~kornia.geometry.camera.distort_points_affine` takes on its own, and ``k0`` to+ ``k3`` multiply :math:`\theta^2`, :math:`\theta^4`, :math:`\theta^6` and :math:`\theta^8` in the+ fish-eye polynomial.+ - :func:`undistort_points_kannala_brandt` is the inverse map.+Args:projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).params: torch.Tensor representing the parameters of the Kannala-Brandt distortion model with shape (..., 8).@@ -102,6 +112,29 @@ def distort_points_kannala_brandt(def undistort_points_kannala_brandt(distorted_points_in_camera: torch.Tensor, params: torch.Tensor) -> torch.Tensor:r"""Undistort points from the camera frame into the canonical z=1 plane using the Kannala-Brandt model.+ Convention:+ - ``distorted_points_in_camera`` is a **pixel** coordinate and the result is a point on the normalized+ :math:`z = 1` plane; ``params`` is the same 8-element vector documented on+ :func:`distort_points_kannala_brandt`.+ - the inverse is a fixed number of Gauss-Newton steps rather than a closed form: the step count is not+ a parameter and there is no convergence test, so the round trip through+ :func:`distort_points_kannala_brandt` closes only to the accuracy that iteration has reached. The+ step count cannot be raised by a caller. In ``float32`` the residual reaches the rounding floor; in+ ``float64`` it stops at about ``1e-8`` on the normalized plane, because the final radial rescale+ divides by ``r + 1e-8`` rather than ``r`` and so scales every result by ``1 - 1e-8 / r``. That is the+ ``float64`` side of `#4308 <https://github.com/kornia/kornia/issues/4308>`_.+ :func:`~kornia.geometry.camera.undistort_points_affine` is the closed-form contrast.+ - three small constants guard the Newton start (``1e-16``), Newton denominator (``1e-12``), and final+ radial rescale (``1e-8``), so a point at the principal point comes back as the origin rather than+ ``nan`` -- as long as those constants are representable in the dtype of ``params``, which is the+ dtype the whole body runs in.++ .. warning::+ All three guard constants underflow to zero in ``float16``. At the principal point the unguarded Newton+ denominator is one, but the final ``1e-8`` rescale guard then underflows and returns ``nan`` instead of+ the origin. ``float32``, ``float64`` and ``bfloat16`` are unaffected. Tracked as+ `#4308 <https://github.com/kornia/kornia/issues/4308>`_.+Args:distorted_points_in_camera: torch.Tensor representing the points to undistort with shape (..., 2).params: torch.Tensor representing the parameters of the Kannala-Brandt distortion model with shape (..., 8).@@ -167,19 +200,29 @@ def undistort_points_kannala_brandt(distorted_points_in_camera: torch.Tensor, padef dx_distort_points_kannala_brandt(projected_points_in_camera_z1_plane: torch.Tensor, params: torch.Tensor) -> torch.Tensor:- r"""Compute the derivative of the x distortion with respect to the x coordinate.-- .. math::- \frac{\partial u}{\partial x} =- \begin{bmatrix} f_x & 0 \\ 0 & f_y \end{bmatrix}+ r"""Return the analytic matrix the Kannala-Brandt model provides as its distortion Jacobian.++ Convention:+ - the result has shape :math:`(..., 2, 2)` and is laid out like the Jacobian that+ :func:`~kornia.geometry.camera.dx_distort_points_affine` returns: rows are the output components+ ``(u, v)``, columns the input components ``(x, y)``.++ .. warning::+ The matrix this function returns today is **not** the Jacobian of+ :func:`distort_points_kannala_brandt`. It disagrees with :func:`torch.autograd.functional.jacobian`+ and with central finite differences, which agree with each other, and transposing it does not close+ the gap; at the origin it is ``nan``. Tracked as+ `#4277 <https://github.com/kornia/kornia/issues/4277>`_. The ``Example:`` block below prints the value+ this implementation returns today and is deliberately left byte-identical -- it is the executable+ evidence for the issue, and the repair has to re-derive it together with the existing regression tests.Args:projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).params: torch.Tensor representing the parameters of the Kannala-Brandt distortion model with shape (..., 8).Returns:- torch.Tensor representing the derivative of the x distortion with respect to the x coordinate- with shape (..., 2).+ torch.Tensor representing the derivative of the distortion with respect to the point+ with shape (..., 2, 2).Example:>>> points = torch.tensor([1., 2.])diff --git a/tests/geometry/calibration/test_distort.py b/tests/geometry/calibration/test_distort.pyindex 2dfe3ae81..7a509e3ee 100644--- a/tests/geometry/calibration/test_distort.py+++ b/tests/geometry/calibration/test_distort.py@@ -18,9 +18,33 @@import pytestimport torch-from kornia.geometry.calibration.distort import distort_points+from kornia.geometry.calibration.distort import distort_points, tilt_projection+from kornia.geometry.camera.distortion_affine import distort_points_affinefrom testing.base import BaseTester+from testing.geometry.linalg import euler_angles_to_rotation_matrix+++def _pz_r(taux, tauy, device, dtype):+ """Build OpenCV's ``(R, Pz)`` pair for a tilt of ``(taux, tauy)`` radians.++ Uses the independent Euler-angle test helper for ``R = Ry(tauy) @ Rx(taux)``;+ ``Pz`` follows OpenCV's ``modules/calib3d/src/distortion_model.hpp``.+ OpenCV's tilt projection is ``Pz @ R``; kornia returns ``Pz @ R.T`` (#4276).+ """+ taux = torch.tensor([taux], device=device, dtype=dtype)+ tauy = torch.tensor([tauy], device=device, dtype=dtype)+ one, zero = torch.ones_like(taux), torch.zeros_like(taux)+ r = euler_angles_to_rotation_matrix(-taux, -tauy, zero)[:, :3, :3]+ p_z = torch.stack(+ [r[..., 2, 2], zero, -r[..., 0, 2], zero, r[..., 2, 2], -r[..., 1, 2], zero, zero, one], -1+ ).reshape(-1, 3, 3)+ return r, p_z+++def _k_asymmetric(device, dtype):+ """``fx = fy = 100``, ``cx = 4``, ``cy = 3`` -- ``cx != cy`` so a transposed reading changes the literals."""+ return torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)class TestDistortPoints(BaseTester):@@ -105,6 +129,205 @@ class TestDistortPoints(BaseTester):assert self.gradcheck(distort_points, (points, K, distCoeff, new_K), raise_exception=True, fast_mode=True)+ def test_convention_accepts_4_5_8_12_14_coefficients_and_rejects_6(self, device, dtype):+ # Convention pin: the distortion vector is OpenCV's+ # (k1, k2, p1, p2[, k3[, k4, k5, k6[, s1, s2, s3, s4[, taux, tauy]]]]), so only the five prefix lengths+ # 4, 5, 8, 12 and 14 are meaningful; anything else -- 6 and 3 below -- is a ValueError, not a silent+ # zero-pad. Shorter accepted vectors ARE zero-padded to 14 internally, which is why 4 and 14 zeros give+ # the same answer. undistort_points enforces the identical rule.+ # Snippet used to generate expected: distort_points(pts, K, zeros(1, n)) for n in (3, 4, 5, 6, 8, 12, 14)+ # executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0, cpu and mps, every dtype) -> shape (1, 2, 2)+ # for the five accepted lengths, ValueError("Invalid number of distortion coefficients. Got 6") for 6;+ # torch.equal between the 4-coefficient answer and its 14-coefficient zero-padding -> True on every cell.+ points = torch.tensor([[[54.0, 53.0], [-16.0, 23.0]]], device=device, dtype=dtype)+ K = _k_asymmetric(device, dtype)+ for n in (4, 5, 8, 12, 14):+ assert distort_points(points, K, torch.zeros(1, n, device=device, dtype=dtype)).shape == (1, 2, 2)+ for n in (3, 6):+ with pytest.raises(ValueError, match="Invalid number of distortion coefficients"):+ distort_points(points, K, torch.zeros(1, n, device=device, dtype=dtype))+ short = torch.tensor([[0.1, 0.01, 0.001, 0.001]], device=device, dtype=dtype)+ padded = torch.cat([short, torch.zeros(1, 10, device=device, dtype=dtype)], -1)+ assert not torch.allclose(distort_points(points, K, short).float(), points.float())+ assert torch.equal(distort_points(points, K, short), distort_points(points, K, padded))++ def test_convention_zero_coefficients_are_a_no_op_at_dtype_tolerance(self, device, dtype):+ # Convention pin: with every coefficient zero, distort_points normalizes+ # with new_K (= K here) and denormalizes with K, so it is a no-op -- but only up to the dtype tolerance,+ # because ``(u - cx) / fx`` followed by ``fx * x + cx`` is not an exact round trip for a general pixel.+ # This is the GENERAL statement; the bit-for-bit case is scoped in the sibling pin below.+ # The points sit half a focal length off the principal point on both sides of it, so the round trip is+ # exercised at a radius where a non-zero coefficient would move them by 2.775 px, and the fractional+ # offsets keep ``(u - cx) / fx`` off the exactly-representable grid.+ # Snippet used to generate expected: (distort_points(pts, K, zeros(1, 4)) - pts).abs().max() on+ # [[54.3, 53.7], [-16.1, 23.9]] executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0), differenced+ # in the working dtype -> cpu float32 3.81e-06 (torch.equal False), float64 0.0, float16 3.13e-02,+ # bfloat16 2.50e-01; mps float32 3.81e-06, float16 3.13e-02.+ points = torch.tensor([[[54.3, 53.7], [-16.1, 23.9]]], device=device, dtype=dtype)+ K = _k_asymmetric(device, dtype)+ self.assert_close(distort_points(points, K, torch.zeros(1, 4, device=device, dtype=dtype)), points)++ def test_convention_zero_coefficients_are_bit_exact_on_these_points(self, device, dtype):+ # On these four coordinates the normalize/denormalize arithmetic rounds back to the input+ # bit for bit in the tested dtypes, even though +/-0.2 are not exactly representable in binary.+ # This is NOT a general bit-for-bit no-op. Executed counterexample on the same K, 2026-09-06 on the+ # commit c0b50ad7 (torch 2.14.0): the perturbed points [[54.3, 53.7], [-16.1, 23.9]] give torch.equal+ # False with a residual of 3.81e-06 in cpu float32 (3.13e-02 in float16, 2.50e-01 in bfloat16); only the+ # float64 cell is still exact there.+ # Snippet used to generate expected: torch.equal(distort_points(pts, K, zeros(1, 4)), pts) on+ # [[54.0, 53.0], [-16.0, 23.0]] executed 2026-09-06 -> True on cpu for float32/float64/float16/bfloat16+ # and on mps for float32/float16.+ points = torch.tensor([[[54.0, 53.0], [-16.0, 23.0]]], device=device, dtype=dtype)+ K = _k_asymmetric(device, dtype)+ assert torch.equal(distort_points(points, K, torch.zeros(1, 4, device=device, dtype=dtype)), points)++ def test_convention_new_K_normalizes_and_K_denormalizes(self, device, dtype):+ # Convention pin: the two intrinsics play OPPOSITE roles -- new_K maps+ # the incoming pixel to the normalized z = 1 plane, K maps the distorted normalized point back to pixels.+ # Every intrinsic is distinct here (new_K: fx 5, fy 7, cx 2, cy 4; K: fx 2, fy 3, cx 1, cy 1), so+ # swapping the two arguments, or fx with fy, changes both literals: (10, 10) normalizes to+ # ((10-2)/5, (10-4)/7) = (1.6, 6/7) and denormalizes to (2*1.6+1, 3*6/7+1) = (4.2, 3.571428...).+ # The diag(2, 2, 1) probe is the same claim with the roles reversed: a (1, 2) pixel+ # under new_K = diag(2, 2, 1) and K = eye(3) comes back as (0.5, 1.0).+ # Snippet used to generate expected: distort_points([[[10., 10.]]], K, zeros(1, 4), new_K) executed+ # 2026-09-06 on commit c0b50ad7 (torch 2.14.0, cpu float32) -> [[[4.199999809265137,+ # 3.5714285373687744]]]; the same call on mps float32 gives the same value.+ K = torch.tensor([[[2.0, 0.0, 1.0], [0.0, 3.0, 1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ new_K = torch.tensor([[[5.0, 0.0, 2.0], [0.0, 7.0, 4.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ zero_dist = torch.zeros(1, 4, device=device, dtype=dtype)+ points = torch.tensor([[[10.0, 10.0]]], device=device, dtype=dtype)+ self.assert_close(+ distort_points(points, K, zero_dist, new_K),+ torch.tensor([[[4.2, 3.5714285714285716]]], device=device, dtype=dtype),+ )+ self.assert_close(+ distort_points(+ torch.tensor([[[1.0, 2.0]]], device=device, dtype=dtype),+ torch.eye(3, device=device, dtype=dtype)[None],+ zero_dist,+ torch.tensor([[[2.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype),+ ),+ torch.tensor([[[0.5, 1.0]]], device=device, dtype=dtype),+ )++ def test_convention_agrees_with_distort_points_affine_on_the_same_camera(self, device, dtype):+ # Convention pin: the two paths encode the same+ # pinhole camera through different INPUT DOMAINS and parametrizations. distort_points_affine takes a+ # normalized z = 1 point and a flat [fx, fy, cx, cy]; calibration.distort_points takes a pixel point, a+ # (3, 3) K and a coefficient vector. Feeding the normalized point through distort_points with+ # new_K = eye(3) (so the normalization step is the identity) and K = the same camera reproduces the+ # affine answer bit for bit, and the already-pixel point with zero coefficients+ # gives the same [54, 28].+ # Snippet used to generate expected: torch.equal(distort_points([[[0.5, 0.25]]], K, zeros(1, 4), eye(3)[None])+ # .reshape(2), distort_points_affine([0.5, 0.25], [100., 100., 4., 3.])) executed 2026-09-06 on the+ # commit c0b50ad7 (torch 2.14.0, cpu float32) -> True, value [54., 28.].+ K = _k_asymmetric(device, dtype)+ zero_dist = torch.zeros(1, 4, device=device, dtype=dtype)+ expected = torch.tensor([[[54.0, 28.0]]], device=device, dtype=dtype)+ affine = distort_points_affine(+ torch.tensor([0.5, 0.25], device=device, dtype=dtype),+ torch.tensor([100.0, 100.0, 4.0, 3.0], device=device, dtype=dtype),+ )+ self.assert_close(affine.reshape(1, 1, 2), expected, atol=0.0, rtol=0.0)+ self.assert_close(+ distort_points(+ torch.tensor([[[0.5, 0.25]]], device=device, dtype=dtype),+ K,+ zero_dist,+ torch.eye(3, device=device, dtype=dtype)[None],+ ),+ expected,+ atol=0.0,+ rtol=0.0,+ )+ self.assert_close(distort_points(expected, K, zero_dist), expected, atol=0.0, rtol=0.0)++ def test_convention_tilt_projection_zero_angles_are_the_identity(self, device, dtype):+ # Convention pin: tilt_projection(0, 0) is exactly eye(3) in BOTH branches,+ # which is why a caller who leaves the 13th and 14th coefficients at zero never meets kornia#4276 -- and+ # why the round trip pinned in test_undistort.py closes to 0.0 with tau = 0 and not with tau != 0.+ # Snippet used to generate expected: torch.equal(tilt_projection(tensor([0.]), tensor([0.])), eye(3)[None])+ # executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0) -> True on cpu for float32/float64/float16/+ # bfloat16 and on mps for float32/float16; same for return_inverse=True.+ zero = torch.zeros(1, device=device, dtype=dtype)+ identity = torch.eye(3, device=device, dtype=dtype)[None]+ assert torch.equal(tilt_projection(zero, zero), identity)+ self.assert_close(tilt_projection(zero, zero, True), identity, atol=0.0, rtol=0.0)++ def test_convention_tilt_projection_inverse_branch_inverts_pz_times_r(self, device, dtype):+ # Convention pin: the ``return_inverse=True`` branch is the inverse of OpenCV's+ # ``Pz @ R``, not of kornia's own forward branch -- ``(Pz @ R) @ inverse`` is the identity at the dtype+ # tolerance, while ``(Pz @ R.T) @ inverse`` (kornia's forward reading, kornia#4276) is not.+ # This pin is PERMANENT and outlives the #4276 repair, and that is its point: the strict xfail below only+ # asks for ``forward @ inverse == I``, which the WRONG repair -- moving the inverse branch to+ # ``inv(Pz @ R.T)`` -- would satisfy just as well. #4276's Expected section forbids that repair because+ # undistort_points uses this branch and is what currently reproduces the repo's own cv2.undistortPoints+ # values (TestUndistortPoints::test_opencv_all_coeff in test_undistort.py). Written as a matrix product+ # rather than torch.linalg.inv so it runs on mps.+ # Snippet used to generate expected: ((Pz @ R) @ tilt_projection([0.1], [0.2], True) - eye(3)).abs().max()+ # executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0), differenced in the working dtype -> cpu+ # float32 1.19e-07, float64 2.22e-16, float16 4.88e-04, bfloat16 3.91e-03; mps float32 1.19e-07,+ # float16 4.88e-04. The same product built from Pz @ R.T is 0.396 away from the identity on every cell.+ # The second assertion uses a 0.1 SEPARATOR rather than ``not torch.allclose``: the identity's zero+ # entries pull torch.allclose's default atol down to 1e-08, which the correct reading's own float32+ # residual (1.19e-07) already exceeds, so ``not allclose`` would hold for BOTH readings and discriminate+ # nothing. 0.1 sits between the two populations (worst correct cell 3.91e-03, wrong reading 0.396).+ r, p_z = _pz_r(0.1, 0.2, device, dtype)+ inverse = tilt_projection(+ torch.tensor([0.1], device=device, dtype=dtype), torch.tensor([0.2], device=device, dtype=dtype), True+ )+ identity = torch.eye(3, device=device, dtype=dtype)[None]+ self.assert_close((p_z @ r) @ inverse, identity)+ wrong = (p_z @ r.transpose(-1, -2)) @ inverse+ assert (wrong - identity).abs().max().item() > 0.1++ def test_wart_tilt_projection_forward_is_pz_times_r_transpose_4276(self, device, dtype):+ # Wart pin for kornia#4276: the forward branch returns ``Pz @ R.T``+ # where OpenCV's computeTiltProjectionMatrix returns ``Pz @ R``, while the return_inverse=True branch IS+ # the OpenCV inverse (pinned permanently by+ # test_convention_tilt_projection_inverse_branch_inverts_pz_times_r above). The consequence is that the two+ # branches of the same function are not inverses of each other: forward @ inverse is visibly not eye(3).+ # taux = 0.1 != tauy = 0.2, so Pz @ R and Pz @ R.T are different matrices here (they coincide at 0, 0).+ # Snippet used to generate expected: (tilt_projection([0.1], [0.2]) - Pz @ R.transpose(-1, -2)).abs().max()+ # executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0) -> 0.0 on cpu for float32/float64/float16/+ # bfloat16 and on mps for float32/float16; forward @ inverse deviates from eye(3) by 0.3963 (cpu float32).+ # The last two assertions use a 0.1 separator for the same reason as the inverse-branch pin above:+ # ``not torch.allclose`` against an identity is satisfied by a 1e-07 residual too, so it would not flip+ # when #4276 is repaired. Pins the CURRENT value; NOT a contract; delete when #4276 is repaired.+ r, p_z = _pz_r(0.1, 0.2, device, dtype)+ taux = torch.tensor([0.1], device=device, dtype=dtype)+ tauy = torch.tensor([0.2], device=device, dtype=dtype)+ forward = tilt_projection(taux, tauy)+ self.assert_close(forward, p_z @ r.transpose(-1, -2), atol=0.0, rtol=0.0)+ assert (forward - p_z @ r).abs().max().item() > 0.1+ inverse = tilt_projection(taux, tauy, True)+ identity = torch.eye(3, device=device, dtype=dtype)[None]+ assert (forward @ inverse - identity).abs().max().item() > 0.1++ @pytest.mark.xfail(+ strict=True, reason="kornia#4276: the forward tilt branch returns Pz @ R.T, so it is not the inverse's inverse"+ )+ def test_convention_tilt_projection_branches_are_inverses_4276(self, device, dtype):+ # Intended contract, asserted as a strict xfail so the repair makes it XPASS and forces this mark out: the+ # two branches of tilt_projection document themselves as a matrix and its inverse+ # (``return_inverse``: "False to obtain the tilt projection matrix. True for the inverse matrix."), so+ # ``forward @ inverse`` must be the identity. Settled by the function's own signature and by #4276's+ # Expected section, which fixes the FORWARD branch and leaves the inverse branch -- the one that already+ # matches OpenCV and the repo's own cv2 pin -- untouched. The pin does not assert any particular OpenCV+ # form; #4276's ``Pz @ R`` claim comes from reading OpenCV's source, not from executing it here.+ taux = torch.tensor([0.1], device=device, dtype=dtype)+ tauy = torch.tensor([0.2], device=device, dtype=dtype)+ product = tilt_projection(taux, tauy) @ tilt_projection(taux, tauy, True)+ self.assert_close(product, torch.eye(3, device=device, dtype=dtype)[None])++ @pytest.mark.parametrize("return_inverse", [False, True])+ def test_wart_tilt_projection_flattens_leading_axes_4324(self, device, dtype, return_inverse):+ # Wart pin for kornia#4324: every leading axis of the angles is flattened into one, so (2, 3, 1) angles+ # give (6, 3, 3) where the Returns line at the base commit promised (*, 3, 3). Both branches.+ # Pins the CURRENT behavior; NOT a contract; delete when #4324 is repaired.+ angles = torch.zeros(2, 3, 1, device=device, dtype=dtype)+ assert tilt_projection(angles, angles, return_inverse).shape == (6, 3, 3)+def test_jit(self, device, dtype):points = torch.rand(1, 1, 2, device=device, dtype=dtype)K = torch.rand(1, 3, 3, device=device, dtype=dtype)diff --git a/tests/geometry/calibration/test_pnp.py b/tests/geometry/calibration/test_pnp.pyindex c4313023d..6e166943b 100644--- a/tests/geometry/calibration/test_pnp.py+++ b/tests/geometry/calibration/test_pnp.py@@ -19,6 +19,7 @@ import pytestimport torchimport kornia+from kornia.core.exceptions import ShapeErrorfrom kornia.geometry.calibration.pnp import _mean_isotropic_scale_normalizefrom testing.base import BaseTester@@ -162,6 +163,118 @@ class TestSolvePnpDlt(BaseTester):self.assert_close(pred_img_points, img_points, atol=1e-3, rtol=1e-3)+ @staticmethod+ def _convention_world_points(device, dtype):+ # Six non-coplanar, non-collinear points spread over x, y and z with mixed signs. A planar or collinear set+ # trips solve_pnp_dlt's own singular-value guard, and a+ # symmetric set would hide a transposed [R|t].+ return torch.tensor(+ [+ [+ [5.0, -5.0, 10.0],+ [0.0, 0.0, 11.5],+ [2.5, 3.0, 16.0],+ [9.0, -2.0, 13.0],+ [-4.0, 5.0, 12.0],+ [-5.0, 5.0, 11.0],+ ]+ ],+ device=device,+ dtype=dtype,+ )++ def test_convention_returns_the_world_to_camera_extrinsics(self, device, dtype):+ # Convention pin: solve_pnp_dlt returns a (B, 3, 4)+ # [R | t] that maps WORLD points INTO the camera frame -- the same direction as PinholeCamera.extrinsics+ # and OpenCV's solvePnP rvec/tvec, not the camera pose in the world. Two cases: world points that are+ # already camera-frame points recover [I | 0], and a camera translated so that cam = world + (1, 0, 0)+ # recovers t = (+1, 0, 0). A cam-to-world reading would give t = (-1, 0, 0) on the second case, which is+ # why the identity case alone is not enough.+ # Snippet used to generate expected: solve_pnp_dlt(W, project_points(W + [1., 0., 0.], K), K) executed+ # 2026-09-06 at c0b50ad7 (torch 2.14.0, cpu float64) -> [[[1., -0., -0., 1.], [0., 1., -0.,+ # 0.], [0., 0., 1., 0.]]], max abs error vs [I | (1, 0, 0)] 6.14e-15; the identity case gives [I | 0] to+ # 8.01e-14.+ if dtype != torch.float64:+ pytest.skip("float64-only pin: float32 recovers [R|t] to 1.06e-05 on mps, outside the float32 atol")+ world_points = self._convention_world_points(device, dtype)+ K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ identity = torch.tensor(+ [[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]], device=device, dtype=dtype+ )+ recovered = kornia.geometry.solve_pnp_dlt(world_points, kornia.geometry.project_points(world_points, K), K)+ assert recovered.shape == (1, 3, 4)+ self.assert_close(recovered, identity)+ shift = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)+ shifted = kornia.geometry.solve_pnp_dlt(+ world_points, kornia.geometry.project_points(world_points + shift, K), K+ )+ expected = torch.tensor(+ [[[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]], device=device, dtype=dtype+ )+ self.assert_close(shifted, expected)++ def test_convention_world_to_camera_translation_sign(self, device, dtype):+ # Convention pin: the tolerance-free half of the pin above covers the+ # frame-direction claim is covered on every device and not only where float64 exists (mps has none).+ # A camera translated so that cam = world + (1, 0, 0) gives a world-to-camera [R | t] with t = (+1, 0, 0);+ # the cam-to-world reading is t = (-1, 0, 0). The assertion is a sign test, not a value test, so it needs+ # no tolerance and survives the float32 solve on mps, which recovers t only to about 1e-05.+ # Snippet used to generate expected: solve_pnp_dlt(W, project_points(W + [1., 0., 0.], K), K)[0, :, 3]+ # executed 2026-09-06 at c0b50ad7 (torch 2.14.0) -> cpu float32+ # [1.0000005960464478, 3.45e-06, 5.88e-06]; mps float32 [1.0000009536743164, -2.21e-06, -1.06e-05].+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt's shape/dtype validation rejects float16 and bfloat16 (BaseError)")+ world_points = self._convention_world_points(device, dtype)+ K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ shift = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)+ translation = kornia.geometry.solve_pnp_dlt(+ world_points, kornia.geometry.project_points(world_points + shift, K), K+ )[0, :, 3]+ assert translation[0] > 0.5+ assert abs(translation[1]) < 0.5+ assert abs(translation[2]) < 0.5++ def test_convention_rejects_4x4_intrinsics(self, device, dtype):+ # Convention pin: ``intrinsics`` is the (B, 3, 3)+ # K, and the (B, 4, 4) intrinsics matrix that a PinholeCamera stores is rejected by the shape check+ # rather than silently truncated to its upper-left block. The positive control is the same call with+ # that upper-left block passed on its own, which solves: so the rejection is about the shape and not+ # about the camera.+ # Snippet used to generate expected: solve_pnp_dlt(W, project_points(W, K), eye(4)[None] with K in the+ # upper-left 3x3) executed 2026-09-06 at c0b50ad7 (torch 2.14.0) -> ShapeError("Shape+ # mismatch at dimension 1: expected 3, got 4. | Expected shape: ['B', '3', '3'] | Actual shape:+ # [1, 4, 4]") on cpu float32 and float64. In float16 and bfloat16 the earlier dtype validation fires+ # first with a bare BaseError("Validation condition failed"), so those cells are skipped.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt's dtype validation rejects float16 and bfloat16 before the 4x4 shape check")+ world_points = self._convention_world_points(device, dtype)+ K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ img_points = kornia.geometry.project_points(world_points, K)+ K_4x4 = torch.eye(4, device=device, dtype=dtype)[None].clone()+ K_4x4[:, :3, :3] = K+ with pytest.raises(ShapeError, match="expected 3, got 4"):+ kornia.geometry.solve_pnp_dlt(world_points, img_points, K_4x4)+ assert kornia.geometry.solve_pnp_dlt(world_points, img_points, K_4x4[:, :3, :3]).shape == (1, 3, 4)++ def test_convention_planar_world_points_raise(self, device, dtype):+ # Convention pin: the DLT needs a non-degenerate configuration, and+ # the function enforces it -- a coplanar point set (the same six points flattened onto z = 5) raises+ # AssertionError naming the last singular value, rather than returning a silently wrong pose. This is a+ # documented, validated contract, so it is a convention and not a wart.+ # Snippet used to generate expected: solve_pnp_dlt(planar, project_points(planar, K), K) executed+ # 2026-09-06 at c0b50ad7 (torch 2.14.0, cpu float32 and float64) -> AssertionError("The last+ # singular value of one/more of the elements of the batch is smaller than 0.0001. ..."). In float16 and+ # bfloat16 the earlier dtype validation fires first, so those cells are skipped.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt's dtype validation rejects float16 and bfloat16 before the degeneracy check")+ world_points = self._convention_world_points(device, dtype)+ K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ planar = torch.stack(+ [world_points[0, :, 0], world_points[0, :, 1], torch.full_like(world_points[0, :, 0], 5.0)], -1+ )[None]+ with pytest.raises(AssertionError, match="last singular value"):+ kornia.geometry.solve_pnp_dlt(planar, kornia.geometry.project_points(planar, K), K)+class TestNormalization(BaseTester):@pytest.mark.parametrize("dimension", (2, 3, 5))diff --git a/tests/geometry/calibration/test_undistort.py b/tests/geometry/calibration/test_undistort.pyindex b77786ada..c0f595cd4 100644--- a/tests/geometry/calibration/test_undistort.py+++ b/tests/geometry/calibration/test_undistort.py@@ -18,11 +18,40 @@import pytestimport torch+from kornia.geometry.calibration.distort import distort_pointsfrom kornia.geometry.calibration.undistort import undistort_image, undistort_points+from kornia.geometry.grid import create_meshgrid+from kornia.geometry.transform import remapfrom testing.base import BaseTester+def _k_asymmetric(device, dtype):+ """``fx = fy = 100``, ``cx = 4``, ``cy = 3`` -- ``cx != cy`` so a transposed reading changes the literals."""+ return torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+++def _k_short_focal(device, dtype, fx=3.0, fy=2.0, cx=3.0, cy=2.0):+ """A camera whose distortion actually bites on a 5 x 7 image.++ Every intrinsic differs from every other, and the focal lengths are short enough that the 5 x 7 pixel grid+ spans a normalized radius of about 1.4, so the radial polynomial displaces the map by 0.74 px instead of the+ 3.5e-04 px that ``fx = 100`` would give -- a resampling pin on that map would pass for the identity.+ """+ return torch.tensor([[[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+++def _ramp_image(batch, channels, height, width, device, dtype):+ """A deterministic, non-constant image.++ ``% 17`` on a ramp of length ``B * C * H * W`` makes neighbouring pixels differ in every direction, so a+ resampling pin cannot pass by accident on a flat image; ``H != W`` keeps a row/column swap visible.+ """+ numel = batch * channels * height * width+ ramp = torch.arange(numel, device=device, dtype=torch.float32) % 17.0+ return (ramp / 17.0).reshape(batch, channels, height, width).to(dtype)++class TestUndistortPoints(BaseTester):def test_smoke(self, device, dtype):points = torch.rand(1, 2, device=device, dtype=dtype)@@ -243,6 +272,162 @@ class TestUndistortPoints(BaseTester):self.assert_close(ptsu[0], ptsu_expected1, rtol=1e-4, atol=1e-4)self.assert_close(ptsu[1], ptsu_expected2, rtol=1e-4, atol=1e-4)+ def test_convention_undistort_points_inverts_distort_points(self, device, dtype):+ # Convention pin: undistort_points is the+ # ITERATIVE inverse of distort_points (a 5-step fixed point by default), so the round trip closes to the+ # dtype tolerance on these points with moderate coefficients. Both+ # functions take PIXEL points and a (3, 3) K -- contrast the affine and Kannala-Brandt pairs in+ # tests/geometry/camera/test_distortion.py, which take normalized z = 1 points and a flat parameter+ # vector. The pin asserts closure at assert_close's dtype tolerance and states no error bound; the+ # five-step float64 residual (4.62e-05) passes because atol plus rtol * abs(points) allows it.+ # Raising the count to 50 improves float32/float64 accuracy; float16 stays at its rounding floor.+ # Outside the valid radius the iteration can cycle (#4285), pinned separately below.+ # The two pixels sit half a focal length off the principal point in both directions and on both sides of+ # it, so the forward map actually moves them by 2.775 px -- a round trip pin on near-axis points would+ # pass with undistort_points replaced by the identity.+ # Snippet used to generate expected: (undistort_points(distort_points(pts, K, d), K, d) - pts).abs().max()+ # executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0), differenced in the working dtype -> cpu+ # float32 3.81e-05, float64 4.62e-05, float16 1.56e-02, bfloat16 0.0; mps float32 3.81e-05,+ # float16 1.56e-02. The forward displacement (distorted - points).abs().max() is 2.775 px on cpu float32.+ points = torch.tensor([[[54.0, 53.0], [-16.0, 23.0]]], device=device, dtype=dtype)+ K = _k_asymmetric(device, dtype)+ dist = torch.tensor([[0.1, 0.01, 0.001, 0.001]], device=device, dtype=dtype)+ distorted = distort_points(points, K, dist)+ assert not torch.allclose(distorted.float(), points.float())+ self.assert_close(undistort_points(distorted, K, dist), points)+ self.assert_close(undistort_points(distorted, K, dist, num_iters=50), points)++ def test_wart_distort_undistort_round_trip_breaks_with_tilt_4276(self, device, dtype):+ # Wart pin for kornia#4276: distort_points and undistort_points stop being+ # inverses as soon as the 13th and 14th coefficients (taux, tauy) are non-zero, because distort_points+ # applies tilt_projection's FORWARD branch (Pz @ R.T) while undistort_points applies the return_inverse+ # branch (inv(Pz @ R)) -- see test_wart_tilt_projection_forward_is_pz_times_r_transpose_4276 in+ # test_distort.py. With taux = 0.1, tauy = 0.2 the round trip misses by tens of pixels; with the same+ # 14-coefficient vector and both tilt angles zero it closes within the dtype tolerance.+ # taux != tauy so a symmetric tilt cannot mask the defect.+ # The two 14-coefficient vectors below share the SAME radial and tangential part, so the only difference+ # between the two arms is the tilt: with tau = 0 the round trip on genuinely distorted points closes, and+ # with tau != 0 it misses by tens of pixels.+ # Snippet used to generate expected: (undistort_points(distort_points(pts, K, d14), K, d14) - pts)+ # .abs().max() executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0), tau = (0.1, 0.2) -> cpu+ # float32 47.765, float64 47.765, float16 47.812, bfloat16 47.5; mps float32 47.765, float16 47.75. The+ # same vector with tau = 0 gives 3.81e-05 (cpu float32) / 0.0 (cpu bfloat16).+ # Pins the CURRENT behavior; NOT a contract; delete when #4276 is repaired.+ points = torch.tensor([[[54.0, 53.0], [-16.0, 23.0]]], device=device, dtype=dtype)+ K = _k_asymmetric(device, dtype)+ radial = torch.tensor([[0.1, 0.01, 0.001, 0.001]], device=device, dtype=dtype)+ zero_tilt = torch.cat([radial, torch.zeros(1, 10, device=device, dtype=dtype)], -1)+ tilted = torch.cat([zero_tilt[:, :12], torch.tensor([[0.1, 0.2]], device=device, dtype=dtype)], -1)+ assert not torch.allclose(+ undistort_points(distort_points(points, K, tilted), K, tilted).float(), points.float()+ )+ self.assert_close(undistort_points(distort_points(points, K, zero_tilt), K, zero_tilt), points)++ def test_convention_new_K_denormalizes_and_K_normalizes(self, device, dtype):+ # The two intrinsics play the mirror image of their+ # roles in distort_points -- here K maps the incoming distorted pixel onto the normalized z = 1 plane and+ # new_K maps the undistorted normalized point back to pixels, which is why the same new_K that shrinks+ # the forward answer enlarges this one. Every intrinsic is distinct (K: fx 2, fy 3, cx 1, cy 1; new_K:+ # fx 5, fy 7, cx 2, cy 4), so swapping the two arguments, or fx with fy, changes both literals:+ # (10, 10) normalizes under K to ((10-1)/2, (10-1)/3) = (4.5, 3.0) and denormalizes under new_K to+ # (5*4.5+2, 7*3+4) = (24.5, 25.0). The sibling pin in test_distort.py fixes the forward direction.+ # Snippet used to generate expected: undistort_points([[[10., 10.]]], K, zeros(1, 4), new_K) executed+ # 2026-09-06 on commit c0b50ad7 (torch 2.14.0, cpu float32 and float64) -> [[[24.5, 25.0]]]; the+ # same call on mps float32 gives the same value. The second case, the mirror of test_distort.py's+ # diag(2, 2, 1) probe, doubles instead of halving: (1, 2) under K = eye(3) and new_K = diag(2, 2, 1)+ # comes back as (2.0, 4.0).+ K = torch.tensor([[[2.0, 0.0, 1.0], [0.0, 3.0, 1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ new_K = torch.tensor([[[5.0, 0.0, 2.0], [0.0, 7.0, 4.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ zero_dist = torch.zeros(1, 4, device=device, dtype=dtype)+ points = torch.tensor([[[10.0, 10.0]]], device=device, dtype=dtype)+ self.assert_close(+ undistort_points(points, K, zero_dist, new_K),+ torch.tensor([[[24.5, 25.0]]], device=device, dtype=dtype),+ )+ self.assert_close(+ undistort_points(+ torch.tensor([[[1.0, 2.0]]], device=device, dtype=dtype),+ torch.eye(3, device=device, dtype=dtype)[None],+ zero_dist,+ torch.tensor([[[2.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype),+ ),+ torch.tensor([[[2.0, 4.0]]], device=device, dtype=dtype),+ )++ def test_convention_more_iterations_shrink_the_round_trip_residual(self, device, dtype):+ # Inside the convergence region, more iterations reduce the residual down to the rounding floor.+ # The fx = fy = 100 camera above already passes assert_close after five steps, although 50 steps+ # improve its float32/float64 residual. Halving fy here makes the five-step error exceed that tolerance.+ # The first assertion is the non-triviality guard: the five-step answer is OUTSIDE the tolerance that+ # assert_close would use on these points, so the strict decrease below is not a decrease between three+ # already-converged answers.+ # Snippet used to generate expected: (undistort_points(distort_points(pts, K, d), K, d, num_iters=n)+ # - pts).abs().max() for n in (5, 10, 50), executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0),+ # differenced in the working dtype -> cpu float64 1.355131e-02, 2.410766e-05, 1.421085e-14; cpu float32+ # 1.355362e-02, 3.051758e-05, 1.907349e-06; mps float32 the same three float32 values. float32 has+ # reached its own rounding floor by 50 steps while float64 is still closing, which is the scoping the+ # Convention block states. The forward map displaces these points by 7.306 px, so an identity+ # undistort_points would not pass. In float16 and bfloat16 the residual is pinned at the dtype's own+ # quantum from the first step (1.5625e-02 and 0.5), so the three counts are indistinguishable there and+ # those cells are skipped.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("half precision quantizes the residual, so the three step counts are indistinguishable")+ points = torch.tensor([[[54.0, 53.0], [-16.0, 23.0]]], device=device, dtype=dtype)+ K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 50.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ dist = torch.tensor([[0.1, 0.01, 0.001, 0.001]], device=device, dtype=dtype)+ distorted = distort_points(points, K, dist)+ with pytest.raises(AssertionError):+ self.assert_close(undistort_points(distorted, K, dist, num_iters=5), points)+ residuals = [(undistort_points(distorted, K, dist, num_iters=n) - points).abs().max() for n in (5, 10, 50)]+ assert residuals[0] > residuals[1]+ assert residuals[1] > residuals[2]+ self.assert_close(undistort_points(distorted, K, dist, num_iters=50), points)++ def test_wart_fixed_point_cycles_outside_valid_radius_4285(self, device, dtype):+ # The iteration alternates between two inaccurate values; a larger even count is worse+ # than an odd count, rather than the residual increasing monotonically. Delete after #4285.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("probe requires float32/float64 to avoid half-precision overflow")+ points = torch.tensor([[[304.0, 3.0]]], device=device, dtype=dtype)+ K = _k_asymmetric(device, dtype)+ dist = torch.tensor([[0.5, 0.0, 0.0, 0.0]], device=device, dtype=dtype)+ distorted = distort_points(points, K, dist)+ residuals = [(undistort_points(distorted, K, dist, num_iters=n) - points).abs().max() for n in (5, 6, 7, 8)]+ self.assert_close(residuals[0], residuals[2], atol=1e-3, rtol=1e-5)+ self.assert_close(residuals[1], residuals[3], atol=1e-3, rtol=1e-5)+ assert residuals[1] > residuals[0] > 1++ @pytest.mark.parametrize("op", [distort_points, undistort_points])+ @pytest.mark.parametrize("exporting", [False, True])+ def test_wart_multi_axis_tilt_batch_fails_4324(self, device, dtype, monkeypatch, op, exporting):+ # Wart pin for kornia#4324: with two leading axes the tilt path fails, and export always takes the tilt+ # path, including for four zero coefficients. The first assertion is the eager control on the same shapes.+ # Pins the CURRENT behavior; NOT a contract; delete when #4324 is repaired.+ points = torch.ones(2, 3, 5, 2, device=device, dtype=dtype)+ K = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3, 3)+ dist = torch.zeros(2, 3, 4 if exporting else 14, device=device, dtype=dtype)+ assert op(points, K, dist).shape == points.shape+ if exporting:+ monkeypatch.setattr(f"{op.__module__}.is_exporting", lambda: True)+ else:+ dist[..., 12:] = torch.tensor([0.01, 0.02], device=device, dtype=dtype)+ error = RuntimeError if op is distort_points else ValueError+ message = "size of tensor" if op is distort_points else "Input batch size must be the same"+ with pytest.raises(error, match=message):+ op(points, K, dist)++ def test_wart_unbatched_export_undistort_fails_4324(self, device, dtype, monkeypatch):+ # Wart pin for kornia#4324: the legacy unbatched form that eager undistort_points accepts is rejected on+ # the export path, which the four-coefficient vector does not avoid.+ # Pins the CURRENT behavior; NOT a contract; delete when #4324 is repaired.+ points = torch.ones(1, 2, device=device, dtype=dtype)+ K = torch.eye(3, device=device, dtype=dtype)+ dist = torch.zeros(4, device=device, dtype=dtype)+ assert undistort_points(points, K, dist).shape == points.shape+ monkeypatch.setattr(f"{undistort_points.__module__}.is_exporting", lambda: True)+ with pytest.raises(ValueError, match="Input batch size must be the same"):+ undistort_points(points, K, dist)+def test_gradcheck(self, device):points = torch.rand(1, 8, 2, device=device, dtype=torch.float64, requires_grad=True)K = torch.rand(1, 3, 3, device=device, dtype=torch.float64)@@ -289,6 +474,22 @@ class TestUndistortImage(BaseTester):assert imu.shape == (3, 2, 3, 5, 5)self.assert_close(imu[0], imu[1])+ @pytest.mark.parametrize("exporting", [False, True])+ def test_wart_multi_axis_tilt_image_fails_4324(self, device, dtype, monkeypatch, exporting):+ # Wart pin for kornia#4324: undistort_image inherits the distort_points failure on two leading axes once+ # the tilt path is taken (non-zero tilt in eager, always under export).+ # Pins the CURRENT behavior; NOT a contract; delete when #4324 is repaired.+ image = torch.ones(2, 3, 1, 5, 5, device=device, dtype=dtype)+ K = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3, 3)+ dist = torch.zeros(2, 3, 4 if exporting else 14, device=device, dtype=dtype)+ assert undistort_image(image, K, dist).shape == image.shape+ if exporting:+ monkeypatch.setattr(f"{distort_points.__module__}.is_exporting", lambda: True)+ else:+ dist[..., 12:] = torch.tensor([0.01, 0.02], device=device, dtype=dtype)+ with pytest.raises(RuntimeError, match="size of tensor"):+ undistort_image(image, K, dist)+def test_exception(self, device, dtype):with pytest.raises(ValueError):im = torch.rand(5, 5, device=device, dtype=dtype)@@ -353,6 +554,76 @@ class TestUndistortImage(BaseTester):imu = undistort_image(im / 255.0, K, dist)self.assert_close(imu, imu_expected / 255.0, rtol=1e-2, atol=1e-2)+ def test_convention_zero_coefficients_are_close_but_not_byte_identical(self, device, dtype):+ # Convention pin: with every coefficient zero the+ # DISTORTION MAP is exact -- distort_points reproduces the pixel grid bit for bit (Y3-03: 0.0) -- but+ # undistort_image still routes the image through remap's bilinear sampler, so the returned image is NOT+ # byte-identical to the input; it is only equal within the dtype tolerance. This refutes the plausible+ # "zero coefficients give back the same image" reading, and it is why the pin uses assert_close where the+ # point-level pin in test_distort.py uses torch.equal. No residual bound is asserted.+ # Snippet used to generate expected: (torch.equal(undistort_image(img, K, zeros(1, 4)), img),+ # (undistort_image(...) - img).abs().max()) executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0)+ # -> cpu float32 (False, 1.19e-07), float64 (False, 2.09e-16), float16 (False, 9.19e-04), bfloat16+ # (False, 7.81e-03); mps float32 (False, 1.19e-07), float16 (False, 1.84e-03). Only the mps float16 cell+ # exceeds its atol, so the skip is conditioned on the device and the cpu float16 leg still runs.+ if dtype == torch.float16 and device.type == "mps":+ pytest.skip("mps float16 only: the remap round trip leaves a 1.84e-03 residual, outside the atol")+ image = _ramp_image(1, 3, 5, 7, device, dtype)+ K = _k_short_focal(device, dtype)+ out = undistort_image(image, K, torch.zeros(1, 4, device=device, dtype=dtype))+ assert not torch.equal(out, image)+ self.assert_close(out, image)++ def test_convention_accepts_both_batch_conventions(self, device, dtype):+ # Convention pin: undistort_image accepts the batched form+ # (B, C, H, W) + (B, 3, 3) + (B, n) AND the legacy unbatched form (1, C, H, W) + (3, 3) + (n,), which the+ # source keeps "to avoid a breaking change". The legacy relaxation is special-cased to B = 1 only: the+ # same unbatched K and dist with a B = 2 image raise ValueError rather than broadcasting. The batch is+ # built from the SAME image repeated twice with different intrinsics (fx 3/5, fy 2/4, cx 3/2, cy 2/1) and+ # different coefficients, so the two output rows can only differ if each element used its own K and dist.+ # Snippet used to generate expected: shapes from undistort_image on each form, plus+ # (out[0] - out[1]).abs().max(), executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0) ->+ # (2, 3, 5, 7), (1, 3, 5, 7), ValueError("Input shape is invalid. Input batch dimensions should match."),+ # and a row-to-row difference of 0.284 (cpu float32) / 0.283 (mps float32) on an image in [0, 1).+ dist = torch.tensor([[0.1, 0.01, 0.001, 0.001]], device=device, dtype=dtype)+ K = _k_short_focal(device, dtype)+ K_batch = torch.cat([K, _k_short_focal(device, dtype, fx=5.0, fy=4.0, cx=2.0, cy=1.0)])+ image = _ramp_image(1, 3, 5, 7, device, dtype)+ batched = undistort_image(torch.cat([image, image]), K_batch, torch.cat([dist, dist * 2]))+ assert batched.shape == (2, 3, 5, 7)+ assert not torch.allclose(batched[0].float(), batched[1].float())+ legacy = undistort_image(image, K[0], dist[0])+ assert legacy.shape == (1, 3, 5, 7)+ self.assert_close(legacy, batched[:1])+ with pytest.raises(ValueError, match="Input batch dimensions should match"):+ undistort_image(torch.cat([image, image]), K[0], dist[0])++ def test_convention_resamples_with_align_corners_true(self, device, dtype):+ # Convention pin: undistort_image is exactly+ # ``remap(image, mapx, mapy, align_corners=True)`` over the map that distort_points produces on the+ # create_meshgrid pixel grid -- the align_corners choice is BAKED IN and the function exposes no way to+ # change it (a documented window item; the same baked flag appears in warp_frame_depth and DepthWarper).+ # The align_corners=False arm is asserted to DIFFER on the same map, so the pin discriminates rather than+ # passing for both settings; the coefficients are non-trivial for the same reason.+ # Snippet used to generate expected: torch.equal(undistort_image(img, K, dist), remap(img, mapx, mapy,+ # align_corners=True)) executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0) -> True on cpu for+ # float32/float64/float16/bfloat16 and on mps for float32/float16; the align_corners=False output is+ # visibly different on every one of those cells, which the pin asserts without a bound. On this+ # short-focal camera the map deviates from the pixel grid by 0.738 px and the undistorted image differs+ # from the input by 0.652 (cpu float32), so the pin is not comparing two copies of an unresampled image.+ image = _ramp_image(1, 3, 5, 7, device, dtype)+ K = _k_short_focal(device, dtype)+ dist = torch.tensor([[0.1, 0.01, 0.001, 0.001]], device=device, dtype=dtype)+ grid = create_meshgrid(5, 7, False, device, dtype).reshape(-1, 2)+ distorted = distort_points(grid, K, dist)+ assert not torch.allclose(distorted.float(), grid.float())+ mapx = distorted[..., 0].reshape(1, 5, 7)+ mapy = distorted[..., 1].reshape(1, 5, 7)+ out = undistort_image(image, K, dist)+ assert not torch.allclose(out.float(), image.float())+ self.assert_close(out, remap(image, mapx, mapy, align_corners=True), atol=0.0, rtol=0.0)+ assert not torch.allclose(out.float(), remap(image, mapx, mapy, align_corners=False).float())+def test_gradcheck(self, device):im = torch.rand(1, 1, 15, 15, device=device, dtype=torch.float64, requires_grad=True)K = torch.rand(3, 3, device=device, dtype=torch.float64)diff --git a/tests/geometry/camera/test_distortion.py b/tests/geometry/camera/test_distortion.pyindex 4c8aa244e..61f0c3a50 100644--- a/tests/geometry/camera/test_distortion.py+++ b/tests/geometry/camera/test_distortion.py@@ -134,6 +134,58 @@ class TestDistortionAffine(BaseTester):self._test_jit_distort(device, dtype)self._test_jit_undistort(device, dtype)+ def test_convention_distort_points_affine_takes_normalized_z1_points(self, device, dtype):+ # Convention pin: distort_points_affine consumes points on the z = 1+ # NORMALIZED plane and a flat ``[fx, fy, cx, cy]`` parameter vector -- it is the pinhole projection, not a+ # pixel-to-pixel map. (0.5, 0.25) with fx = fy = 100, cx = 4, cy = 3 therefore lands on+ # u = 100 * 0.5 + 4 = 54, v = 100 * 0.25 + 3 = 28. cx != cy and x != y, so a transposed reading of either+ # the point or the parameter vector changes both literals; the batched row uses a second, differently+ # scaled camera (fx = 200, fy = 50, cx = 6, cy = 2) so a broadcast of element 0 fails too.+ # Snippet used to generate expected: distort_points_affine(tensor([0.5, 0.25]), tensor([100., 100., 4., 3.]))+ # executed 2026-09-06 at c0b50ad7 (torch 2.14.0, cpu and mps, every dtype) -> [54., 28.].+ points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)+ params = torch.tensor([100.0, 100.0, 4.0, 3.0], device=device, dtype=dtype)+ self.assert_close(distort_points_affine(points, params), torch.tensor([54.0, 28.0], device=device, dtype=dtype))+ batched_points = torch.tensor([[0.5, 0.25], [1.0, 1.0]], device=device, dtype=dtype)+ batched_params = torch.tensor([[100.0, 100.0, 4.0, 3.0], [200.0, 50.0, 6.0, 2.0]], device=device, dtype=dtype)+ self.assert_close(+ distort_points_affine(batched_points, batched_params),+ torch.tensor([[54.0, 28.0], [206.0, 52.0]], device=device, dtype=dtype),+ )++ def test_convention_undistort_points_affine_is_the_exact_inverse(self, device, dtype):+ # Convention pin: undistort_points_affine((u, v), params) is the exact inverse of+ # distort_points_affine -- pixel in, normalized z = 1 point out -- and the round trip recovers the input+ # bit for bit on this asymmetric camera (atol = rtol = 0). The pair is a genuine forward/inverse duo; the+ # Kannala-Brandt twin below is iterative and closes only to a tolerance.+ # Snippet used to generate expected: torch.equal(undistort_points_affine(distort_points_affine(p, par), par), p)+ # executed 2026-09-06 at c0b50ad7 (torch 2.14.0) -> True on cpu for float32/float64/float16/+ # bfloat16 and on mps for float32/float16; recovered value [0.5, 0.25].+ points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)+ params = torch.tensor([100.0, 100.0, 4.0, 3.0], device=device, dtype=dtype)+ distorted = distort_points_affine(points, params)+ self.assert_close(undistort_points_affine(distorted, params), points, atol=0.0, rtol=0.0)++ def test_convention_dx_distort_points_affine_matches_autograd(self, device, dtype):+ # Convention pin: dx_distort_points_affine returns the (2, 2)+ # Jacobian of distort_points_affine with respect to the POINT (rows = output components, columns = input+ # components), byte-identical to torch.autograd.functional.jacobian, and constant in the point because the+ # map is affine -- diag(fx, fy) = diag(100, 100). This is the control probe for the Kannala-Brandt+ # Jacobian pinned in TestDistortionKannalaBrandt below, which is NOT the Jacobian of the function it+ # documents (kornia#4277).+ # Snippet used to generate expected: torch.equal(dx_distort_points_affine(p, par),+ # torch.autograd.functional.jacobian(lambda q: distort_points_affine(q, par), p)) executed 2026-09-06 on+ # c0b50ad7 (torch 2.14.0) -> True on cpu (float32/float64/float16/bfloat16) and on mps+ # (float32/float16); value [[100., 0.], [0., 100.]].+ points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)+ params = torch.tensor([100.0, 100.0, 4.0, 3.0], device=device, dtype=dtype)+ analytic = dx_distort_points_affine(points, params)+ autograd = torch.autograd.functional.jacobian(lambda q: distort_points_affine(q, params), points)+ self.assert_close(analytic, autograd, atol=0.0, rtol=0.0)+ self.assert_close(+ analytic, torch.tensor([[100.0, 0.0], [0.0, 100.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0+ )+class TestDistortionKannalaBrandt(BaseTester):def test_smoke(self, device, dtype) -> None:@@ -255,3 +307,146 @@ class TestDistortionKannalaBrandt(BaseTester):def test_jit(self, device, dtype) -> None:self._test_jit_distort(device, dtype)self._test_jit_undistort(device, dtype)++ def test_convention_undistort_points_kannala_brandt_round_trip_closes(self, device, dtype):+ # Convention pin: unlike the affine pair in+ # TestDistortionAffine, undistort_points_kannala_brandt is an ITERATIVE inverse (10 Gauss-Newton steps),+ # so the round trip closes to the dtype tolerance rather than bit for bit. The pin asserts closure at+ # assert_close's dtype tolerance and deliberately states no error bound; the executed residuals are+ # recorded, not enforced. The far-off-axis case is the sibling pin below.+ # Snippet used to generate expected: (undistort_points_kannala_brandt(distort_points_kannala_brandt(p, par),+ # par) - p).abs().max() executed 2026-09-06 at c0b50ad7 (torch 2.14.0), differenced in the+ # working dtype -> cpu float32 2.98e-08, float64 9.55e-09, float16 9.77e-04, bfloat16 1.95e-03;+ # mps float32 2.98e-08, float16 9.77e-04.+ params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)+ points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)+ self.assert_close(+ undistort_points_kannala_brandt(distort_points_kannala_brandt(points, params), params), points+ )++ def test_convention_undistort_points_kannala_brandt_closes_far_off_axis(self, device, dtype):+ # Convention pin: the Gauss-Newton inverse still closes at a normalized radius of+ # 3 focal lengths, where the fish-eye polynomial is far from linear -- the fixed-point iteration in+ # kornia.geometry.calibration.undistort_points does NOT (kornia#4285). Closure is asserted at+ # assert_close's dtype tolerance, with no error bound.+ # Snippet used to generate expected: (undistort_points_kannala_brandt(distort_points_kannala_brandt(+ # tensor([3., 0.]), par), par) - tensor([3., 0.])).abs().max() executed 2026-09-06 at c0b50ad7+ # (torch 2.14.0), differenced in the working dtype -> cpu float32 1.91e-06, float64 2.03e-08,+ # float16 1.95e-03, bfloat16 6.25e-02; mps float32 1.91e-06, float16 1.95e-03.+ if dtype == torch.bfloat16:+ pytest.skip("bfloat16: the far-off-axis round trip closes only to 6.25e-02, outside the bfloat16 atol")+ params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)+ far = torch.tensor([3.0, 0.0], device=device, dtype=dtype)+ self.assert_close(undistort_points_kannala_brandt(distort_points_kannala_brandt(far, params), params), far)++ def test_convention_principal_point_undistorts_to_the_origin(self, device, dtype):+ # Convention pin: small constants that guard the Gauss-Newton denominator and final radial rescale mean the+ # principal point (cx, cy) undistorts to the EXACT origin instead of the 0/0 that the unguarded+ # arithmetic would give. The assertion is torch.equal, not assert_close, because the guard makes the+ # result exactly zero rather than nearly zero.+ # cx != cy in these params, so the principal point is off the diagonal and a cx/cy swap would move it.+ # The second, off-centre point is what keeps the pin from being frame-invariant: (54, 28) normalizes to+ # (0.5, 0.25) and undistorts to a value that changes under either swap -- the same params with cx and cy+ # exchanged give [0.5507686734199524, 0.2591852843761444] and with fy halved to 50 they give+ # [0.5658687353134155, 0.5658687353134155].+ # Snippet used to generate expected: undistort_points_kannala_brandt(tensor([4., 3.]), params) and the+ # same call on tensor([54., 28.]), executed 2026-09-06 at c0b50ad7 (torch 2.14.0) -> the+ # principal point gives exactly [0.0, 0.0] on cpu float64/float32/bfloat16 and on mps float32; the+ # off-centre point gives [0.5392647981643677, 0.26963239908218384] on cpu and mps float32. In float16+ # the final radial-rescale denominator's 1e-8 guard underflows and the principal point gives [nan, nan]+ # -- kornia#4308, pinned by+ # test_wart_principal_point_undistorts_to_nan_in_float16_4308 below.+ if dtype == torch.float16:+ pytest.skip("float16: the final radial-rescale guard 1e-8 underflows, making the origin 0/0 (#4308)")+ params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)+ principal_point = torch.tensor([4.0, 3.0], device=device, dtype=dtype)+ undistorted = undistort_points_kannala_brandt(principal_point, params)+ assert torch.equal(undistorted, torch.zeros(2, device=device, dtype=dtype))+ off_centre = torch.tensor([54.0, 28.0], device=device, dtype=dtype)+ self.assert_close(+ undistort_points_kannala_brandt(off_centre, params),+ torch.tensor([0.5392647981643677, 0.26963239908218384], device=device, dtype=dtype),+ )++ def test_wart_principal_point_undistorts_to_nan_in_float16_4308(self, device, dtype):+ # Wart pin for kornia#4308: in float16, the 1e-8 epsilon added to ``rth`` for the final radial rescale+ # underflows to zero (the smallest subnormal is about 5.96e-08). At the principal point, both+ # ``radius_undistorted`` and ``rth`` are zero, so ``mag = 0 / (0 + 0)`` is nan and propagates through+ # the final multiplication. The 1e-16 Newton-start clamp and 1e-12 Newton-step denominator also+ # underflow, but they are not the direct source of this result. The body runs in ``params.dtype``;+ # bfloat16 preserves these values' exponent range, so the wart is specific to float16.+ # Snippet used to generate expected: undistort_points_kannala_brandt(tensor([4., 3.], dtype=torch.+ # float16), params.half()) executed 2026-09-06 at c0b50ad7 (torch 2.14.0) -> [nan, nan] on+ # both cpu and mps. Float16 POINTS with float32+ # params return [0.0, 0.0], because the body casts the points to params.dtype first.+ # Pins the CURRENT behavior; NOT a contract; delete when #4308 is repaired.+ if dtype != torch.float16:+ pytest.skip("float16-only wart: the radial-rescale epsilon is representable in every other dtype")+ params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)+ principal_point = torch.tensor([4.0, 3.0], device=device, dtype=dtype)+ assert undistort_points_kannala_brandt(principal_point, params).isnan().all()+ wide_params = params.to(torch.float32)+ self.assert_close(+ undistort_points_kannala_brandt(principal_point, wide_params),+ torch.zeros(2, device=device, dtype=dtype),+ )++ def test_wart_rescale_guard_caps_float64_round_trip_4308(self, device, dtype):+ # Wart pin for kornia#4308, the float64 side of the same constant: the final radial rescale divides by+ # ``rth + 1e-8`` rather than ``rth``, so every result is scaled by ``1 - 1e-8 / r`` and the float64 round+ # trip stops at about 1e-8 on the normalized plane instead of the ~1e-16 the ten Gauss-Newton steps reach.+ # Snippet used to generate expected: (undistort_points_kannala_brandt(distort_points_kannala_brandt(+ # tensor([3., 0.]), par), par) - tensor([3., 0.])).abs().max() executed 2026-09-08 at d2fe9507 (torch+ # 2.14.0, cpu float64) -> 2.03e-08; the same body with the guard set to 0.0 -> 0.0. float32's rounding+ # floor (1.91e-06 here) sits above the bias, so only float64 sees it.+ # Pins the CURRENT behavior; NOT a contract; delete when #4308 is repaired.+ if dtype != torch.float64:+ pytest.skip("float64-only wart: every other dtype's rounding floor is above the 1e-8 bias")+ params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)+ far = torch.tensor([3.0, 0.0], device=device, dtype=dtype)+ distorted = distort_points_kannala_brandt(far, params)+ residual = (undistort_points_kannala_brandt(distorted, params) - far).abs().max().item()+ assert 1e-9 < residual < 1e-7++ def test_wart_dx_distort_points_kannala_brandt_disagrees_with_autograd_4277(self, device, dtype):+ # Wart pin for kornia#4277: the analytic Jacobian is+ # not the Jacobian of distort_points_kannala_brandt. torch.autograd.functional.jacobian and central finite+ # differences agree with each other and both disagree with the analytic matrix -- by 62.58 in absolute+ # terms on entries of order 1e2 at this point. The asymmetric focal lengths also make the analytic matrix+ # nonsymmetric, and its transpose still does not close the gap, so it is not an index-order slip. The+ # sibling dx_distort_points_affine (pinned in+ # TestDistortionAffine) matches autograd byte for byte.+ # The pre-existing test_dx_distort_points_kannala_brandt in this class asserts the same wrong analytic+ # family at a different input; the fix for+ # #4277 has to re-derive both its ``expected`` and the function's docstring example.+ # Snippet used to generate expected: dx_distort_points_kannala_brandt(tensor([0.5, 0.25]), params) executed+ # 2026-09-06 at c0b50ad7 (torch 2.14.0, cpu float32) with fx = 100 and fy = 50 ->+ # [[22.0633487701416, -35.7770881652832], [-17.8885440826416, 37.8644866943359]]; autograd at the same+ # input -> [[84.64064025878906, -4.488434791564941], [-2.24421739578247, 45.6866455078125]].+ # Pins the CURRENT value; NOT a contract; delete when #4277 is repaired.+ params = torch.tensor([100.0, 50.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)+ points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)+ analytic = dx_distort_points_kannala_brandt(points, params)+ self.assert_close(+ analytic,+ torch.tensor(+ [[22.0633487701416, -35.7770881652832], [-17.8885440826416, 37.8644866943359]],+ device=device,+ dtype=dtype,+ ),+ )+ autograd = torch.autograd.functional.jacobian(lambda q: distort_points_kannala_brandt(q, params), points)+ assert not torch.allclose(analytic.float(), analytic.transpose(-1, -2).float())+ assert not torch.allclose(analytic.float(), autograd.float())+ assert not torch.allclose(analytic.transpose(-1, -2).float(), autograd.float())++ @pytest.mark.xfail(strict=True, reason="kornia#4277: the analytic Kannala-Brandt Jacobian disagrees with autograd")+ def test_convention_dx_distort_points_kannala_brandt_matches_autograd_4277(self, device, dtype):+ # Intended contract, asserted as a strict xfail so the repair makes it XPASS and forces this mark out:+ # dx_distort_points_kannala_brandt returns the Jacobian of the function it is named after, exactly as+ # dx_distort_points_affine and dx_project_points_z1 already do.+ # Settled by #4277's own Expected section ("re-derived so it matches autograd and central differences").+ params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)+ points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)+ autograd = torch.autograd.functional.jacobian(lambda q: distort_points_kannala_brandt(q, params), points)+ self.assert_close(dx_distort_points_kannala_brandt(points, params), autograd)