Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(calibration): correct forward sensor tilt projection (#4384)

UnbearableFate5e6ab6b2c7cc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eecae066a..2a412073b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -417,6 +417,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* `RandomThinPlateSpline(scale=0.0)` now generates zero control-point displacement instead of
raising an error when constructing a degenerate uniform distribution. (#4463)
+* Correct non-zero sensor tilt in `tilt_projection` and `distort_points` to match OpenCV,
+ restoring forward/inverse round trips and correcting `undistort_image` sampling. (#4384)
* `reproject_disparity_to_3D` (the `StereoCamera` method and the module-level function, which share
one body) no longer transposes the two pixel indices. The pixel meshgrid was unbound as
diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.py
index b18edc3c6..2313cc61f 100644
--- a/kornia/geometry/calibration/distort.py
+++ b/kornia/geometry/calibration/distort.py
@@ -34,21 +34,11 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
- ``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.
+ - ``return_inverse=False`` returns ``Pz @ R``, matching OpenCV's tilt projection.
- Scalar angles return :math:`(3, 3)`. For non-scalar angles, a trailing singleton angle-component
axis is consumed and every leading batch dimension is preserved; without that trailing singleton,
the full input shape is treated as the batch shape.
- .. 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 any shape, matching the other angle.
tauy: Rotation angle in radians around the :math:`y`-axis with any shape, matching the other angle.
@@ -115,7 +105,7 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
-2,
)
- tilt = Pz @ R.transpose(-1, -2)
+ tilt = Pz @ R
return tilt
@@ -145,10 +135,6 @@ def distort_points(
- Matching leading dimensions are preserved with or without tilt. Compilation and ONNX export always apply
the tilt branch, including for zero tilt, where the resulting projection is the identity.
- .. 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.
-
Args:
points: Input image points with shape :math:`(*, N, 2)`.
K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index d5ce389d3..9e33e9ef0 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -62,11 +62,6 @@ def undistort_points(
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.
-
Args:
points: Input image points with shape :math:`(*, N, 2)`.
K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.
@@ -194,13 +189,6 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
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/tests/geometry/calibration/test_distort.py b/tests/geometry/calibration/test_distort.py
index b860c28b1..fb04abb36 100644
--- a/tests/geometry/calibration/test_distort.py
+++ b/tests/geometry/calibration/test_distort.py
@@ -31,7 +31,7 @@ def _pz_r(taux, tauy, device, dtype):
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).
+ OpenCV's tilt projection is ``Pz @ R``.
"""
taux = torch.tensor([taux], device=device, dtype=dtype)
tauy = torch.tensor([tauy], device=device, dtype=dtype)
@@ -297,35 +297,15 @@ class TestDistortPoints(BaseTester):
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.
+ # Both branches reduce to the identity when tilt is disabled.
zero = torch.zeros(1, 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).
+ # Preserve OpenCV's inverse independently of the forward/inverse round trip (#4276).
+ # A simultaneous change to both branches must not hide a convention error.
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
@@ -335,40 +315,13 @@ class TestDistortPoints(BaseTester):
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.
+ def test_convention_tilt_projection_forward_is_pz_times_r_4276(self, device, dtype):
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
+ self.assert_close(tilt_projection(taux, tauy), p_z @ r)
- @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)
diff --git a/tests/geometry/calibration/test_undistort.py b/tests/geometry/calibration/test_undistort.py
index 6d0a588e4..7bd948ad7 100644
--- a/tests/geometry/calibration/test_undistort.py
+++ b/tests/geometry/calibration/test_undistort.py
@@ -231,6 +231,9 @@ class TestUndistortPoints(BaseTester):
ptsu = undistort_points(pts, K, dist)
self.assert_close(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
+ # Forward distortion of the independent OpenCV values must recover the input (#4276).
+ self.assert_close(distort_points(ptsu_expected, K, dist), pts, rtol=1e-4, atol=1e-4)
+
new_K = K * 2
new_K[2, 2] = 1
# Expected output generated with OpenCV:
@@ -355,30 +358,18 @@ class TestUndistortPoints(BaseTester):
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.
+ def test_convention_distort_undistort_round_trip_with_tilt_4276(self, device, dtype):
+ # Unequal tilt angles plus non-zero radial/tangential coefficients expose #4276.
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()
- )
+ # float16 accumulates two ulps through forward tilt and iterative inversion;
+ # increasing num_iters from 5 to 50 leaves the same 0.0625-pixel rounding floor.
+ rtol = 2 * torch.finfo(dtype).eps if dtype == torch.float16 else None
+ atol = 0.0 if dtype == torch.float16 else None
+ self.assert_close(undistort_points(distort_points(points, K, tilted), K, tilted), points, rtol=rtol, atol=atol)
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):