Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(geometry): accept per-batch camera parameters in depth_from_disparity (#4648)

abhijeet sharmaca72db02b267
diff --git a/changelog.d/4648.added.md b/changelog.d/4648.added.md
new file mode 100644
index 000000000..88a7b10ed
--- /dev/null
+++ b/changelog.d/4648.added.md
@@ -0,0 +1,5 @@
+`depth_from_disparity` accepts a per-batch-element `(B,)` `baseline` and `focal`, so a batch of stereo pairs from
+rigs with different baselines or focal lengths no longer has to be split and processed one sample at a time.
+Element `b` pairs with `disparity[b]`, which needs a disparity of rank 3 or more with a leading size of `B`; a
+mismatched size still raises `ShapeError`. The shared forms, a Python number, a scalar tensor or a `(1,)` tensor,
+behave exactly as before, and the two may be mixed.
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 6f1b5ea04..8ae281146 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -799,6 +799,23 @@ def depth_warp(
return warper(depth_src, patch_dst)
+def _per_sample_camera_parameter(parameter: float | torch.Tensor, disparity: torch.Tensor) -> float | torch.Tensor:
+ """Shape a per-batch-element ``(B,)`` camera parameter so each value meets its own disparity sample.
+
+ A Python number, a scalar tensor and a ``(1,)`` tensor already broadcast over the whole disparity and are
+ returned untouched, so every input accepted before ``(B,)`` support existed takes the same path as it did.
+ A ``(B,)`` tensor pairs element ``b`` with ``disparity[b]``, which needs a batch axis: ``disparity`` must
+ have rank 3 or more and a leading size of ``B``. Anything else raises ``ShapeError``.
+ """
+ if not isinstance(parameter, torch.Tensor) or parameter.ndim == 0 or parameter.shape == (1,):
+ return parameter
+ if parameter.ndim == 1 and disparity.ndim >= 3:
+ KORNIA_CHECK_SHAPE(parameter, [str(disparity.shape[0])])
+ return parameter.reshape(disparity.shape[0], *([1] * (disparity.ndim - 1)))
+ KORNIA_CHECK_SHAPE(parameter, ["1"])
+ return parameter
+
+
def depth_from_disparity(
disparity: torch.Tensor, baseline: float | torch.Tensor, focal: float | torch.Tensor
) -> torch.Tensor:
@@ -809,8 +826,11 @@ def depth_from_disparity(
two camera centres and ``focal`` the focal length in pixels, so a disparity of 2 with a baseline of
0.5 and a focal length of 100 gives a depth of 25.
- ``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``.
+ shape :math:`(1,)`, all of which share one value across the whole disparity; or a per-batch-element
+ tensor of shape :math:`(B,)`, which pairs element ``b`` with ``disparity[b]``. A :math:`(B,)` tensor
+ needs a batch axis, so ``disparity`` must be at least :math:`(B, H, W)` with a leading size of ``B``;
+ any other size raises ``ShapeError``. The two may mix, for example a per-sample ``baseline`` with
+ one shared ``focal``.
- ``disparity`` is :math:`(*, H, W)` and the result has its shape. Its sign is not checked, so a
negative disparity gives a negative depth.
@@ -825,8 +845,10 @@ def depth_from_disparity(
Args:
disparity: Disparity tensor of shape :math:`(*, H, W)`.
- 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,)``.
+ baseline: Distance between the two lenses, as an int, float, or tensor of shape ``()`` or ``(1,)``,
+ or of shape ``(B,)`` for one value per batch element.
+ focal: Focal length, as an int, float, or tensor of shape ``()`` or ``(1,)``, or of shape ``(B,)`` for
+ one value per batch element.
Return:
Depth map of the shape :math:`(*, H, W)`.
@@ -850,10 +872,7 @@ def depth_from_disparity(
f"Input focal should be an int, float or torch.Tensor. Got {type(focal)}",
)
- if isinstance(baseline, torch.Tensor) and baseline.ndim != 0:
- KORNIA_CHECK_SHAPE(baseline, ["1"])
-
- if isinstance(focal, torch.Tensor) and focal.ndim != 0:
- KORNIA_CHECK_SHAPE(focal, ["1"])
+ baseline = _per_sample_camera_parameter(baseline, disparity)
+ focal = _per_sample_camera_parameter(focal, disparity)
return baseline * focal / (disparity + 1e-8)
diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.py
index 25e38c23f..e3766af86 100644
--- a/tests/geometry/test_depth.py
+++ b/tests/geometry/test_depth.py
@@ -1083,7 +1083,9 @@ class TestDepthFromDisparity(BaseTester):
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)]:
+ # (2,) would be a valid per-batch-element parameter for this batch-2 disparity, so the mismatched
+ # sizes are 0 and 3; (1, 1) has the wrong rank for either form.
+ for shape in [(0,), (3,), (1, 1)]:
parameters[parameter_name] = torch.ones(shape, device=device, dtype=dtype)
with pytest.raises(ShapeError):
kornia.geometry.depth.depth_from_disparity(disparity, **parameters)
@@ -1136,10 +1138,10 @@ class TestDepthFromDisparity(BaseTester):
points3d = kornia.geometry.depth.depth_from_disparity(disparity, baseline, focal)
assert points3d.shape == shape
- @pytest.mark.parametrize("parameter_shape", [(), (1,)])
+ @pytest.mark.parametrize("parameter_shape", [(), (1,), (2,)])
def test_gradcheck(self, device, parameter_shape):
- # generate input data
- disparity = torch.rand(1, 1, 3, 4, device=device, dtype=torch.float64)
+ # generate input data; a batch of 2 so the (2,) case is a per-batch-element parameter
+ disparity = torch.rand(2, 1, 3, 4, device=device, dtype=torch.float64)
baseline = torch.rand(parameter_shape, device=device, dtype=torch.float64)
@@ -1175,26 +1177,64 @@ class TestDepthFromDisparity(BaseTester):
torch.full((1, 1, 1, 1), 25.0, device=device, dtype=dtype),
)
- def test_wart_depth_from_disparity_rejects_a_batched_baseline_4272(self, device, dtype):
- # 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, 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"):
- depth_from_disparity(
- disparity,
- torch.tensor([0.5], device=device, dtype=dtype),
- torch.tensor([100.0, 100.0], device=device, dtype=dtype),
- )
- 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,
+ @pytest.mark.parametrize("disparity_shape", [(2, 1, 2, 3), (2, 2, 3)])
+ @pytest.mark.parametrize("per_batch", ["baseline", "focal", "both"])
+ def test_convention_per_batch_camera_parameters_4272(self, disparity_shape, per_batch, device, dtype):
+ # Convention pin for kornia#4272: a (B,) baseline or focal pairs element b with disparity[b]. Until this
+ # landed only a shared value was accepted, and a (B,) tensor raised ShapeError. The expected result is
+ # built from the path that already worked, one sample at a time with (1,) parameters, so this asserts
+ # the pairing itself rather than a literal. The two samples use different camera values so a swapped or
+ # shared pairing gives different numbers; both a (B, 1, H, W) and a (B, H, W) disparity are covered.
+ disparity = torch.arange(1.0, 13.0, device=device, dtype=dtype).reshape(disparity_shape)
+ baselines = torch.tensor([0.5, 2.0], device=device, dtype=dtype)
+ focals = torch.tensor([100.0, 30.0], device=device, dtype=dtype)
+ shared_baseline = torch.tensor([0.5], device=device, dtype=dtype)
+ shared_focal = torch.tensor([100.0], device=device, dtype=dtype)
+
+ baseline = baselines if per_batch in ("baseline", "both") else shared_baseline
+ focal = focals if per_batch in ("focal", "both") else shared_focal
+ depth = depth_from_disparity(disparity, baseline, focal)
+
+ per_sample = torch.cat(
+ [
+ depth_from_disparity(
+ disparity[b : b + 1],
+ baselines[b : b + 1] if per_batch in ("baseline", "both") else shared_baseline,
+ focals[b : b + 1] if per_batch in ("focal", "both") else shared_focal,
+ )
+ for b in range(2)
+ ]
+ )
+ assert depth.shape == disparity.shape
+ self.assert_close(depth, per_sample, atol=0.0, rtol=0.0)
+ # the two samples use different camera values, so a swapped pairing gives different numbers and the
+ # comparison above genuinely discriminates the pairing (flip is a no-op on the shared (1,) parameter)
+ swapped = depth_from_disparity(disparity, baseline.flip(0), focal.flip(0))
+ assert not torch.allclose(depth, swapped)
+
+ def test_convention_per_batch_camera_parameters_must_match_the_batch_4272(self, device, dtype):
+ # A (B,) parameter is only meaningful against a batch of the same size. A mismatched size raises, and so
+ # does a (B,) parameter for a disparity with no batch axis, where it would otherwise broadcast against
+ # the width instead. The size-1 and scalar forms are unaffected, and an empty batch stays empty.
+ disparity = torch.ones(2, 1, 2, 3, device=device, dtype=dtype)
+ three = torch.ones(3, device=device, dtype=dtype)
+ with pytest.raises(ShapeError, match="expected 2, got 3"):
+ depth_from_disparity(disparity, three, 100.0)
+ with pytest.raises(ShapeError, match="expected 2, got 3"):
+ depth_from_disparity(disparity, 0.5, three)
+ with pytest.raises(ShapeError, match="expected 1, got 3"):
+ depth_from_disparity(torch.ones(2, 3, device=device, dtype=dtype), three, 100.0)
+
+ assert depth_from_disparity(disparity, 1.0, 100.0).shape == (2, 1, 2, 3)
+ assert depth_from_disparity(disparity, torch.tensor([0.5], device=device, dtype=dtype), 100.0).shape == (
+ 2,
1,
2,
3,
)
+ empty = torch.ones(0, 1, 2, 3, device=device, dtype=dtype)
+ nothing = torch.ones(0, device=device, dtype=dtype)
+ assert depth_from_disparity(empty, nothing, nothing).shape == (0, 1, 2, 3)
class TestDepthFromPlaneEquation(BaseTester):