Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(stereo): stop reproject_disparity_to_3D transposing the pixel indices (closes #4269) (#4366)

Dipak Chaudharicfcd8cdce183
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 243c49365..eecae066a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -417,6 +417,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* `RandomThinPlateSpline(scale=0.0)` now generates zero control-point displacement instead of
raising an error when constructing a degenerate uniform distribution. (#4463)
+
+* `reproject_disparity_to_3D` (the `StereoCamera` method and the module-level function, which share
+ one body) no longer transposes the two pixel indices. The pixel meshgrid was unbound as
+ `v, u = torch.unbind(uv, dim=-1)`, but `create_meshgrid(normalized_coordinates=False)` returns
+ `(x, y)`, so the column fed `v` and the row fed `u`: `X` was computed from the row and `Y` from
+ the column. Every returned point was the value belonging to its transposed pixel -- kornia's
+ answer at `(row, col)` was what `cv2.reprojectImageTo3D` puts at `(col, row)`, the OpenCV
+ semantics this function was added to provide (#2042). A square rig with `fx == fy` and
+ `cx == cy` agrees only on the diagonal, so the error was silent rather than absent. Output
+ changes at every pixel with `row != col`, square inputs included. The real-data regression
+ fixture stored ten points as ten rows of one column while its own comment and its ground truth
+ describe one row of ten columns,
+ which is why it passed against the swapped code; it is now laid out as the comment says, and
+ the fixed code reproduces the unchanged ground-truth values. #4317's two wart pins for this defect
+ are retired and its strict-xfail convention test is now an ordinary passing regression. (#4269, #4366)
+
* `RandomRain` with `same_on_batch=True` now samples the same number of rain drops for all samples in the batch. (#4453)
* `RandomRain` now rejects drop heights equal to the image height and absolute drop widths equal to the image
width with the documented validation error, instead of allowing boundary-sized drops to reach an internal
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index b9176cdd7..5bbd08938 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -79,16 +79,8 @@ class StereoCamera:
- the pixels are the integer pixel centres that :func:`~kornia.geometry.grid.create_meshgrid`
enumerates, described in the Convention block on
:class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
-
- .. warning::
- :meth:`~kornia.geometry.camera.stereo.StereoCamera.reproject_disparity_to_3D` unbinds that pixel grid
- as ``v, u``, while :func:`~kornia.geometry.grid.create_meshgrid` returns it as ``(x, y)``, so ``X`` is
- computed from the **row** index and ``Y`` from the column index -- the opposite of
- ``cv2.reprojectImageTo3D``, whose semantics this function was added to provide. The repository's own
- real-data test passes only because its fixture lays a one-row, ten-column strip out as ten rows of one
- column, which the swap cancels; its stored numbers are correct OpenCV output for that strip, so a fix
- corrects the layout and keeps every literal. Tracked as
- `#4269 <https://github.com/kornia/kornia/issues/4269>`_.
+ - ``u`` is the **column** index and ``v`` the **row** index, as in ``cv2.reprojectImageTo3D``:
+ :math:`X = (u - c_x) Z / f_x` and :math:`Y = (v - c_y) Z / f_y`.
.. warning::
Several of the constructor guards do not enforce the contract above. A differing ``cx`` is
@@ -399,8 +391,13 @@ def reproject_disparity_to_3D(disparity_tensor: torch.Tensor, Q_matrix: torch.Te
uv = create_meshgrid(rows, cols, normalized_coordinates=False, device=device, dtype=dtype)
uv = uv.expand(batch_size, -1, -1, -1)
- v, u = torch.unbind(uv, dim=-1)
- v, u = torch.unsqueeze(v, -1), torch.unsqueeze(u, -1)
+ # create_meshgrid(normalized_coordinates=False) returns (x, y), so uv[..., 0] is the
+ # column and uv[..., 1] is the row. u is the column and v the row, as in
+ # cv2.reprojectImageTo3D, whose semantics this function provides (#2042). Unbinding
+ # them the other way round fed the row into u and the column into v, which transposed
+ # the two pixel indices in the result.
+ u, v = torch.unbind(uv, dim=-1)
+ u, v = torch.unsqueeze(u, -1), torch.unsqueeze(v, -1)
uvd = torch.stack((u, v, disparity_tensor), 1).reshape(batch_size, 3, -1).permute(0, 2, 1)
points = transform_points(Q_matrix, uvd).reshape(batch_size, rows, cols, 3)
diff --git a/tests/geometry/camera/test_stereo.py b/tests/geometry/camera/test_stereo.py
index abaae5526..34bf655b2 100644
--- a/tests/geometry/camera/test_stereo.py
+++ b/tests/geometry/camera/test_stereo.py
@@ -124,7 +124,11 @@ class _RealTestData(BaseTester):
],
device=device,
dtype=dtype,
- ).permute(0, 2, 3, 1)
+ )
+ # The literal is already (B, rows=1, cols=10, 1). It used to be permuted to
+ # (B, 10, 1, 1) -- ten rows of one column -- which contradicts the comment above
+ # and the ground truth below, and made this test pass only because the pixel
+ # indices were swapped inside reproject_disparity_to_3D (#4269).
return disp.expand(batch_size, -1, -1, -1)
@staticmethod
@@ -147,7 +151,8 @@ class _RealTestData(BaseTester):
],
device=device,
dtype=dtype,
- )
+ ).permute(0, 2, 1, 3)
+ # Same ten points, laid out as the one row of ten columns the comment describes.
return pc.expand(batch_size, -1, -1, -1)
@@ -295,6 +300,46 @@ class TestStereoCamera(BaseTester):
self.assert_close(xyz, xyz_gt)
+ def test_reproject_disparity_to_3D_uses_the_column_for_x(self, batch_size, device, dtype):
+ """X must come from the column and Y from the row, as in cv2.reprojectImageTo3D.
+
+ The meshgrid was unbound as ``v, u``, but create_meshgrid returns ``(x, y)``, so the
+ row fed X and the column fed Y: every pixel got the value belonging to its transpose.
+ A square rig with fx == fy and cx == cy hides it everywhere except off the diagonal,
+ so this uses an asymmetric 3x5 rig with cx != cy (#4269).
+ """
+ fx, fy, cx, cy, tx = 100.0, 100.0, 4.0, 3.0, 0.5
+ left = torch.zeros(batch_size, 3, 4, device=device, dtype=dtype)
+ left[:, 0, 0], left[:, 1, 1], left[:, 2, 2] = fx, fy, 1.0
+ left[:, 0, 2], left[:, 1, 2] = cx, cy
+ right = left.clone()
+ right[:, 0, 3] = -tx * fx
+ camera = StereoCamera(left, right)
+
+ rows, cols, disparity = 3, 5, 10.0
+ points = camera.reproject_disparity_to_3D(
+ torch.full((batch_size, rows, cols, 1), disparity, device=device, dtype=dtype)
+ )
+
+ depth = fx * tx / disparity
+ expected = torch.stack(
+ [
+ (torch.arange(cols, device=device, dtype=dtype) - cx).view(1, 1, cols).expand(1, rows, cols)
+ * depth
+ / fx,
+ (torch.arange(rows, device=device, dtype=dtype) - cy).view(1, rows, 1).expand(1, rows, cols)
+ * depth
+ / fy,
+ torch.full((1, rows, cols), depth, device=device, dtype=dtype),
+ ],
+ dim=-1,
+ ).expand(batch_size, -1, -1, -1)
+ self.assert_close(points, expected)
+
+ # The axis dependence, stated directly: X varies across a row, Y does not.
+ assert not torch.allclose(points[0, 0, :, 0], points[0, 0, :1, 0].expand(cols))
+ self.assert_close(points[0, 0, :, 1], points[0, 0, :1, 1].expand(cols))
+
def test_reproject_disparity_to_3D_simple(self, batch_size, device, dtype):
"""Test reprojecting of disparity to 3D for real data."""
height, width = _RealTestData().height, _RealTestData().width
@@ -419,98 +464,44 @@ class TestStereoCamera(BaseTester):
self.assert_close(points, expected)
self.assert_close(reproject_disparity_to_3D(disparity, -q), -expected)
- def test_wart_reproject_disparity_reads_u_from_the_row_index_4269(self, device, dtype):
- # Wart pin for kornia#4269: the pixel
- # meshgrid is unbound as ``v, u = torch.unbind(uv, dim=-1)``, but create_meshgrid returns (x, y), so
- # uv[..., 0] is the COLUMN and uv[..., 1] is the ROW. X is therefore computed from the row index and Y
- # from the column index -- the opposite of cv2.reprojectImageTo3D, which this function was added
- # (kornia#2042) to provide. What comes out is the OpenCV answer with the two pixel indices TRANSPOSED:
- # kornia's value at (row, col) is what cv2.reprojectImageTo3D puts at (col, row), i.e. exactly
- # X = (row - cx) Z / fx, Y = (col - cy) Z / fy with Z = fx * tx / d. The fy/fx swap in Q rows 0 and 1
- # compensates for the homogeneous divide, so X is still scaled by 1/fx and Y by 1/fy -- what moved is
- # only which INDEX feeds which coordinate. The transpose arm below runs on the fy = 50 camera, where
- # fx != fy, so a reading that swapped the focal lengths as well would not reproduce it.
- # The swap does NOT cancel on a square image with fx == fy and cx == cy: transposing the index pair is
- # a no-op only where row == col, so the diagonal agrees with OpenCV and everything else does not (the
- # square arm below measures a 0.2 gap on a 5 x 5 map, asserted as > 0.1).
- # Snippet used to generate expected: cam.reproject_disparity_to_3D(full((1, 3, 5, 1), 10.0)) executed
- # recorded in original commit 1a96bfd1 (torch 2.14.0, cpu float32) -> (row 0, col 2) [-0.2, -0.05, 5.0],
- # (row 1, col 0) [-0.15, -0.15, 5.0], (row 2, col 4) [-0.1, 0.05, 5.0]; the hand-computed OpenCV answers
- # for the same three pixels are [-0.1, -0.15, 5.0], [-0.2, -0.1, 5.0] and [0.0, -0.05, 5.0]. On the
- # fy = 50 camera the whole (1, 3, 5, 3) map equals the transposed OpenCV map to 0.0 (float32, float64,
- # bfloat16 on cpu and float32 on mps) and to 0.00390625 in float16 (cpu and mps), which is that dtype's
- # rounding of Z = 5. On the square fx = fy = 100, cx = cy = 3 camera the same map is 0.2 away from the
- # untransposed OpenCV map in every one of those cells, and its (2, 2) pixel is on the diagonal and
- # agrees. Every cell (cpu float32/float64/float16/bfloat16, mps float32/float16) reproduces this.
- # Pins the CURRENT value; NOT a contract; delete when #4269 is repaired.
+ def test_convention_reproject_disparity_uses_the_column_as_u_4269(self, device, dtype):
+ # The contract, repaired by #4269 and an ordinary passing regression since: u is the COLUMN index and
+ # v the ROW index, as in cv2.reprojectImageTo3D -- X = (u - cx) Z / fx, Y = (v - cy) Z / fy, with
+ # Z = fx * tx / d. On this fixture (fx = fy = 100, cx = 4, cy = 3, tx = 0.5, d = 10, so Z = 5) that is
+ # [-0.1, -0.15, 5] at (row 0, col 2), [-0.2, -0.1, 5] at (row 1, col 0) and [0.0, -0.05, 5] at
+ # (row 2, col 4). It was a strict xfail while the two indices were transposed.
cam = self._asymmetric_stereo(device, dtype)
points = cam.reproject_disparity_to_3D(torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype))
- self.assert_close(points[0, 0, 2], torch.tensor([-0.2, -0.05, 5.0], device=device, dtype=dtype))
- self.assert_close(points[0, 1, 0], torch.tensor([-0.15, -0.15, 5.0], device=device, dtype=dtype))
- self.assert_close(points[0, 2, 4], torch.tensor([-0.1, 0.05, 5.0], device=device, dtype=dtype))
- # the whole map, on a camera with fx = 100 != fy = 50: the OpenCV formula read at (u, v) = (row, col)
- transposed = self._asymmetric_stereo(device, dtype, fy=50.0).reproject_disparity_to_3D(
+ self.assert_close(points[0, 0, 2], torch.tensor([-0.1, -0.15, 5.0], device=device, dtype=dtype))
+ self.assert_close(points[0, 1, 0], torch.tensor([-0.2, -0.1, 5.0], device=device, dtype=dtype))
+ self.assert_close(points[0, 2, 4], torch.tensor([0.0, -0.05, 5.0], device=device, dtype=dtype))
+ # The whole map on a camera with fx = 100 != fy = 50, so a reading that swapped the focal lengths as
+ # well as the indices could not reproduce it. This arm is what the deleted wart pin asserted
+ # transposed.
+ points = self._asymmetric_stereo(device, dtype, fy=50.0).reproject_disparity_to_3D(
torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype)
)
rows = torch.arange(3.0, device=device, dtype=dtype).view(3, 1).expand(3, 5)
columns = torch.arange(5.0, device=device, dtype=dtype).view(1, 5).expand(3, 5)
depth = torch.full((3, 5), 5.0, device=device, dtype=dtype)
- self.assert_close(transposed, torch.stack([(rows - 4.0) * 0.05, (columns - 3.0) * 0.1, depth], dim=-1)[None])
- # fx == fy and cx == cy on a square map does not make it cancel: only the diagonal agrees with OpenCV
- square_left = torch.tensor(
- [[[100.0, 0.0, 3.0, 0.0], [0.0, 100.0, 3.0, 0.0], [0.0, 0.0, 1.0, 0.0]]], device=device, dtype=dtype
- )
- square_right = square_left.clone()
- square_right[0, 0, 3] = -50.0
- square = StereoCamera(square_left, square_right)
- square_points = square.reproject_disparity_to_3D(torch.full((1, 5, 5, 1), 10.0, device=device, dtype=dtype))
- square_rows = torch.arange(5.0, device=device, dtype=dtype).view(5, 1).expand(5, 5)
- square_columns = torch.arange(5.0, device=device, dtype=dtype).view(1, 5).expand(5, 5)
- square_depth = torch.full((5, 5), 5.0, device=device, dtype=dtype)
- opencv = torch.stack([(square_columns - 3.0) * 0.05, (square_rows - 3.0) * 0.05, square_depth], dim=-1)[None]
- self.assert_close(
- square_points,
- torch.stack([(square_rows - 3.0) * 0.05, (square_columns - 3.0) * 0.05, square_depth], dim=-1)[None],
- )
- assert (square_points - opencv).abs().max().item() > 0.1
- self.assert_close(square_points[0, 2, 2], opencv[0, 2, 2])
-
- @pytest.mark.xfail(strict=True, reason="kornia#4269: reproject_disparity_to_3D swaps u and v")
- def test_convention_reproject_disparity_uses_the_column_as_u_4269(self, device, dtype):
- # Intended contract, asserted as a strict xfail so the repair makes it XPASS and forces this mark out:
- # u is the COLUMN index and v the ROW index, as in cv2.reprojectImageTo3D --
- # X = (u - cx) Z / fx, Y = (v - cy) Z / fy, with Z = fx * tx / d. On this fixture (fx = fy = 100,
- # cx = 4, cy = 3, tx = 0.5, d = 10, so Z = 5) that is [-0.1, -0.15, 5] at (row 0, col 2),
- # [-0.2, -0.1, 5] at (row 1, col 0) and [0.0, -0.05, 5] at (row 2, col 4).
- # Settled by #4269's Expected section (unbind as ``u, v``); the fix is focused and welcome as a PR, and
- # it also has to re-lay _RealTestData's disparity and point cloud as (1, 1, 10, 1) / (1, 1, 10, 3): the
- # stored literals are correct OpenCV output for a one-row strip and stay as they are.
- cam = self._asymmetric_stereo(device, dtype)
- points = cam.reproject_disparity_to_3D(torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype))
- self.assert_close(points[0, 0, 2], torch.tensor([-0.1, -0.15, 5.0], device=device, dtype=dtype))
- self.assert_close(points[0, 1, 0], torch.tensor([-0.2, -0.1, 5.0], device=device, dtype=dtype))
- self.assert_close(points[0, 2, 4], torch.tensor([0.0, -0.05, 5.0], device=device, dtype=dtype))
-
- def test_wart_reproject_disparity_x_varies_with_the_row_and_y_with_the_column_4269(self, device, dtype):
- # Wart pin for kornia#4269: the axis-dependence form of the
- # same defect, independent of any single pixel's literal. On a constant disparity map, X must vary along
- # a row (it is a function of the column) and be constant down a column; kornia does the reverse -- X is
- # constant along row 0 and steps by 0.05 down column 0, while Y steps by 0.05 along row 0. This is the
- # reproduction that survives any change of fixture, because it asserts which INDEX each output
- # coordinate depends on rather than a value.
- # Snippet used to generate expected: slices of cam.reproject_disparity_to_3D(full((1, 3, 5, 1), 10.0))
- # recorded in original commit 1a96bfd1 (torch 2.14.0, cpu float32) -> X along row 0
- # [-0.2, -0.2, -0.2, -0.2, -0.2], X down column 0 [-0.2, -0.15, -0.1], Y along row 0
- # [-0.15, -0.1, -0.05, -0.0, 0.05]. Identical (up to the dtype rounding) in every cell: cpu float32,
- # float64, float16 and bfloat16, mps float32 and float16.
- # Pins the CURRENT value; NOT a contract; delete when #4269 is repaired.
+ opencv = torch.stack([(columns - 4.0) * 0.05, (rows - 3.0) * 0.1, depth], dim=-1)[None]
+ self.assert_close(points, opencv)
+
+ def test_convention_reproject_disparity_x_varies_with_the_column_4269(self, device, dtype):
+ # The axis-dependence form of the contract, and the one statement that survives any change of fixture
+ # because it asserts which INDEX each output coordinate depends on rather than a literal. On a constant
+ # disparity map X is a function of the column, so it varies along a row and is constant down a column;
+ # Y is the mirror image. This was a wart pin asserting the reverse while the indices were transposed.
cam = self._asymmetric_stereo(device, dtype)
points = cam.reproject_disparity_to_3D(torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype))
- x_along_row = points[0, 0, :, 0]
- assert bool((x_along_row == x_along_row[0]).all())
- self.assert_close(x_along_row, torch.full((5,), -0.2, device=device, dtype=dtype))
- self.assert_close(points[0, :, 0, 0], torch.tensor([-0.2, -0.15, -0.1], device=device, dtype=dtype))
- self.assert_close(points[0, 0, :, 1], torch.tensor([-0.15, -0.1, -0.05, 0.0, 0.05], device=device, dtype=dtype))
+ # X: steps by 0.05 along a row, constant down a column.
+ self.assert_close(points[0, 0, :, 0], torch.tensor([-0.2, -0.15, -0.1, -0.05, 0.0], device=device, dtype=dtype))
+ x_down_column = points[0, :, 0, 0]
+ assert bool((x_down_column == x_down_column[0]).all())
+ # Y: constant along a row, steps by 0.05 down a column.
+ y_along_row = points[0, 0, :, 1]
+ assert bool((y_along_row == y_along_row[0]).all())
+ self.assert_close(points[0, :, 0, 1], torch.tensor([-0.15, -0.1, -0.05], device=device, dtype=dtype))
def test_wart_stereo_rejects_differing_principal_points_4270(self, device, dtype):
# Wart pin for kornia#4270: the docs page says "cx may differ between