Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(calibration): preserve tilt projection batch dimensions (#4345)

victorwon2001fa5441794128
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31c7d254b..4df25d2d7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -570,6 +570,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
abstract. It now has a `SuperResolutionConfig` and a `from_config` that dispatches to either
builder family, and both builders are covered by tests. Fixes #4291. (#4335)
+* `tilt_projection` preserves its documented leading batch dimensions, so `distort_points`,
+ `undistort_points`, and `undistort_image` no longer fail on multi-axis batches when tilt distortion
+ is applied. (#4345)
+
* `kornia.io.load_image` and `write_image` work on the kornia_rs that a plain `pip install kornia`
resolves. kornia_rs 0.1.11 moved its image readers and writers from the package root into
`kornia_rs.io`, and kornia kept calling the root, so on 0.1.11 and newer `load_image` raised
diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.py
index 14badb839..b18edc3c6 100644
--- a/kornia/geometry/calibration/distort.py
+++ b/kornia/geometry/calibration/distort.py
@@ -35,9 +35,9 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
: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>`_.
+ - 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
@@ -56,15 +56,16 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
Returns:
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.
+ True, with shape :math:`(3, 3)` for scalar angles or :math:`(*, 3, 3)` for non-scalar angles, where a
+ trailing singleton angle-component axis is omitted from :math:`*`.
"""
if taux.shape != tauy.shape:
raise ValueError(f"Shape of taux {taux.shape} and tauy {tauy.shape} do not match.")
- ndim: int = taux.dim()
- taux = taux.reshape(-1)
- tauy = tauy.reshape(-1)
+ if taux.dim() > 0 and taux.shape[-1] == 1:
+ taux = taux.squeeze(-1)
+ tauy = tauy.squeeze(-1)
cTx = torch.cos(taux)
sTx = torch.sin(taux)
@@ -73,30 +74,48 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
zero = torch.zeros_like(cTx)
one = torch.ones_like(cTx)
- Rx = torch.stack([one, zero, zero, zero, cTx, sTx, zero, -sTx, cTx], -1).reshape(-1, 3, 3)
- Ry = torch.stack([cTy, zero, -sTy, zero, one, zero, sTy, zero, cTy], -1).reshape(-1, 3, 3)
+ Rx = torch.stack(
+ [
+ torch.stack([one, zero, zero], -1),
+ torch.stack([zero, cTx, sTx], -1),
+ torch.stack([zero, -sTx, cTx], -1),
+ ],
+ -2,
+ )
+ Ry = torch.stack(
+ [
+ torch.stack([cTy, zero, -sTy], -1),
+ torch.stack([zero, one, zero], -1),
+ torch.stack([sTy, zero, cTy], -1),
+ ],
+ -2,
+ )
R = Ry @ Rx
if return_inverse:
invR22 = 1 / R[..., 2, 2]
invPz = torch.stack(
- [invR22, zero, R[..., 0, 2] * invR22, zero, invR22, R[..., 1, 2] * invR22, zero, zero, one], -1
- ).reshape(-1, 3, 3)
+ [
+ torch.stack([invR22, zero, R[..., 0, 2] * invR22], -1),
+ torch.stack([zero, invR22, R[..., 1, 2] * invR22], -1),
+ torch.stack([zero, zero, one], -1),
+ ],
+ -2,
+ )
inv_tilt = R.transpose(-1, -2) @ invPz
- if ndim == 0:
- inv_tilt = torch.squeeze(inv_tilt)
-
return inv_tilt
Pz = torch.stack(
- [R[..., 2, 2], zero, -R[..., 0, 2], zero, R[..., 2, 2], -R[..., 1, 2], zero, zero, one], -1
- ).reshape(-1, 3, 3)
+ [
+ torch.stack([R[..., 2, 2], zero, -R[..., 0, 2]], -1),
+ torch.stack([zero, R[..., 2, 2], -R[..., 1, 2]], -1),
+ torch.stack([zero, zero, one], -1),
+ ],
+ -2,
+ )
tilt = Pz @ R.transpose(-1, -2)
- if ndim == 0:
- tilt = torch.squeeze(tilt)
-
return tilt
@@ -123,10 +142,8 @@ def distort_points(
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`. Compilation and ONNX export
- always take that path, including for zero tilt. Tracked as `#4324 <https://github.com/kornia/kornia/issues/4324>`_.
+ - 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;
@@ -211,7 +228,7 @@ def distort_points(
if not torch.jit.is_scripting():
capture = capture or is_compiling()
if capture or torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):
- tilt = tilt_projection(dist[..., 12], dist[..., 13])
+ tilt = tilt_projection(dist[..., 12:13], dist[..., 13:14])
# Transposed untilt points (instead of [x,y,1]^T, we obtain [x,y,1])
points_untilt = torch.stack([xd, yd, torch.ones_like(xd)], -1) @ tilt.transpose(-2, -1)
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index b33138f5e..d5ce389d3 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -54,10 +54,8 @@ def undistort_points(
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. Compilation and ONNX export always take 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>`_.
+ - Matching leading dimensions are preserved with or without tilt. Compilation and ONNX export always apply
+ the tilt branch, including for zero tilt, and the legacy unbatched form remains supported there as well.
.. warning::
The iteration has no convergence test and no valid-radius guard. Outside the iteration
@@ -132,7 +130,9 @@ def undistort_points(
if not torch.jit.is_scripting():
capture = capture or is_compiling()
if capture or torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):
- inv_tilt = tilt_projection(dist[..., 12], dist[..., 13], True)
+ inv_tilt = tilt_projection(dist[..., 12:13], dist[..., 13:14], True)
+ if inv_tilt.dim() == 2:
+ inv_tilt = inv_tilt.unsqueeze(0)
# Transposed untilt points (instead of [x,y,1]^T, we obtain [x,y,1])
x, y = transform_points(inv_tilt, torch.stack([x, y], dim=-1)).unbind(-1)
@@ -180,13 +180,11 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
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; compilation and ONNX export always take the tilt path, including for zero tilt. Tracked as
- `#4324 <https://github.com/kornia/kornia/issues/4324>`_.
+ - 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, including with non-zero tilt and under
+ compilation or ONNX export. 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``.
- 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)``.
diff --git a/tests/geometry/calibration/test_distort.py b/tests/geometry/calibration/test_distort.py
index 7a509e3ee..b860c28b1 100644
--- a/tests/geometry/calibration/test_distort.py
+++ b/tests/geometry/calibration/test_distort.py
@@ -18,6 +18,7 @@
import pytest
import torch
+import kornia.geometry.calibration.distort as distort_module
from kornia.geometry.calibration.distort import distort_points, tilt_projection
from kornia.geometry.camera.distortion_affine import distort_points_affine
@@ -47,6 +48,30 @@ def _k_asymmetric(device, dtype):
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 TestTiltProjection(BaseTester):
+ @pytest.mark.parametrize("return_inverse", [False, True])
+ def test_batch_shapes(self, return_inverse, device, dtype):
+ multi_axis = torch.zeros(2, 3, 1, device=device, dtype=dtype)
+ single_axis = torch.zeros(2, 1, device=device, dtype=dtype)
+ scalar = torch.zeros((), device=device, dtype=dtype)
+
+ assert tilt_projection(multi_axis, multi_axis, return_inverse).shape == (2, 3, 3, 3)
+ assert tilt_projection(single_axis, single_axis, return_inverse).shape == (2, 3, 3)
+ assert tilt_projection(scalar, scalar, return_inverse).shape == (3, 3)
+
+ @pytest.mark.parametrize("return_inverse", [False, True])
+ def test_multi_axis_matches_individual(self, return_inverse, device, dtype):
+ taux = torch.linspace(-0.03, 0.03, 6, device=device, dtype=dtype).reshape(2, 3, 1)
+ tauy = torch.linspace(0.02, -0.02, 6, device=device, dtype=dtype).reshape(2, 3, 1)
+
+ actual = tilt_projection(taux, tauy, return_inverse)
+ expected = torch.stack(
+ [torch.stack([tilt_projection(taux[i, j], tauy[i, j], return_inverse) for j in range(3)]) for i in range(2)]
+ )
+
+ self.assert_close(actual, expected)
+
+
class TestDistortPoints(BaseTester):
def test_smoke(self, device, dtype):
points = torch.rand(1, 2, device=device, dtype=dtype)
@@ -70,6 +95,35 @@ class TestDistortPoints(BaseTester):
pointsu = distort_points(points, K, distCoeff, new_K)
assert points.shape == pointsu.shape
+ @pytest.mark.parametrize("batch_shape", [(2, 3), (2, 1)])
+ def test_tilt_multi_axis_batch(self, batch_shape, device, dtype):
+ num_points = 5
+ points = torch.rand(*batch_shape, num_points, 2, device=device, dtype=dtype)
+ K = torch.eye(3, device=device, dtype=dtype).expand(*batch_shape, 3, 3).clone()
+ dist = torch.zeros(*batch_shape, 14, device=device, dtype=dtype)
+ dist[..., 12] = 0.01
+ dist[..., 13] = -0.02
+
+ actual = distort_points(points, K, dist)
+ expected = torch.stack(
+ [distort_points(p, k, d) for p, k, d in zip(points.flatten(0, -3), K.flatten(0, -3), dist.flatten(0, -2))]
+ ).reshape(*batch_shape, num_points, 2)
+
+ assert actual.shape == (*batch_shape, num_points, 2)
+ self.assert_close(actual, expected)
+
+ def test_export_multi_axis_batch(self, monkeypatch, device, dtype):
+ points = torch.rand(2, 3, 5, 2, device=device, dtype=dtype)
+ K = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3, 3).clone()
+ dist = torch.tensor([0.01, -0.02, 0.001, -0.001], device=device, dtype=dtype).expand(2, 3, 4).clone()
+ expected = distort_points(points, K, dist)
+
+ monkeypatch.setattr(distort_module, "is_exporting", lambda: True)
+ actual = distort_points(points, K, dist)
+
+ assert actual.shape == points.shape
+ self.assert_close(actual, expected)
+
@pytest.mark.parametrize(
"batch_size, num_points, num_distcoeff", [(1, 3, 4), (2, 4, 5), (3, 5, 8), (4, 6, 12), (5, 7, 14)]
)
@@ -246,10 +300,10 @@ class TestDistortPoints(BaseTester):
# 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])
+ # 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)
+ 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)
@@ -274,7 +328,7 @@ class TestDistortPoints(BaseTester):
# 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
+ 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)
@@ -295,8 +349,8 @@ class TestDistortPoints(BaseTester):
# ``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)
+ 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
@@ -315,19 +369,11 @@ class TestDistortPoints(BaseTester):
# 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)
+ 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_undistort.py b/tests/geometry/calibration/test_undistort.py
index b70ae7c9b..6d0a588e4 100644
--- a/tests/geometry/calibration/test_undistort.py
+++ b/tests/geometry/calibration/test_undistort.py
@@ -18,6 +18,7 @@
import pytest
import torch
+import kornia.geometry.calibration.undistort as undistort_module
from kornia.geometry.calibration.distort import distort_points
from kornia.geometry.calibration.undistort import undistort_image, undistort_points
from kornia.geometry.grid import create_meshgrid
@@ -75,6 +76,46 @@ class TestUndistortPoints(BaseTester):
pointsu = undistort_points(points, K, distCoeff, new_K)
assert points.shape == pointsu.shape
+ def test_tilt_multi_axis_batch(self, device, dtype):
+ num_points = 5
+ points = torch.rand(2, 3, num_points, 2, device=device, dtype=dtype)
+ K = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3, 3).clone()
+ dist = torch.zeros(2, 3, 14, device=device, dtype=dtype)
+ dist[..., 12] = 0.01
+ dist[..., 13] = -0.02
+
+ actual = undistort_points(points, K, dist)
+ expected = torch.stack(
+ [undistort_points(p, k, d) for p, k, d in zip(points.flatten(0, -3), K.flatten(0, -3), dist.flatten(0, -2))]
+ ).reshape(2, 3, num_points, 2)
+
+ assert actual.shape == points.shape
+ self.assert_close(actual, expected)
+
+ def test_export_multi_axis_batch(self, monkeypatch, device, dtype):
+ points = torch.rand(2, 3, 5, 2, device=device, dtype=dtype)
+ K = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3, 3).clone()
+ dist = torch.tensor([0.01, -0.02, 0.001, -0.001], device=device, dtype=dtype).expand(2, 3, 4).clone()
+ expected = undistort_points(points, K, dist)
+
+ monkeypatch.setattr(undistort_module, "is_exporting", lambda: True)
+ actual = undistort_points(points, K, dist)
+
+ assert actual.shape == points.shape
+ self.assert_close(actual, expected)
+
+ def test_export_unbatched(self, monkeypatch, device, dtype):
+ points = torch.rand(5, 2, device=device, dtype=dtype)
+ K = torch.eye(3, device=device, dtype=dtype)
+ dist = torch.tensor([0.01, -0.02, 0.001, -0.001], device=device, dtype=dtype)
+ expected = undistort_points(points, K, dist)
+
+ monkeypatch.setattr(undistort_module, "is_exporting", lambda: True)
+ actual = undistort_points(points, K, dist)
+
+ assert actual.shape == points.shape
+ self.assert_close(actual, expected)
+
@pytest.mark.parametrize(
"batch_size, num_points, num_distcoeff", [(1, 3, 4), (2, 4, 5), (3, 5, 8), (4, 6, 12), (5, 7, 14)]
)
@@ -414,37 +455,6 @@ class TestUndistortPoints(BaseTester):
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)
@@ -491,21 +501,21 @@ 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_tilt_multi_axis_batch(self, device, dtype):
+ image = torch.rand(2, 3, 1, 5, 6, device=device, dtype=dtype)
+ K = torch.tensor([[3.0, 0.0, 3.0], [0.0, 2.0, 2.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ K = K.expand(2, 3, 3, 3).clone()
+ dist = torch.zeros(2, 3, 14, device=device, dtype=dtype)
+ dist[..., 12] = 0.01
+ dist[..., 13] = 0.02
+
+ actual = undistort_image(image, K, dist)
+ expected = torch.stack(
+ [torch.stack([undistort_image(image[i, j], K[i, j], dist[i, j]) for j in range(3)]) for i in range(2)]
+ )
+
+ assert actual.shape == image.shape
+ self.assert_close(actual, expected)
def test_exception(self, device, dtype):
with pytest.raises(ValueError):