π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Accept scalar camera parameters in depth_from_disparity (#4392)
SHILIN KONGdead87ac0003
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2a1fc397e..a186408ac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -464,6 +464,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`eps=1e-8` is below float16 resolution, so half-precision callers must pass a representable `eps`.(#4280, #4348)+* `depth_from_disparity` accepts Python integers and scalar tensors for the baseline and focal length. (#4392)+* `iterative_quad_interp3d`'s `max_candidates` cap is now a per-image budget rather than one sharedacross the batch. The `topk` ranked the flattened `(B*C)` candidate list, so an image's refinedkeypoints depended on which other images shared its batch: a quiet image next to a high-contrastdiff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex dc03821ab..d90e28d6a 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -790,10 +790,9 @@ def depth_from_disparity(- the depth is ``baseline * focal / disparity``, elementwise: ``baseline`` is the distance between thetwo camera centres and ``focal`` the focal length in pixels, so a disparity of 2 with a baseline of0.5 and a focal length of 100 gives a depth of 25.- - ``baseline`` and ``focal`` are each a python ``float`` or a tensor of shape :math:`(1,)`. A 0-dim- tensor -- what a reduction produces -- and a per-batch-element :math:`(B,)` tensor both raise- ``ShapeError``, and a python ``int`` is rejected by the type check, so one value is shared by the- whole batch.+ - ``baseline`` and ``focal`` are each a Python ``int`` or ``float``, a scalar tensor, or a tensor of+ shape :math:`(1,)`; one value is shared by the whole batch. Per-batch-element :math:`(B,)` tensors+ with :math:`B > 1` raise ``ShapeError``.- ``disparity`` is :math:`(*, H, W)` and the result has its shape. Its sign is not checked, so anegative disparity gives a negative depth.@@ -808,9 +807,8 @@ def depth_from_disparity(Args:disparity: Disparity tensor of shape :math:`(*, H, W)`.- baseline: a python ``float`` or a tensor of shape :math:`(1,)` containing the distance between the two- lenses.- focal: a python ``float`` or a tensor of shape :math:`(1,)` containing the focal length.+ baseline: Distance between the two lenses, as an int, float, or tensor of shape ``()`` or ``(1,)``.+ focal: Focal length, as an int, float, or tensor of shape ``()`` or ``(1,)``.Return:Depth map of the shape :math:`(*, H, W)`.@@ -826,18 +824,18 @@ def depth_from_disparity(KORNIA_CHECK_IS_TENSOR(disparity, f"Input disparity type is not a torch.Tensor. Got {type(disparity)}.")KORNIA_CHECK_SHAPE(disparity, ["*", "H", "W"])KORNIA_CHECK(- isinstance(baseline, (float, torch.Tensor)),- f"Input baseline should be either a float or torch.Tensor. Got {type(baseline)}",+ isinstance(baseline, (int, float, torch.Tensor)) and not isinstance(baseline, bool),+ f"Input baseline should be an int, float or torch.Tensor. Got {type(baseline)}",)KORNIA_CHECK(- isinstance(focal, (float, torch.Tensor)),- f"Input focal should be either a float or torch.Tensor. Got {type(focal)}",+ isinstance(focal, (int, float, torch.Tensor)) and not isinstance(focal, bool),+ f"Input focal should be an int, float or torch.Tensor. Got {type(focal)}",)- if isinstance(baseline, torch.Tensor):+ if isinstance(baseline, torch.Tensor) and baseline.ndim != 0:KORNIA_CHECK_SHAPE(baseline, ["1"])- if isinstance(focal, torch.Tensor):+ if isinstance(focal, torch.Tensor) and focal.ndim != 0:KORNIA_CHECK_SHAPE(focal, ["1"])return baseline * focal / (disparity + 1e-8)diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex 97f831a6e..956e0e09d 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -1048,6 +1048,43 @@ class TestDepthWarperConventions(BaseTester):class TestDepthFromDisparity(BaseTester):+ @pytest.mark.parametrize("baseline_kind", ["int", "float", "scalar_tensor", "tensor"])+ @pytest.mark.parametrize("focal_kind", ["int", "float", "scalar_tensor", "tensor"])+ @pytest.mark.parametrize("batched", [False, True])+ def test_scalar_camera_parameters_4272(self, baseline_kind, focal_kind, batched, device, dtype):+ def parameter(value, kind):+ if kind == "int":+ return int(value)+ if kind == "float":+ return float(value)+ return torch.tensor(value if kind == "scalar_tensor" else [value], device=device, dtype=dtype)++ disparity = torch.tensor([[1.0, 2.0, 4.0], [8.0, 16.0, 32.0]], device=device, dtype=dtype)+ expected = torch.tensor([[60.0, 30.0, 15.0], [7.5, 3.75, 1.875]], device=device, dtype=dtype)+ if batched:+ disparity = disparity.expand(2, 1, 2, 3)+ expected = expected.expand(2, 1, 2, 3)+ depth = kornia.geometry.depth.depth_from_disparity(+ disparity, parameter(2.0, baseline_kind), parameter(30.0, focal_kind)+ )+ assert depth.shape == disparity.shape+ assert depth.dtype == dtype+ assert depth.device == disparity.device+ self.assert_close(depth, expected)++ @pytest.mark.parametrize("parameter_name", ["baseline", "focal"])+ def test_scalar_camera_parameters_reject_invalid(self, parameter_name, device, dtype):+ disparity = torch.ones(2, 1, 3, 4, device=device, dtype=dtype)+ parameters = {"baseline": 1.0, "focal": 1.0}+ for shape in [(0,), (2,), (1, 1)]:+ parameters[parameter_name] = torch.ones(shape, device=device, dtype=dtype)+ with pytest.raises(ShapeError):+ kornia.geometry.depth.depth_from_disparity(disparity, **parameters)+ for value in ["1", 1j, True]:+ parameters[parameter_name] = value+ with pytest.raises(BaseError, match=f"Input {parameter_name}"):+ kornia.geometry.depth.depth_from_disparity(disparity, **parameters)+def test_smoke(self, device, dtype):disparity = 2 * torch.tensor([[[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]], device=device, dtype=dtype@@ -1092,13 +1129,14 @@ class TestDepthFromDisparity(BaseTester):points3d = kornia.geometry.depth.depth_from_disparity(disparity, baseline, focal)assert points3d.shape == shape- def test_gradcheck(self, device):+ @pytest.mark.parametrize("parameter_shape", [(), (1,)])+ def test_gradcheck(self, device, parameter_shape):# generate input datadisparity = torch.rand(1, 1, 3, 4, device=device, dtype=torch.float64)- baseline = torch.rand(1, device=device, dtype=torch.float64)+ baseline = torch.rand(parameter_shape, device=device, dtype=torch.float64)- focal = torch.rand(1, device=device, dtype=torch.float64)+ focal = torch.rand(parameter_shape, device=device, dtype=torch.float64)# evaluate function gradientself.gradcheck(kornia.geometry.depth.depth_from_disparity, (disparity, baseline, focal))@@ -1131,24 +1169,10 @@ class TestDepthFromDisparity(BaseTester):)def test_wart_depth_from_disparity_rejects_a_batched_baseline_4272(self, device, dtype):- # Wart pin for kornia#4272: the- # docstring says baseline and focal are "float/tensor", but the guard is KORNIA_CHECK_SHAPE(..., ["1"]),- # so a tensor argument must have exactly shape (1,). A 0-dim tensor -- what ``torch.tensor(0.5)`` or any- # reduction produces -- is rejected, and so is a per-batch-element (2,) baseline, even though the- # disparity itself is batched. A python ``int`` is rejected outright by the type check, for either- # argument -- so ``depth_from_disparity(d, 1, 100.0)`` fails while ``(d, 1.0, 100.0)`` works.- # Snippet used to generate expected: depth_from_disparity(ones(1, 1, 2, 3), baseline, focal) executed- # 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> ShapeError("Shape dimension mismatch: expected 1- # dimensions, got 0.") for the 0-dim baseline and ShapeError("Shape mismatch at dimension 0: expected 1,- # got 2.") for the (2,) baseline and the (2,) focal, on cpu for float32, float64, float16 and bfloat16- # and on mps for float32 and float16; a python int raises BaseError("Input baseline should be either a- # float or torch.Tensor. Got <class 'int'>") and the same sentence for ``focal`` in those cells, and- # the (1,) form returns shape (1, 1, 2, 3).- # Pins the CURRENT behavior; NOT a contract; delete when #4272 is repaired.+ # Per-batch calibration is still unsupported; scalar forms are covered by+ # test_scalar_camera_parameters_4272. Delete this wart pin when #4272 adds batching.disparity = torch.ones(1, 1, 2, 3, device=device, dtype=dtype)focal = torch.tensor([100.0], device=device, dtype=dtype)- with pytest.raises(ShapeError, match="expected 1 dimensions, got 0"):- depth_from_disparity(disparity, torch.tensor(0.5, device=device, dtype=dtype), focal)with pytest.raises(ShapeError, match="expected 1, got 2"):depth_from_disparity(disparity, torch.tensor([0.5, 0.5], device=device, dtype=dtype), focal)with pytest.raises(ShapeError, match="expected 1, got 2"):@@ -1157,10 +1181,6 @@ class TestDepthFromDisparity(BaseTester):torch.tensor([0.5], device=device, dtype=dtype),torch.tensor([100.0, 100.0], device=device, dtype=dtype),)- with pytest.raises(BaseError, match=r"Input baseline should be either a float or torch\.Tensor"):- depth_from_disparity(disparity, 1, 100.0)- with pytest.raises(BaseError, match=r"Input focal should be either a float or torch\.Tensor"):- depth_from_disparity(disparity, 0.5, 100)assert depth_from_disparity(disparity, 1.0, 100.0).shape == (1, 1, 2, 3)assert depth_from_disparity(disparity, torch.tensor([0.5], device=device, dtype=dtype), focal).shape == (1,