π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): validate pixel2cam inverse intrinsics shape (#4381)
Zhenhuan Wang749a1c171219
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3ead07170..d775f312a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -369,6 +369,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `pixel2cam` now validates the full `Bx4x4` shape of `intrinsics_inv`, rejecting invalid matrix sizes+ before they cause unrelated transformation errors or return the wrong number of coordinate components. (#4381)* `Boxes.to_mask` leaves list-padding channels empty, including after coordinate transforms,instead of treating padding entries as real boxes. (#4390)* Fixed fixture teardown between files when running half-precision tests withdiff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.pyindex a8e9a7818..ab0da1494 100644--- a/kornia/geometry/camera/pinhole.py+++ b/kornia/geometry/camera/pinhole.py@@ -833,15 +833,11 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: t- ``intrinsics_inv`` is a :math:`(B, 4, 4)` inverse calibration matrix β the layout of:class:`~kornia.geometry.camera.pinhole.PinholeCamera`, not the :math:`(*, 3, 3)` ``K`` the functional APItakes β and ``depth`` is the camera-frame ``z`` at each pixel of the ``(u, v, 1)`` grid.- - ``intrinsics_inv`` is checked for rank 3 alone, so a :math:`(B, 3, 3)` inverse passes the check and- fails further in with an unrelated message.+ - ``intrinsics_inv`` must have shape :math:`(B, 4, 4)`; other ranks or matrix sizes raise+ :class:`ValueError` before transforming the pixel coordinates.- ``depth`` must have shape ``Bx1xHxW``; multi-channel depth raises :class:`ValueError`.``pixel_coords`` must have shape ``BxHxWx3``.- .. warning::- The rank-only ``intrinsics_inv`` check is tracked in- `#4266 <https://github.com/kornia/kornia/issues/4266>`_.-Args:depth: the source depth maps. Shape must be Bx1xHxW.intrinsics_inv: the inverse intrinsics camera matrix. Shape must be Bx4x4.@@ -853,7 +849,7 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: t"""if not (len(depth.shape) == 4 and depth.shape[1] == 1):raise ValueError(f"Input depth has to be in the shape of Bx1xHxW. Got {depth.shape}")- if not len(intrinsics_inv.shape) == 3:+ if not (len(intrinsics_inv.shape) == 3 and intrinsics_inv.shape[-2:] == (4, 4)):raise ValueError(f"Input intrinsics_inv has to be in the shape of Bx4x4. Got {intrinsics_inv.shape}")if not (len(pixel_coords.shape) == 4 and pixel_coords.shape[3] == 3):raise ValueError(f"Input pixel_coords has to be in the shape of BxHxWx3. Got {pixel_coords.shape}")diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.pyindex f14a34145..b4e81e302 100644--- a/tests/geometry/camera/test_pinhole.py+++ b/tests/geometry/camera/test_pinhole.py@@ -322,21 +322,36 @@ class TestPixel2Cam(BaseTester):self.gradcheck(kornia.geometry.camera.pixel2cam, (depth, intrinsics_inv, pixel_coords_input), fast_mode=False)- def test_wart_pixel2cam_guard_admits_a_3x3_inverse_4266(self, device, dtype):- # Wart pin for kornia#4266: pixel2cam's ``intrinsics_inv`` guard is written- # ``if not len(intrinsics_inv.shape) == 3``, so it checks the RANK alone and never inspects the trailing- # 4x4 its own message promises. A (B, 3, 3) inverse -- the shape every free function on this surface- # takes -- has rank 3, passes the guard, and the failure surfaces much later, from transform_points.- # Snippet used to generate expected: pixel2cam(ones(1,1,2,3), (1,3,3) inverse, zeros(1,2,3,3)) executed- # 2026-09-05 (torch 2.14.0) -> ValueError("Last input dimensions must differ by one unit Got...").- # Pins the CURRENT behavior; NOT a contract; delete when #4266 is repaired.+ @pytest.mark.parametrize(+ "intrinsics_shape",+ [(), (4,), (4, 4), (1, 4, 4, 1), (1, 3, 3), (1, 2, 2), (1, 5, 5), (1, 3, 4), (1, 4, 3), (1, 5, 4)],+ )+ def test_invalid_intrinsics_shape_4266(self, intrinsics_shape, device, dtype):+ # A rank-only guard lets non-square matrices return the wrong number of coordinate components.depth = torch.ones(1, 1, 2, 3, device=device, dtype=dtype)- pixel_coords = torch.zeros(1, 2, 3, 3, device=device, dtype=dtype)- intrinsics_inv_3x3 = torch.tensor(- [[[0.01, 0.0, -0.04], [0.0, 0.01, -0.03], [0.0, 0.0, 1.0]]], device=device, dtype=dtype- )- with pytest.raises(ValueError, match="Last input dimensions must differ by one unit"):- kornia.geometry.camera.pixel2cam(depth, intrinsics_inv_3x3, pixel_coords)+ pixel_coords = torch.ones(1, 2, 3, 3, device=device, dtype=dtype)+ intrinsics_inv = torch.ones(intrinsics_shape, device=device, dtype=dtype)++ with pytest.raises(ValueError, match="Input intrinsics_inv has to be in the shape of Bx4x4") as exc_info:+ kornia.geometry.camera.pixel2cam(depth, intrinsics_inv, pixel_coords)++ assert str(intrinsics_inv.shape) in str(exc_info.value)++ @pytest.mark.parametrize("intrinsics_batch, points_batch", [(1, 1), (2, 2), (1, 2)])+ def test_intrinsics_batch_broadcast(self, intrinsics_batch, points_batch, device, dtype):+ # fx=2, fy=4, cx=4, cy=3: pixel (6, 11) at depth 2 maps to camera point (2, 4, 2).+ intrinsics_inv = torch.tensor(+ [[[0.5, 0.0, -2.0, 0.0], [0.0, 0.25, -0.75, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],+ device=device,+ dtype=dtype,+ ).expand(intrinsics_batch, -1, -1)+ depth = torch.full((points_batch, 1, 1, 1), 2.0, device=device, dtype=dtype)+ pixel_coords = torch.tensor([[[[6.0, 11.0, 1.0]]]], device=device, dtype=dtype).expand(points_batch, -1, -1, -1)++ actual = kornia.geometry.camera.pixel2cam(depth, intrinsics_inv, pixel_coords)++ expected = torch.tensor([[[[2.0, 4.0, 2.0]]]], device=device, dtype=dtype).expand(points_batch, -1, -1, -1)+ self.assert_close(actual, expected)def test_convention_pixel2cam_rejects_multi_channel_depth_4266(self, device, dtype):# Regression pin for kornia#4266: multi-channel depth must be rejected instead of scaling