Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): reject a zero baseline and any swapped rig in StereoCamera (#4616)

abhijeet sharma65417f9cc666
diff --git a/changelog.d/4616.breaking.md b/changelog.d/4616.breaking.md
new file mode 100644
index 000000000..61d2c28af
--- /dev/null
+++ b/changelog.d/4616.breaking.md
@@ -0,0 +1,5 @@
+`StereoCamera` now rejects a rectified pair whose `tx * fx` is not strictly negative for every rig in the batch.
+Its sign guard used `torch.all`, so a batch holding one pair with its cameras swapped was accepted and silently
+reprojected that pair behind the camera, and a zero baseline passed too, collapsing `Q` so that every disparity
+reprojected to the origin. A zero baseline now raises with its own message naming `tx`; an empty batch is still
+accepted, and valid rigs build the same `Q` as before.
diff --git a/docs/source/geometry.camera.stereo.rst b/docs/source/geometry.camera.stereo.rst
index 03953ebb1..746350b44 100644
--- a/docs/source/geometry.camera.stereo.rst
+++ b/docs/source/geometry.camera.stereo.rst
@@ -125,7 +125,7 @@ where :math:`Q` is
0 & 0 & -fy & fy * (cx_{left} -cx_{right})
\end{bmatrix}
-The point cloud is obtained by a homogeneous transform by :math:`Q` followed by the division by :math:`W`. When :math:`|W| > 10^{-8}`, an overall sign on :math:`Q` cancels in that divide, so :math:`Q` and :math:`-Q` give the same points. When :math:`|W| \leq 10^{-8}`, Kornia's homogeneous conversion returns the numerator unchanged, so the two matrices give opposing values. :class:`StereoCamera` builds exactly the matrix above, with :math:`tx = P_1[0, 3] / fx` as :math:`P_1` defines it; its constructor rejects a rig only when that product is positive (a zero product and a batch with one positive product pass; tracked in #4270), so :math:`tx` here is negative on a rig it validates as intended. The class's ``tx`` attribute is the negation of this symbol, :math:`-P_1[0, 3] / fx`. Substituting the attribute's value for :math:`tx` above gives neither the class's :math:`Q` nor its negation, because the last row carries no :math:`tx` and does not flip.
+The point cloud is obtained by a homogeneous transform by :math:`Q` followed by the division by :math:`W`. When :math:`|W| > 10^{-8}`, an overall sign on :math:`Q` cancels in that divide, so :math:`Q` and :math:`-Q` give the same points. When :math:`|W| \leq 10^{-8}`, Kornia's homogeneous conversion returns the numerator unchanged, so the two matrices give opposing values. :class:`StereoCamera` builds exactly the matrix above, with :math:`tx = P_1[0, 3] / fx` as :math:`P_1` defines it; its constructor requires that product to be strictly negative for every rig in the batch, so :math:`tx` here is negative on every rig it accepts. The class's ``tx`` attribute is the negation of this symbol, :math:`-P_1[0, 3] / fx`. Substituting the attribute's value for :math:`tx` above gives neither the class's :math:`Q` nor its negation, because the last row carries no :math:`tx` and does not flip.
The :math:`Q[3, 3]` term carries :math:`fy * (cx_{left} - cx_{right})` for a setup whose principal points differ in :math:`cx`, but :class:`StereoCamera` rejects such a pair today: its constructor requires the two projection matrices to be equal outside the last column, so :math:`cx_{left} = cx_{right}` and that factor is zero. This is tracked in `#4270 <https://github.com/kornia/kornia/issues/4270>`_.
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index cd4a5ae60..d240537aa 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -67,10 +67,11 @@ class StereoCamera:
and the two matrices return opposing values. :attr:`Q` is exactly the matrix written out on the
:doc:`/geometry.camera.stereo` page, above this docstring, evaluated at the page's own ``tx``: the
page's :math:`P_1` carries ``fx * tx`` in its last column, so that ``tx`` is ``P_right[0, 3] / fx``,
- which the constructor rejects only when it is **positive** (``tx = 0`` and a batch with one positive
- product pass, see the second warning below). The :attr:`tx` attribute exposes the negation of that
- symbol, ``-P_right[0, 3] / fx``; substituting the attribute's value for the page's ``tx`` gives
- neither :attr:`Q` nor its negation, because the page's last row carries no ``tx`` and does not flip.
+ which the constructor requires to be strictly **negative** for every rig in the batch; a zero product
+ (a degenerate baseline) and a positive one (the cameras swapped) both raise. The :attr:`tx` attribute
+ exposes the negation of that symbol, ``-P_right[0, 3] / fx``; substituting the attribute's value for
+ the page's ``tx`` gives neither :attr:`Q` nor its negation, because the page's last row carries no
+ ``tx`` and does not flip.
- a disparity map is channels-**last**, :math:`(B, H, W, 1)`, for
:meth:`~kornia.geometry.camera.stereo.StereoCamera.reproject_disparity_to_3D` and for the module-level
:func:`~kornia.geometry.camera.stereo.reproject_disparity_to_3D` alike -- the :math:`(B, 1, H, W)`
@@ -86,18 +87,11 @@ class StereoCamera:
depth and integer pixel-centre conventions.
.. warning::
- Several of the constructor guards do not enforce the contract above. A differing ``cx`` is
- **rejected**, even though :attr:`cx_left` and :attr:`cx_right` are exposed separately and
- ``Q[3, 3]`` carries ``fy * (cx_left - cx_right)`` for exactly that case, so that factor is zero on
- any rig the constructor accepts. The ``tx * fx < 0`` guard is quantified with ``torch.all``, so a
- batch whose second element has the two cameras the wrong way round is accepted and reprojects that
- element 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. These guard issues are tracked as
- `#4270 <https://github.com/kornia/kornia/issues/4270>`_ and pinned by
- ``test_wart_stereo_rejects_differing_principal_points_4270``,
- ``test_wart_stereo_accepts_a_batch_with_one_positive_tx_fx_4270``,
- ``test_wart_stereo_tx_zero_collapses_every_point_to_the_origin_4270`` in
- ``tests/geometry/camera/test_stereo.py``.
+ A differing ``cx`` is **rejected**, even though :attr:`cx_left` and :attr:`cx_right` are exposed
+ separately and ``Q[3, 3]`` carries ``fy * (cx_left - cx_right)`` for exactly that case, so that factor
+ is zero on any rig the constructor accepts. Whether to admit a differing ``cx`` or to drop that claim is
+ tracked as `#4270 <https://github.com/kornia/kornia/issues/4270>`_ and pinned by
+ ``test_wart_stereo_rejects_differing_principal_points_4270`` in ``tests/geometry/camera/test_stereo.py``.
.. warning::
The module-level :func:`~kornia.geometry.camera.stereo.reproject_disparity_to_3D` is rendered on
@@ -189,10 +183,22 @@ class StereoCamera:
f"Got {rectified_left_camera[..., :, :3]} and {rectified_right_camera[..., :, :3]}."
)
- # Ensure that tx * fx is negative and exists.
+ # Reject every rig whose baseline is zero or points the wrong way. The right camera's last column is
+ # -tx * fx, so it must be strictly negative: zero means coincident cameras, which collapses Q and sends
+ # every disparity to the origin, and positive means the two cameras are swapped. The quantifier is
+ # ``any``, so one bad rig cannot hide behind good ones, and an empty batch stays vacuously valid. Neither
+ # comparison screens non-finite input: ``nan`` fails both of them and ``-inf`` is negative, so both are
+ # still accepted, exactly as they were before these checks were tightened.
+ # The check reads the data, which graph capture cannot do; skip it under export.
tx_fx = rectified_right_camera[..., 0, 3]
- 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}.")
+ if not is_exporting():
+ if torch.any(tx_fx == 0):
+ raise StereoException(
+ "Expected a non-zero stereo baseline, but :math:`T_x * f_x` is 0 for at least one camera pair, "
+ f"so `tx` is 0 and every disparity would reproject to the origin. Got {tx_fx}."
+ )
+ if torch.any(tx_fx > 0):
+ raise StereoException(f"Expected :math:`T_x * f_x` to be negative for every camera pair. Got {tx_fx}.")
@property
def batch_size(self) -> int:
diff --git a/tests/geometry/camera/test_stereo.py b/tests/geometry/camera/test_stereo.py
index 34bf655b2..b5ca6e91e 100644
--- a/tests/geometry/camera/test_stereo.py
+++ b/tests/geometry/camera/test_stereo.py
@@ -520,53 +520,47 @@ class TestStereoCamera(BaseTester):
assert torch.equal(cam.cx_left, cam.cx_right)
assert cam.Q[0, 3, 3].item() == 0.0
- def test_wart_stereo_accepts_a_batch_with_one_positive_tx_fx_4270(self, device, dtype):
- # Wart pin for kornia#4270: the sign guard is
- # ``torch.all(torch.gt(tx * fx, 0))``, which fires only when EVERY element of the batch is positive, so
- # a batch whose second element has the cameras the wrong way round is accepted and silently reprojects
- # that element behind the camera (its tx is -0.5). An all-positive batch is rejected, which is what
- # shows the guard exists and is simply quantified over the wrong side.
- # Snippet used to generate expected: StereoCamera(left, right) with right[0, 0, 3] = -50 and
- # right[1, 0, 3] = +50, recorded in original commit 1a96bfd1 (torch 2.14.0) -> accepted, tx =
- # [0.5, -0.5]; with both elements at +50 -> StereoException("Expected :math:`T_x * f_x` to be
- # negative."). Both hold on cpu for float32, float64, float16 and bfloat16 and on mps for float32 and
- # float16.
- # Pins the CURRENT behavior; NOT a contract; delete when #4270 is repaired.
+ @pytest.mark.parametrize("bad_index", [0, 1])
+ def test_convention_stereo_rejects_a_batch_with_one_positive_tx_fx_4270(self, bad_index, device, dtype):
+ # Convention pin for kornia#4270: the right camera's last column is -tx * fx, and the sign guard rejects a
+ # batch in which ANY rig has it positive, i.e. its two cameras swapped. Until the fix the guard was
+ # ``torch.all(torch.gt(tx * fx, 0))``, which fired only when EVERY element was positive, so a batch with one
+ # swapped rig was accepted and silently reprojected that rig behind the camera (its tx was -0.5). Both
+ # positions of the bad rig are covered, and the all-positive batch that was already rejected still is.
left = torch.tensor(
[[[100.0, 0.0, 4.0, 0.0], [0.0, 100.0, 3.0, 0.0], [0.0, 0.0, 1.0, 0.0]]] * 2, device=device, dtype=dtype
)
- mixed_right = torch.tensor(
- [
- [[100.0, 0.0, 4.0, -50.0], [0.0, 100.0, 3.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
- [[100.0, 0.0, 4.0, 50.0], [0.0, 100.0, 3.0, 0.0], [0.0, 0.0, 1.0, 0.0]],
- ],
- device=device,
- dtype=dtype,
+ right = torch.tensor(
+ [[[100.0, 0.0, 4.0, -50.0], [0.0, 100.0, 3.0, 0.0], [0.0, 0.0, 1.0, 0.0]]] * 2, device=device, dtype=dtype
)
- mixed = StereoCamera(left, mixed_right)
- self.assert_close(mixed.tx, torch.tensor([0.5, -0.5], device=device, dtype=dtype))
+ mixed_right = right.clone()
+ mixed_right[bad_index, 0, 3] = 50.0
+
+ with pytest.raises(StereoException, match="to be negative"):
+ StereoCamera(left, mixed_right)
with pytest.raises(StereoException, match="to be negative"):
self._asymmetric_stereo(device, dtype, tx_fx=50.0)
-
- def test_wart_stereo_tx_zero_collapses_every_point_to_the_origin_4270(self, device, dtype):
- # Wart pin for kornia#4270: tx * fx == 0 is not "greater than zero",
- # so a pair of coincident cameras passes the sign guard. The whole Q matrix then collapses to zeros
- # except Q[3, 2] = -fy, and every disparity -- including a large, perfectly valid one -- reprojects to
- # exactly the origin, with no warning and no inf to notice. A degenerate rig should be rejected by the
- # guard that already exists for the reversed one.
- # Snippet used to generate expected: StereoCamera(left, right) with the right camera's last column 0,
- # recorded in original commit 1a96bfd1 (torch 2.14.0) -> Q is zeros with Q[3, 2] = -100 (torch.equal
- # True) and the reprojection of a constant disparity 10 is exactly zeros (torch.equal True), on cpu for
- # float32, float64, float16 and bfloat16 and on mps for float32 and float16; the tx = 0.5 rig on the
- # same disparity reaches 5.0.
- # Pins the CURRENT behavior; NOT a contract; delete when #4270 is repaired.
- degenerate = self._asymmetric_stereo(device, dtype, tx_fx=0.0)
- expected_q = torch.zeros(1, 4, 4, device=device, dtype=dtype)
- expected_q[0, 3, 2] = -100.0
- self.assert_close(degenerate.Q, expected_q, atol=0.0, rtol=0.0)
+ # the all-negative batch is still accepted, with the baseline read back unchanged
+ self.assert_close(StereoCamera(left, right).tx, torch.tensor([0.5, 0.5], device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("zero", [0.0, -0.0])
+ def test_convention_stereo_rejects_a_zero_baseline_4270(self, zero, device, dtype):
+ # Convention pin for kornia#4270: tx * fx == 0 means coincident cameras, a rig with no baseline. It is not
+ # "greater than zero", so until the fix it passed the sign guard: Q collapsed to zeros except
+ # Q[3, 2] = -fy, and every disparity, including a large valid one, reprojected to exactly the origin with
+ # no warning and no inf to notice. It is now rejected with a message naming tx, both for a single rig and
+ # when one rig of a batch is degenerate. -0.0 is covered because it compares equal to 0.
+ with pytest.raises(StereoException, match="non-zero stereo baseline"):
+ self._asymmetric_stereo(device, dtype, tx_fx=zero)
+
+ good = self._asymmetric_stereo(device, dtype, batch=2)
+ right = good.rectified_right_camera.clone()
+ right[1, 0, 3] = zero
+ with pytest.raises(StereoException, match="non-zero stereo baseline"):
+ StereoCamera(good.rectified_left_camera, right)
+
+ # a real baseline on the same fixture still reprojects away from the origin
disparity = torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype)
- points = degenerate.reproject_disparity_to_3D(disparity)
- self.assert_close(points, torch.zeros(1, 3, 5, 3, device=device, dtype=dtype), atol=0.0, rtol=0.0)
assert self._asymmetric_stereo(device, dtype).reproject_disparity_to_3D(disparity).abs().max().item() > 0.1
def test_convention_stereo_rejects_a_four_by_four_pair_4270(self, device, dtype):