Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix stereo reprojection for integer camera inputs (#6486)

Pratham Pansare951d20e3dba8
diff --git a/changelog.d/6486.fixed.md b/changelog.d/6486.fixed.md
new file mode 100644
index 000000000..230978029
--- /dev/null
+++ b/changelog.d/6486.fixed.md
@@ -0,0 +1,4 @@
+`StereoCamera` built from integer projection matrices now has a floating-point `Q`, in the default dtype, so
+`reproject_disparity_to_3D` works on it. Before, `Q` had the integer dtype of the cameras, with truncated (and in
+`int8`/`int16` overflowed) entries, and every reprojection raised `StereoException`. The `int8` baseline `tx` at a
+right-camera translation of `-128` now has the right sign. Floating-point rigs are unchanged.
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index 24d927226..4cadca32d 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -256,11 +256,16 @@ class StereoCamera:
def tx(self) -> torch.Tensor:
r"""The horizontal baseline between the two cameras.
+ Integer translations are promoted to the default floating-point dtype before negation.
+
Returns:
torch.Tensor of shape ``(B)``
"""
- return -self.rectified_right_camera[..., 0, 3] / self.fx
+ translation = self.rectified_right_camera[..., 0, 3]
+ if not translation.is_floating_point():
+ translation = translation.to(torch.get_default_dtype())
+ return -translation / self.fx
@property
def Q(self) -> torch.Tensor:
@@ -270,6 +275,9 @@ class StereoCamera:
the corresponding point cloud. Note that this is in a general form that allows different focal
lengths in the x and y direction.
+ Integer camera matrices use the default floating-point dtype for Q; floating-point cameras
+ retain their dtype. The stored camera matrices and intrinsic parameter properties are unchanged.
+
Return:
The Q matrix of shape ``(B, 4, 4)``.
@@ -283,15 +291,20 @@ class StereoCamera:
The Q matrix of shape ``(B, 4, 4)``.
"""
- Q = torch.zeros((self.batch_size, 4, 4), device=self.device, dtype=self.dtype)
+ floating_camera = self.rectified_left_camera.is_floating_point()
+ dtype = self.dtype if floating_camera else torch.get_default_dtype()
+ # Promote before products and negation, which can overflow for narrow integer cameras.
+ fx, fy = self.fx.to(dtype), self.fy.to(dtype)
+ cx_left, cx_right, cy = self.cx_left.to(dtype), self.cx_right.to(dtype), self.cy.to(dtype)
baseline: torch.Tensor = -self.tx
- Q[:, 0, 0] = self.fy * baseline
- Q[:, 0, 3] = -self.fy * self.cx_left * baseline
- Q[:, 1, 1] = self.fx * baseline
- Q[:, 1, 3] = -self.fx * self.cy * baseline
- Q[:, 2, 3] = self.fx * self.fy * baseline
- Q[:, 3, 2] = -self.fy
- Q[:, 3, 3] = self.fy * (self.cx_left - self.cx_right) # NOTE: This is usually zero.
+ Q = torch.zeros((self.batch_size, 4, 4), device=self.device, dtype=dtype)
+ Q[:, 0, 0] = fy * baseline
+ Q[:, 0, 3] = -fy * cx_left * baseline
+ Q[:, 1, 1] = fx * baseline
+ Q[:, 1, 3] = -fx * cy * baseline
+ Q[:, 2, 3] = fx * fy * baseline
+ Q[:, 3, 2] = -fy
+ Q[:, 3, 3] = fy * (cx_left - cx_right) # NOTE: This is usually zero.
return Q
@overload
diff --git a/tests/geometry/camera/test_stereo.py b/tests/geometry/camera/test_stereo.py
index 4fb318e74..397acd30c 100644
--- a/tests/geometry/camera/test_stereo.py
+++ b/tests/geometry/camera/test_stereo.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+from collections.abc import Callable
+
import pytest
import torch
@@ -191,6 +193,133 @@ class _SmokeTestData:
class TestStereoCamera(BaseTester):
"""Test class for :class:`~kornia.geometry.camera.stereo.StereoCamera`"""
+ @pytest.mark.parametrize(
+ "camera_dtype,fx,fy,translation",
+ [
+ (torch.int8, 100, 120, -50),
+ (torch.int8, 100, 120, -128),
+ (torch.int16, 500, 600, -50),
+ (torch.int32, 500, 600, -50),
+ (torch.int64, 100, 120, -50),
+ ],
+ )
+ @pytest.mark.parametrize("batch_size", [0, 1, 2])
+ def test_integer_camera_reprojection_6471(
+ self,
+ device: torch.device,
+ dtype: torch.dtype,
+ camera_dtype: torch.dtype,
+ fx: int,
+ fy: int,
+ translation: int,
+ batch_size: int,
+ ) -> None:
+ """Check integer rigs against pinhole geometry without overflowing camera arithmetic."""
+ left = torch.tensor([[[fx, 0, 3, 0], [0, fy, 2, 0], [0, 0, 1, 0]]], device=device, dtype=camera_dtype).expand(
+ batch_size, -1, -1
+ )
+ right = left.clone()
+ right[:, 0, 3] = translation
+ original_left, original_right = left.clone(), right.clone()
+ camera = StereoCamera(left, right)
+ reference = StereoCamera(left.to(torch.get_default_dtype()), right.to(torch.get_default_dtype()))
+
+ assert camera.rectified_left_camera is left
+ assert camera.rectified_right_camera is right
+ assert camera.dtype == camera_dtype
+ assert camera.device == device
+ assert torch.equal(left, original_left)
+ assert torch.equal(right, original_right)
+ for name, expected in (
+ ("fx", left[:, 0, 0]),
+ ("fy", left[:, 1, 1]),
+ ("cx_left", left[:, 0, 2]),
+ ("cx_right", right[:, 0, 2]),
+ ("cy", left[:, 1, 2]),
+ ("tx", torch.full((batch_size,), -translation / fx, device=device, dtype=torch.get_default_dtype())),
+ ):
+ self.assert_close(getattr(camera, name), expected)
+ assert camera.Q.dtype == torch.get_default_dtype()
+ assert camera.Q.device == device
+ assert camera.Q.shape == (batch_size, 4, 4)
+ self.assert_close(camera.Q, reference.Q)
+
+ disparity = torch.arange(1, 7, device=device, dtype=dtype).reshape(1, 2, 3, 1).expand(batch_size, -1, -1, -1)
+ points, valid = camera.reproject_disparity_to_3D(disparity, return_mask=True)
+ # Pinhole geometry: Z = -P_right[0, 3] / d, X = (u-cx) Z/fx, Y = (v-cy) Z/fy.
+ depth = -translation / disparity[..., 0]
+ u = torch.arange(3, device=device, dtype=dtype).reshape(1, 1, 3)
+ v = torch.arange(2, device=device, dtype=dtype).reshape(1, 2, 1)
+ expected = torch.stack(((u - 3) * depth / fx, (v - 2) * depth / fy, depth), dim=-1)
+ assert points.shape == (batch_size, 2, 3, 3)
+ assert points.dtype == dtype
+ assert points.device == device
+ self.assert_close(points, expected)
+ assert torch.equal(points, camera.reproject_disparity_to_3D(disparity))
+ assert valid.shape == disparity.shape
+ assert valid.dtype == torch.bool
+ assert valid.device == device
+ assert valid.all()
+ _, zero_valid = camera.reproject_disparity_to_3D(torch.zeros_like(disparity), return_mask=True)
+ assert not zero_valid.any()
+
+ @pytest.mark.parametrize("default_dtype", [torch.float32, torch.float64])
+ def test_integer_camera_default_dtype_6471(self, device: torch.device, default_dtype: torch.dtype) -> None:
+ """Check integer Q and baseline promotion under each supported default precision."""
+ if device.type == "mps" and default_dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ previous_dtype = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(default_dtype)
+ camera = self._asymmetric_stereo(device, torch.int64)
+ reference = self._asymmetric_stereo(device, default_dtype)
+ assert camera.Q.dtype == default_dtype
+ assert camera.tx.dtype == default_dtype
+ self.assert_close(camera.tx, reference.tx)
+ assert torch.get_default_dtype() == default_dtype
+ self.assert_close(camera.Q, reference.Q)
+ finally:
+ torch.set_default_dtype(previous_dtype)
+
+ @pytest.mark.parametrize("output", ["Q", "tx", "points"])
+ def test_camera_gradcheck(self, device: torch.device, output: str) -> None:
+ """Check floating camera gradients through Q, baseline and disparity reprojection."""
+ camera = self._asymmetric_stereo(device, torch.float64)
+ disparity = torch.full((1, 2, 3, 1), 10.0, device=device, dtype=torch.float64)
+
+ def op(left: torch.Tensor, translation: torch.Tensor, disparity: torch.Tensor) -> torch.Tensor:
+ """Rebuild the rig so camera parameters remain differentiable inputs."""
+ right = left.clone()
+ right[:, 0, 3] = translation
+ rig = StereoCamera(left, right)
+ if output == "tx":
+ return rig.tx
+ return rig.Q if output == "Q" else rig.reproject_disparity_to_3D(disparity)
+
+ self.gradcheck(op, (camera.rectified_left_camera, camera.rectified_right_camera[:, 0, 3], disparity))
+
+ @pytest.mark.parametrize("camera_dtype", [torch.int8, torch.int64])
+ def test_dynamo_integer_camera_6471(
+ self,
+ device: torch.device,
+ dtype: torch.dtype,
+ torch_optimizer: Callable[..., Callable[..., torch.Tensor]],
+ optimizer_backend: str | None,
+ camera_dtype: torch.dtype,
+ ) -> None:
+ """Require fullgraph compilation of integer-camera construction and reprojection."""
+ if not optimizer_backend or optimizer_backend == "jit":
+ pytest.skip("Integer-camera fullgraph capture requires torch.compile")
+ camera = self._asymmetric_stereo(device, camera_dtype, tx_fx=-128)
+ disparity = torch.full((1, 2, 3, 1), 10.0, device=device, dtype=dtype)
+
+ def op(left: torch.Tensor, right: torch.Tensor, disparity: torch.Tensor) -> torch.Tensor:
+ """Capture construction and reprojection together in the compiled graph."""
+ return StereoCamera(left, right).reproject_disparity_to_3D(disparity)
+
+ inputs = (camera.rectified_left_camera, camera.rectified_right_camera, disparity)
+ self.assert_close(torch_optimizer(op, fullgraph=True)(*inputs), op(*inputs))
+
@pytest.mark.parametrize("camera_index", [0, 1])
@pytest.mark.parametrize("shape", [(3, 3), (4, 4), (3, 5)])
def test_exception_invalid_camera_shape(self, batch_size, device, dtype, camera_index, shape):
@@ -423,6 +552,8 @@ class TestStereoCamera(BaseTester):
# row that scales the first output coordinate carries fy, so the fy = 50 arm fails a reading with fx
# there. Q[3, 3] = fy * (cx_left - cx_right) is always 0 (#4270, below).
cam = self._asymmetric_stereo(device, dtype)
+ assert cam.Q.dtype == dtype
+ assert cam.Q.device == device
self.assert_close(cam.tx, torch.tensor([0.5], device=device, dtype=dtype))
self.assert_close(cam.tx, -cam.rectified_right_camera[..., 0, 3] / cam.fx)
symmetric_q = torch.tensor(