π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): support empty batches across camera paths (#4386)
Puttala Jeevan Kumarb479e964f5e8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bbee881c3..2a1fc397e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -410,6 +410,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0* Make calibration `distort_points` and `undistort_points` tilt checks compatible with`torch.compile(fullgraph=True)`, preserving eager behavior. (#4391)* Canny hysteresis preserves the input dtype, avoiding a convolution dtype mismatch for half-precision images. (#4393)+* `PinholeCamera`, `StereoCamera`, and `warp_frame_depth` now support empty batches. (#4386)* `elastic_transform2d` now builds its identity sampling grid with the requested `align_corners`convention, so a zero displacement field preserves the input image. (closes #4235). (#4382)diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.pyindex 9ffa535f1..73516afa3 100644--- a/kornia/geometry/camera/pinhole.py+++ b/kornia/geometry/camera/pinhole.py@@ -62,8 +62,7 @@ class PinholeCamera:`#4264 <https://github.com/kornia/kornia/issues/4264>`_, the in-place :meth:`scale_` failure on aninteger ``height`` / ``width`` with a floating-point scale factor`#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+ `#4266 <https://github.com/kornia/kornia/issues/4266>`_. The behaviour described here isdocumented as it is; the issues above track the repairs.Args:@@ -100,7 +99,8 @@ class PinholeCamera:@staticmethoddef _check_valid(data_iter: Iterable[torch.Tensor]) -> bool:- if not all(data.shape[0] for data in data_iter):+ batch_sizes = [data.shape[0] for data in data_iter]+ if not all(batch_size == batch_sizes[0] for batch_size in batch_sizes):raise ValueError("Arguments shapes must match")return Truediff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.pyindex 9ffe1e2aa..46315a984 100644--- a/kornia/geometry/camera/stereo.py+++ b/kornia/geometry/camera/stereo.py@@ -97,9 +97,7 @@ class StereoCamera:any rig the constructor accepts. The ``tx * fx < 0`` guard is quantified with ``torch.all``, so abatch whose second element has the two cameras the wrong way round is accepted and reprojects thatelement behind the camera. And ``tx = 0`` passes the same guard, collapsing ``Q`` so that every- disparity reprojects to the origin with no ``inf`` to notice. An empty batch is rejected by that- guard as well, because ``torch.all`` of an empty tensor is ``True``- (`#4281 <https://github.com/kornia/kornia/issues/4281>`_). The per-camera :math:`(3, 4)` shape check+ disparity reprojects to the origin with no ``inf`` to notice. The per-camera :math:`(3, 4)` shape checkcompares ``shape[:1]`` rather than ``shape[-2:]``, so it can never fire and a :math:`(B, 4, 4)` pairis accepted, building the same :math:`(B, 4, 4)` ``Q`` as the :math:`(B, 3, 4)` pair it should haverequired. Tracked as@@ -196,7 +194,7 @@ class StereoCamera:# Ensure that tx * fx is negative and exists.tx_fx = rectified_right_camera[..., 0, 3]- if not is_exporting() and torch.all(torch.gt(tx_fx, 0)):+ if not is_exporting() and tx_fx.numel() > 0 and torch.all(torch.gt(tx_fx, 0)):raise StereoException(f"Expected :math:`T_x * f_x` to be negative. Got {tx_fx}.")@propertydiff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex feab55519..dc03821ab 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -417,13 +417,6 @@ def warp_frame_depth(:class:`~kornia.geometry.depth.DepthWarper` states the mapping in full. Tracked as`#4273 <https://github.com/kornia/kornia/issues/4273>`_.- .. warning::- An empty batch (:math:`B = 0`) raises ``ZeroDivisionError`` from ``transform_points`` -- its- batch-repeat count is ``0 // 0`` -- before any sampling runs, rather than returning an empty result,- although the shape guards on the way in accept it and- :func:`~kornia.geometry.depth.depth_to_3d` -- the same unprojection in the other layout -- returns an- empty point cloud. Tracked as `#4281 <https://github.com/kornia/kornia/issues/4281>`_.-Args:image_src: image tensor in the source frame with shape :math:`(B,D,H,W)`.depth_dst: depth tensor in the destination frame with shape :math:`(B,1,H,W)`.@@ -441,6 +434,16 @@ def warp_frame_depth(KORNIA_CHECK_SHAPE(src_trans_dst, ["B", "4", "4"])KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])+ if (+ image_src.shape[0] == 0+ and depth_dst.shape[0] == 0+ and src_trans_dst.shape[0] == 0+ and camera_matrix.shape[0] == 0+ ):+ output_shape = (0, image_src.shape[1], depth_dst.shape[-2], depth_dst.shape[-1])+ output_zero = image_src.reshape(-1)[:1].sum() * 0.0+ return output_zero.reshape(1, 1, 1, 1).expand(output_shape)+# unproject source points to camera frame as (B, H, W, 3) directly β avoids two permutespoints_3d_dst: torch.Tensor = depth_to_3d_v2(depth_dst.squeeze(1), camera_matrix, normalize_points) # BxHxWx3diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.pyindex b4e81e302..b8c0ad08b 100644--- a/tests/geometry/camera/test_pinhole.py+++ b/tests/geometry/camera/test_pinhole.py@@ -884,28 +884,40 @@ class TestPinholeCamera(BaseTester):with pytest.raises(ValueError, match="at least a 2D tensor"):kornia.geometry.camera.project_points(point, _k44(device, dtype)[:, :3, :3].contiguous())- def test_wart_constructor_rejects_an_empty_batch_4281(self, device, dtype):- # Mixed pin. The FIRST assertion is a wart pin for kornia#4281: _check_valid is- # ``all(data.shape[0] for ...)``, which tests that each batch size is non-zero rather than that they are- # EQUAL, so a perfectly consistent B = 0 camera is rejected with a message about mismatched shapes. It- # pins the CURRENT behavior, is NOT a contract, and is the only assertion here that is deleted when- # #4281 is repaired. The SECOND assertion is the CONVENTION the repair has to converge on and SURVIVES- # it: the free functions on the same surface already follow kornia's empty-in/empty-out rule, so- # project_points on a (0, 1, 3) input returns a (0, 1, 2) tensor rather than raising.- # Snippet used to generate expected: both calls executed 2026-09-05 (torch 2.14.0, every dtype)- # -> ValueError("Arguments shapes must match") and shape (0, 1, 2).- with pytest.raises(ValueError, match="Arguments shapes must match"):- kornia.geometry.camera.PinholeCamera(- torch.zeros(0, 4, 4, device=device, dtype=dtype),- torch.zeros(0, 4, 4, device=device, dtype=dtype),- torch.zeros(0, device=device, dtype=dtype),- torch.zeros(0, device=device, dtype=dtype),- )+ def test_constructor_accepts_an_empty_batch_4281(self, device, dtype):+ # Regression for kornia#4281: a consistent empty camera batch is valid.+ intrinsics = torch.zeros(0, 4, 4, device=device, dtype=dtype)+ extrinsics = torch.zeros(0, 4, 4, device=device, dtype=dtype)+ height = torch.zeros(0, device=device, dtype=dtype)+ width = torch.zeros(0, device=device, dtype=dtype)++ camera = kornia.geometry.camera.PinholeCamera(intrinsics, extrinsics, height, width)++ assert camera.batch_size == 0+ assert camera.intrinsics.shape == (0, 4, 4)+ assert camera.extrinsics.shape == (0, 4, 4)+ assert camera.height.shape == (0,)+ assert camera.width.shape == (0,)+ for tensor in (camera.intrinsics, camera.extrinsics, camera.height, camera.width):+ assert tensor.dtype == dtype+ assert tensor.device == device++ # Free functions on the same surface follow the same empty-in/empty-out convention.empty = kornia.geometry.camera.project_points(torch.zeros(0, 1, 3, device=device, dtype=dtype), _k44(device, dtype)[:, :3, :3].contiguous())assert empty.shape == (0, 1, 2)+ @pytest.mark.parametrize("batch_sizes", [(1, 2, 1, 1), (0, 1, 0, 0)])+ def test_constructor_rejects_mismatched_batch_sizes_4281(self, batch_sizes, device, dtype):+ with pytest.raises(ValueError, match="Arguments shapes must match"):+ kornia.geometry.camera.PinholeCamera(+ torch.zeros(batch_sizes[0], 4, 4, device=device, dtype=dtype),+ torch.zeros(batch_sizes[1], 4, 4, device=device, dtype=dtype),+ torch.zeros(batch_sizes[2], device=device, dtype=dtype),+ torch.zeros(batch_sizes[3], device=device, dtype=dtype),+ )+def test_wart_project_and_project_points_disagree_at_z_zero_4267(self, device, dtype):# Wart pin for kornia#4267: PinholeCamera.project and the free function# project_points are documented as the same projection and agree exactly away from the singularity, butdiff --git a/tests/geometry/camera/test_stereo.py b/tests/geometry/camera/test_stereo.pyindex 209fd6d7e..20363d913 100644--- a/tests/geometry/camera/test_stereo.py+++ b/tests/geometry/camera/test_stereo.py@@ -232,6 +232,18 @@ class TestStereoCamera(BaseTester):assert stereo_camera.Q.shape == (batch_size, 4, 4)assert stereo_camera.Q.dtype in (torch.float16, torch.float32, torch.float64)+ def test_empty_batch_4281(self, device, dtype):+ # Regression for kornia#4281: an empty stereo rig is vacuously valid.+ left_rectified_camera = torch.zeros(0, 3, 4, device=device, dtype=dtype)+ right_rectified_camera = torch.zeros(0, 3, 4, device=device, dtype=dtype)++ stereo_camera = StereoCamera(left_rectified_camera, right_rectified_camera)++ assert stereo_camera.batch_size == 0+ assert stereo_camera.Q.shape == (0, 4, 4)+ assert stereo_camera.Q.dtype == dtype+ assert stereo_camera.Q.device == device+def test_stereo_camera_attributes_real(self, batch_size, device, dtype):"""Test proper setup of the class for real data."""left_rectified_camera, right_rectified_camera = _RealTestData._get_real_stereo_camera(batch_size, device, dtype)@@ -581,24 +593,3 @@ class TestStereoCamera(BaseTester):assert torch.equal(square.Q, cam.Q)with pytest.raises(StereoException, match="to have 3 dimensions"):StereoCamera(cam.rectified_left_camera[0], cam.rectified_right_camera[0])-- def test_wart_stereo_rejects_an_empty_batch_4281(self, device, dtype):- # Wart pin for kornia#4281: ``torch.all`` of an empty tensor is True, so the- # sign guard fires on an empty batch and B = 0 is rejected with a message about a tensor that has no- # elements at all. kornia's degenerate-shape convention is empty in, empty out; the non-empty rig on the- # same code path is accepted.- # The match is on the EMPTY tensor in the message, not on "to be negative", because the all-positive rig- # pinned above raises the same sentence -- ``Got tensor([50.])`` -- so a looser match would not tell the- # two apart.- # Snippet used to generate expected: StereoCamera(zeros(0, 3, 4), zeros(0, 3, 4)) recorded in- # original commit 1a96bfd1 (torch 2.14.0) -> StereoException("Expected :math:`T_x * f_x` to be negative. Got- # tensor([]).") on cpu float32, "... Got tensor([], dtype=torch.float64)." / "torch.float16" /- # "torch.bfloat16" on the other cpu cells and "... Got tensor([], device='mps:0')." on mps -- so the- # regex stops before the closing bracket. The all-positive rig raises "... Got tensor([50.])" in the- # same cells and does not match it.- # Pins the CURRENT behavior; NOT a contract; delete when #4281 is repaired.- with pytest.raises(StereoException, match=r"Got tensor\(\[\]"):- StereoCamera(- torch.zeros(0, 3, 4, device=device, dtype=dtype), torch.zeros(0, 3, 4, device=device, dtype=dtype)- )- assert self._asymmetric_stereo(device, dtype, batch=2).Q.shape == (2, 4, 4)diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex 5cbf1b750..97f831a6e 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -581,6 +581,22 @@ class TestWarpFrameDepth(BaseTester):image_dst = kornia.geometry.depth.warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix)assert image_dst.shape == (1, 2, height, width)+ def test_empty_batch_4281(self, device, dtype):+ # Regression for kornia#4281: output geometry comes from the destination depth map.+ image_src = torch.zeros(0, 3, 2, 3, device=device, dtype=dtype, requires_grad=True)+ depth_dst = torch.zeros(0, 1, 4, 5, device=device, dtype=dtype)+ src_trans_dst = torch.zeros(0, 4, 4, device=device, dtype=dtype)+ camera_matrix = torch.zeros(0, 3, 3, device=device, dtype=dtype)++ image_dst = kornia.geometry.depth.warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix)++ assert image_dst.shape == (0, 3, 4, 5)+ assert image_dst.dtype == dtype+ assert image_dst.device == device+ assert image_dst.requires_grad+ image_dst.sum().backward()+ assert image_src.grad is not None+def test_translation(self, device, dtype):# this is for normalize_points=Falseimage_src = torch.tensor(@@ -701,30 +717,6 @@ class TestWarpFrameDepth(BaseTester):assert (warped - image_src).abs().max().item() > 0.5assert torch.equal(warp_frame_depth(image_src, depth_dst, _eye4(device, dtype), camera_matrix), image_src)- def test_wart_warp_frame_depth_rejects_an_empty_batch_4281(self, device, dtype):- # Wart pin for kornia#4281: an empty batch raises a bare- # ZeroDivisionError from transform_points (0 // 0 in its batch-repeat count) rather than returning an empty- # result, although- # every shape guard on the way in accepts B = 0 and depth_to_3d -- the same computation in the other- # layout -- handles it. kornia's degenerate-shape convention is empty in, empty out.- # Snippet used to generate expected: warp_frame_depth(zeros(0, 2, 4, 5), ones(0, 1, 4, 5),- # zeros(0, 4, 4), zeros(0, 3, 3)) executed 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) ->- # ZeroDivisionError("integer division or modulo by zero") on cpu for float32, float64, float16 and- # bfloat16 and on mps for float32 and float16; depth_to_3d(zeros(0, 1, 4, 5), zeros(0, 3, 3)) returns- # shape (0, 3, 4, 5) in the same cells.- # Pins the CURRENT behavior; NOT a contract; delete when #4281 is repaired.- with pytest.raises(ZeroDivisionError, match="integer division or modulo by zero"):- warp_frame_depth(- torch.zeros(0, 2, 4, 5, device=device, dtype=dtype),- torch.ones(0, 1, 4, 5, device=device, dtype=dtype),- torch.zeros(0, 4, 4, device=device, dtype=dtype),- torch.zeros(0, 3, 3, device=device, dtype=dtype),- )- empty = depth_to_3d(- torch.zeros(0, 1, 4, 5, device=device, dtype=dtype), torch.zeros(0, 3, 3, device=device, dtype=dtype)- )- assert empty.shape == (0, 3, 4, 5)-class TestDepthWarperConventions(BaseTester):"""Convention and wart pins for :class:`~kornia.geometry.depth.DepthWarper` and ``depth_warp``."""