Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix pinhole camera and coordinate shape guards (#4387)

SHILIN KONG7a697dcf058e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe92df17e..890204d53 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -369,6 +369,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* Corrected the matrix-shape checks shared by `PinholeCamera` and `PinholeCamerasList`, the
+ `pixel2cam` coordinate-shape check, and the `cam2pixel` coordinate/projection checks. Invalid
+ inputs now raise the intended `ValueError` instead of being accepted or failing later in tensor
+ operations. The rank-4 matrices used by `PinholeCamerasList` remain supported. (#4387)
* Fixed `dx_distort_points_kannala_brandt` to return the true Jacobian of `distort_points_kannala_brandt`, including a finite affine Jacobian at the origin. (#4277, #4368)
* `Boxes3D.from_tensor(..., validate_boxes=True)` rejects non-finite coordinates, and `validate_bbox3d`
returns `False` for them instead of raising an `AssertionError` that names the wrong defect. This is the
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index 8e7217a37..a8e9a7818 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -61,8 +61,7 @@ class PinholeCamera:
that remains on :meth:`scale_` and the setters is
`#4264 <https://github.com/kornia/kornia/issues/4264>`_, the in-place :meth:`scale_` failure on an
integer ``height`` / ``width`` with a floating-point scale factor
- `#4265 <https://github.com/kornia/kornia/issues/4265>`_, the shape
- guards that admit an ``intrinsics`` whose projection is meaningless
+ `#4265 <https://github.com/kornia/kornia/issues/4265>`_, the batch-size and point-shape limitations
`#4266 <https://github.com/kornia/kornia/issues/4266>`_, and the rejection of an empty batch
(:math:`B = 0`) `#4281 <https://github.com/kornia/kornia/issues/4281>`_. The behaviour described here is
documented as it is and pinned by the ``test_convention_*`` / ``test_wart_*`` tests in
@@ -70,10 +69,9 @@ class PinholeCamera:
Args:
intrinsics: torch.Tensor with shape :math:`(B, 4, 4)`
- containing the full 4x4 camera calibration matrix. The constructor rejects it when it is neither
- rank 3 nor rank 4 **and** its last two dimensions are not 4x4, so a :math:`(B, 3, 3)` matrix is
- accepted, as is an unbatched :math:`(4, 4)` matrix, although :meth:`project` needs
- the documented :math:`(B, 4, 4)`.
+ containing the full 4x4 camera calibration matrix. The shared shape validator also accepts
+ :math:`(B, N, 4, 4)` for ``PinholeCamerasList``, while :meth:`project` requires
+ the documented :math:`(B, 4, 4)` layout.
extrinsics: torch.Tensor with shape :math:`(B, 4, 4)`
containing the full 4x4 rotation-translation matrix, checked by the same predicate.
height: torch.Tensor with shape :math:`(B)` containing the image height.
@@ -109,7 +107,7 @@ class PinholeCamera:
@staticmethod
def _check_valid_params(data: torch.Tensor, data_name: str) -> bool:
- if len(data.shape) not in (3, 4) and data.shape[-2:] != (4, 4): # Shouldn't this be an OR logic than AND?
+ if len(data.shape) not in (3, 4) or data.shape[-2:] != (4, 4):
raise ValueError(
f"Argument {data_name} shape must be in the following shape Bx4x4 or BxNx4x4. Got {data.shape}"
)
@@ -838,11 +836,10 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: t
- ``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.
- ``depth`` must have shape ``Bx1xHxW``; multi-channel depth raises :class:`ValueError`.
- The ``pixel_coords`` guard raises when the input is not rank 4 **and** its fourth dimension is 3;
- for lower ranks, accessing that dimension can itself raise :class:`IndexError`.
+ ``pixel_coords`` must have shape ``BxHxWx3``.
.. warning::
- The rank-only ``intrinsics_inv`` check and the incorrect ``pixel_coords`` predicate are tracked in
+ The rank-only ``intrinsics_inv`` check is tracked in
`#4266 <https://github.com/kornia/kornia/issues/4266>`_.
Args:
@@ -858,8 +855,8 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: t
raise ValueError(f"Input depth has to be in the shape of Bx1xHxW. Got {depth.shape}")
if not len(intrinsics_inv.shape) == 3:
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 {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}")
cam_coords: torch.Tensor = transform_points(intrinsics_inv[:, None], pixel_coords)
return cam_coords * depth.permute(0, 2, 3, 1)
@@ -877,19 +874,13 @@ def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: flo
- ``dst_proj_src`` is a :math:`(B, 4, 4)` projection matrix β€” the layout of
:class:`~kornia.geometry.camera.pinhole.PinholeCamera`, not the :math:`(*, 3, 3)` ``K`` the functional API
takes β€” and the result is ``(u, v)`` pixel coordinates in the destination frame.
- - the projection guard raises exactly when ``dst_proj_src`` is not rank 3 **and** its trailing
- dimensions are :math:`(4, 4)`. Thus an unbatched :math:`(4, 4)` matrix raises at the guard, while
- a :math:`(B, 3, 3)` matrix passes and fails later inside ``transform_points``. The coordinate guard
- similarly raises when the input is not rank 4 **and** its fourth dimension is 3; for lower ranks,
- accessing that dimension can itself raise :class:`IndexError`.
- the perspective division is ``x / (z + eps)`` rather than a guarded divide. With the default ``eps``,
a projected coordinate ``x = 100, z = 0`` gives about ``1e14`` in ``float32``, ``float64`` and
``bfloat16``, and ``inf`` in ``float16`` (where ``eps`` rounds to zero). A zero numerator then gives
zero in the former dtypes and ``nan`` in ``float16``; ``eps`` also biases small nonzero depths.
.. warning::
- The incorrect shape predicates are tracked in `#4266 <https://github.com/kornia/kornia/issues/4266>`_, and the
- ``z = 0`` answer in `#4267 <https://github.com/kornia/kornia/issues/4267>`_.
+ The ``z = 0`` answer is tracked in `#4267 <https://github.com/kornia/kornia/issues/4267>`_.
Args:
cam_coords_src: (x, y, z) coordinates defined in the first camera coordinates system. Shape must be BxHxWx3.
@@ -901,9 +892,9 @@ def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: flo
torch.Tensor of shape BxHxWx2 with (u, v) pixel coordinates.
"""
- if not len(cam_coords_src.shape) == 4 and cam_coords_src.shape[3] == 3:
+ if not (len(cam_coords_src.shape) == 4 and cam_coords_src.shape[3] == 3):
raise ValueError(f"Input cam_coords_src has to be in the shape of BxHxWx3. Got {cam_coords_src.shape}")
- if not len(dst_proj_src.shape) == 3 and dst_proj_src.shape[-2:] == (4, 4):
+ if not (len(dst_proj_src.shape) == 3 and dst_proj_src.shape[-2:] == (4, 4)):
raise ValueError(f"Input dst_proj_src has to be in the shape of Bx4x4. Got {dst_proj_src.shape}")
# apply projection matrix to points
point_coords: torch.Tensor = transform_points(dst_proj_src[:, None], cam_coords_src)
diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.py
index 2fb2fc646..f14a34145 100644
--- a/tests/geometry/camera/test_pinhole.py
+++ b/tests/geometry/camera/test_pinhole.py
@@ -22,6 +22,7 @@ import torch
import kornia
from kornia.geometry.camera.pinhole import (
+ PinholeCamerasList,
get_optical_pose_base,
homography_i_H_ref,
inverse_pinhole_matrix,
@@ -182,28 +183,29 @@ class TestCam2Pixel(BaseTester):
expected = torch.tensor([[[[1.0e14, 2.0e14], [5.0e13, 1.0e14]]]], device=device, dtype=dtype)
self.assert_close(uv, expected)
- def test_wart_cam2pixel_guard_admits_a_3x3_projection_4266(self, device, dtype):
- # Wart pin for kornia#4266: cam2pixel's second guard is written
- # ``if not len(dst_proj_src.shape) == 3 and dst_proj_src.shape[-2:] == (4, 4)``, so the shape clause is
- # live: it rejects a wrong rank only when the trailing shape is (4, 4). A (B, 3, 3) projection has
- # the accepted rank, passes the guard whose message promises Bx4x4, and fails much later inside
- # transform_points with a message about homogeneous dimensions rather than at the guard.
- # Snippet used to generate expected: cam2pixel([[[[1., 2., 4.]]]], _k44(...)[:, :3, :3]) executed
- # 2026-09-05 (torch 2.14.0, cpu and mps, every dtype)
- # -> 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("shape", [(), (4, 4), (3, 3), (1, 3, 3), (1, 3, 4), (1, 5, 4), (1, 1, 4, 4)])
+ def test_invalid_projection_shape_4266(self, shape, device, dtype):
cam_coords = torch.tensor([[[[1.0, 2.0, 4.0]]]], device=device, dtype=dtype)
- proj_3x3 = _k44(device, dtype)[:, :3, :3].contiguous()
- with pytest.raises(ValueError, match="Last input dimensions must differ by one unit"):
- kornia.geometry.camera.cam2pixel(cam_coords, proj_3x3)
+ projection = torch.ones(shape, device=device, dtype=dtype)
with pytest.raises(ValueError, match="Input dst_proj_src has to be in the shape of Bx4x4"):
- kornia.geometry.camera.cam2pixel(cam_coords, torch.eye(4, device=device, dtype=dtype))
- # An unbatched 3x3 passes this guard and instead reaches transform_points' rank check.
- with pytest.raises(ValueError, match="Input batch size must be the same for both tensors"):
- kornia.geometry.camera.cam2pixel(cam_coords, torch.eye(3, device=device, dtype=dtype))
+ kornia.geometry.camera.cam2pixel(cam_coords, projection)
+
+ @pytest.mark.parametrize("shape", [(), (3,), (1, 3), (1, 2, 3), (1, 2, 3, 2), (1, 2, 3, 4), (1, 2, 3, 1, 3)])
+ def test_invalid_coordinate_shape_4266(self, shape, device, dtype):
+ cam_coords = torch.ones(shape, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="Input cam_coords_src has to be in the shape of BxHxWx3"):
+ kornia.geometry.camera.cam2pixel(cam_coords, _k44(device, dtype))
class TestPixel2Cam(BaseTester):
+ @pytest.mark.parametrize("shape", [(), (3,), (1, 3), (1, 2, 3), (1, 2, 3, 2), (1, 2, 3, 4), (1, 2, 3, 1, 3)])
+ def test_invalid_coordinate_shape_4266(self, shape, device, dtype):
+ depth = torch.ones(1, 1, 2, 3, device=device, dtype=dtype)
+ pixel_coords = torch.ones(shape, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="Input pixel_coords has to be in the shape of BxHxWx3") as exc_info:
+ kornia.geometry.camera.pixel2cam(depth, _k44(device, dtype), pixel_coords)
+ assert str(pixel_coords.shape) in str(exc_info.value)
+
@pytest.mark.parametrize("depth_shape", [(), (2,), (2, 1, 3), (2, 2, 3, 4), (2, 3, 3, 4), (2, 1, 3, 4, 1)])
def test_invalid_depth_shape(self, depth_shape, device, dtype):
depth = torch.ones(depth_shape, device=device, dtype=dtype)
@@ -823,20 +825,30 @@ class TestPinholeCamera(BaseTester):
self.assert_close(cam.height, torch.tensor([6], device=device))
self.assert_close(cam.width, torch.tensor([8], device=device))
- def test_wart_constructor_accepts_3x3_intrinsics_whose_projection_is_garbage_4266(self, device, dtype):
- # Wart pin for kornia#4266: _check_valid_params uses ``and`` where ``or``
- # was meant (the source even carries the author's "Shouldn't this be an OR logic than AND?"), so a
- # (1, 3, 3) intrinsics with a (1, 3, 4) extrinsics passes a validator whose message promises Bx4x4, and
- # .project returns a (1, 1) tensor of nonsense instead of a (1, 2) pixel.
- # Snippet used to generate expected: PinholeCamera(K[:, :3, :3], E[:, :3, :]).project([[1., 2., 4.]])
- # executed 2026-09-05 (torch 2.14.0) -> shape (1, 1), float32 value [[0.5471698]] (dtype-dependent, so
- # only the cardinality is pinned). NOT a contract; delete when #4266 is repaired.
- K = _k44(device, dtype)[:, :3, :3].contiguous()
- E = _e44(device, dtype, tx=1.0)[:, :3, :].contiguous()
+ @pytest.mark.parametrize("shape", [(4, 4), (1, 3, 3), (1, 3, 4), (1, 5, 5), (1, 2, 3, 3), (1, 1, 1, 4, 4)])
+ @pytest.mark.parametrize("parameter", ["intrinsics", "extrinsics"])
+ def test_invalid_parameter_shape_4266(self, shape, parameter, device, dtype):
+ batch_size = shape[0]
+ params = {
+ "intrinsics": _k44(device, dtype).expand(batch_size, -1, -1),
+ "extrinsics": _e44(device, dtype).expand(batch_size, -1, -1),
+ "height": torch.full((batch_size,), 6, device=device, dtype=dtype),
+ "width": torch.full((batch_size,), 8, device=device, dtype=dtype),
+ }
+ params[parameter] = torch.ones(shape, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match=f"Argument {parameter} shape must be"):
+ kornia.geometry.camera.PinholeCamera(**params)
+
+ def test_camera_list_preserves_rank_four_parameters(self, device, dtype):
cam = kornia.geometry.camera.PinholeCamera(
- K, E, torch.tensor([6], device=device), torch.tensor([8], device=device)
+ _k44(device, dtype), _e44(device, dtype), torch.tensor([6], device=device), torch.tensor([8], device=device)
)
- assert cam.project(torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype)).shape == (1, 1)
+ cameras = PinholeCamerasList([cam, cam.clone()])
+ assert cameras.intrinsics.shape == (1, 2, 4, 4)
+ assert cameras.extrinsics.shape == (1, 2, 4, 4)
+ assert cameras.num_cameras == 2
+ points = torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype)
+ self.assert_close(cameras.get_pinhole(1).project(points), cam.project(points))
def test_wart_project_rejects_an_unbatched_point_with_indexerror_4266(self, device, dtype):
# Wart pin for kornia#4266: PinholeCamera.project documents ``(*, 3)``