π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): accept a differing cx in StereoCamera, as OpenCV's stereoRectify produces (#6558)
Prateekshit Jaiswal6609c750e44f
diff --git a/changelog.d/6558.fixed.md b/changelog.d/6558.fixed.mdnew file mode 100644index 000000000..74729e5df--- /dev/null+++ b/changelog.d/6558.fixed.md@@ -0,0 +1 @@+`StereoCamera` accepts a rectified pair whose `cx` differs between the two cameras, which is what OpenCV's `stereoRectify` produces without `CALIB_ZERO_DISPARITY`. `Q[3, 3] = fy * (cx_left - cx_right)` is then non-zero, and the reprojection matches OpenCV's. In 0.9.0 such a pair raised a `StereoException` about mismatched parameters. A differing `fx`, `fy` or `cy` still raises, now with a message naming what must match.diff --git a/docs/source/geometry.camera.stereo.rst b/docs/source/geometry.camera.stereo.rstindex d06052410..1659c8119 100644--- a/docs/source/geometry.camera.stereo.rst+++ b/docs/source/geometry.camera.stereo.rst@@ -20,7 +20,7 @@ The *left rectified camera matrix*:.. math::P_0 = \begin{bmatrix}- fx & 0 & cx & 0 \\+ fx & 0 & cx_{left} & 0 \\0 & fy & cy & 0 \\0 & 0 & 1 & 0\end{bmatrix}@@ -29,7 +29,7 @@ The *right rectified camera matrix*:.. math::P_1 = \begin{bmatrix}- fx & 0 & cx & tx * fx \\+ fx & 0 & cx_{right} & tx * fx \\0 & fy & cy & 0 \\0 & 0 & 1 & 0\end{bmatrix}@@ -37,7 +37,7 @@ The *right rectified camera matrix*:where:* :math:`fx` is the focal length in the x-direction in pixels.* :math:`fy` is the focal length in the y-direction in pixels.- * :math:`cx` is the x-coordinate of the principal point in pixels.+ * :math:`cx_{left}` and :math:`cx_{right}` are the x-coordinates of the left and right principal points in pixels.* :math:`cy` is the y-coordinate of the principal point in pixels.* :math:`tx` is the horizontal baseline in metric units.@@ -108,7 +108,7 @@ Subtracting the first row from the third and inverting the expression gives:1\end{bmatrix} =\begin{bmatrix}- fy * tx & 0 & 0 & -fy * cx * tx \\+ fy * tx & 0 & 0 & -fy * cx_{left} * tx \\0 & fx * tx & 0 & -fx * cy * tx \\0 & 0 & 0 & fx * fy * tx \\0 & 0 & -fy & fy * (cx_{left} -cx_{right})@@ -125,7 +125,7 @@ where :math:`Q` is.. math::Q = \begin{bmatrix}- fy * tx & 0 & 0 & -fy * cx * tx \\+ fy * tx & 0 & 0 & -fy * cx_{left} * tx \\0 & fx * tx & 0 & -fx * cy * tx \\0 & 0 & 0 & fx * fy * tx \\0 & 0 & -fy & fy * (cx_{left} -cx_{right})@@ -133,13 +133,13 @@ where :math:`Q` isThe :math:`Q` that :class:`StereoCamera` builds is exactly this matrix with :math:`tx = P_1[0, 3] / fx`, which the constructor requires to be strictly negative (a zero baseline or swapped cameras raise). The class's ``tx`` attribute is the positive baseline :math:`-P_1[0, 3] / fx`, so do not substitute it for :math:`tx` above.-The :math:`Q[3, 3]` term is zero on every rig :class:`StereoCamera` accepts outside graph capture (``torch.compile``, ``torch.export``): the constructor rejects differing :math:`cx_{left}` and :math:`cx_{right}` (`#4270 <https://github.com/kornia/kornia/issues/4270>`_).+Rigs with differing :math:`cx_{left}` and :math:`cx_{right}` are accepted, and :math:`Q[3, 3] = fy * (cx_{left} - cx_{right})` is then non-zero, as in OpenCV's :math:`Q` for ``stereoRectify`` without ``CALIB_ZERO_DISPARITY``.Assuming :math:`fx = fy` you can further reduce this to:.. math::Q = \begin{bmatrix}- 1 & 0 & 0 & -cx \\+ 1 & 0 & 0 & -cx_{left} \\0 & 1 & 0 & -cy \\0 & 0 & 0 & fx \\0 & 0 & -1/tx & (cx_{left} - cx_{right}) / txdiff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.pyindex 6a7a380bc..804daf42c 100644--- a/kornia/geometry/camera/stereo.py+++ b/kornia/geometry/camera/stereo.py@@ -91,26 +91,28 @@ class StereoCamera:the right camera, such as ``P1`` and ``P2`` of ``cv2.stereoRectify``, and``points = stereo.reproject_disparity_to_3D(disparity)`` takes a channels-last ``(B, H, W, 1)`` disparity map``d = u_left - u_right``, in pixels, and returns the 3D point of every pixel in the left rectified camera- frame, ``(B, H, W, 3)``, in the units of the baseline: ``Z = fx * tx / d``. Where the homogeneous denominator- ``W`` satisfies ``abs(W) > 1e-8`` the result matches ``cv2.reprojectImageTo3D`` with OpenCV's ``Q``; elsewhere- a placeholder is returned. ``W = -fy * d`` on every rig the constructor accepts outside graph capture, so there- a disparity with ``abs(fy * d) <= 1e-8``, zero included, gets the placeholder (see the warning below). With a- ``Q`` matrix from elsewhere, call :func:`reproject_disparity_to_3D` instead; for a depth map rather than points,+ frame, ``(B, H, W, 3)``, in the units of the baseline: ``Z = fx * tx / (d - (cx_left - cx_right))``. Where the+ homogeneous denominator ``W`` satisfies ``abs(W) > 1e-8`` the result matches ``cv2.reprojectImageTo3D`` with+ OpenCV's ``Q``; elsewhere a placeholder is returned. ``W = -fy * (d - (cx_left - cx_right))``, which is+ ``-fy * d`` on a rig with equal ``cx``, so there a disparity with ``abs(fy * d) <= 1e-8``, zero included, gets+ the placeholder (see the warning below). With a ``Q`` matrix from elsewhere, call+ :func:`reproject_disparity_to_3D` instead; for a depth map rather than points,:func:`~kornia.geometry.depth.depth_from_disparity`.Convention:- the two arguments are the **rectified projection matrices** of the left and the right camera, each of- shape ``(B, 3, 4)``: ``[[fx, 0, cx, 0], [0, fy, cy, 0], [0, 0, 1, 0]]`` for the left camera, and- the same matrix with ``-tx * fx`` in the last column for the right one. The constructor requires the- two to be equal outside that last column.+ shape ``(B, 3, 4)``: ``[[fx, 0, cx_left, 0], [0, fy, cy, 0], [0, 0, 1, 0]]`` for the left camera and+ ``[[fx, 0, cx_right, -tx * fx], [0, fy, cy, 0], [0, 0, 1, 0]]`` for the right one. The constructor+ requires the same ``fx``, ``fy`` and ``cy``; ``cx`` may differ.- the baseline is read back as the attribute :attr:`tx` ``= -P_right[0, 3] / fx``, which must bestrictly **positive** for every rig in the batch: a zero baseline and swapped cameras both raise. A- non-finite ``P_right[0, 3]`` is not screened, and these checks and the equal-intrinsics check are+ non-finite ``P_right[0, 3]`` is not screened, and these checks and the intrinsics check areskipped under graph capture (``torch.compile``, ``torch.export``).The :doc:`/geometry.camera.stereo` page's symbol ``tx`` is the negation of this attribute; :attr:`Q`is the page's matrix evaluated at the page's ``tx``.- - ``Q[0, 0]`` carries ``fy`` and ``Q[1, 1]`` carries ``fx``; with the divide by ``W = -fy * disparity``- the result is ``X = (u - cx) Z / fx``, ``Y = (v - cy) Z / fy``, ``Z = fx * tx / disparity``.+ - ``Q[0, 0]`` carries ``fy`` and ``Q[1, 1]`` carries ``fx``; with the divide by+ ``W = -fy * (disparity - (cx_left - cx_right))`` the result is ``X = (u - cx_left) Z / fx``,+ ``Y = (v - cy) Z / fy``, ``Z = fx * tx / (disparity - (cx_left - cx_right))``.- ``u`` is the **column** index and ``v`` the **row** index, as in ``cv2.reprojectImageTo3D``.- a disparity map is channels-**last**, ``(B, H, W, 1)`` (a ``(B, 1, H, W)`` map is rejected),and the point cloud is ``(B, H, W, 3)``. On a rig with equal ``cx``, where ``abs(fy * d) > 1e-8``, a@@ -120,18 +122,15 @@ class StereoCamera:- pixel centres are integers; see the Convention block on:class:`~kornia.geometry.camera.pinhole.PinholeCamera`.- the constructor raises :class:`StereoException` for a matrix that is not ``(B, 3, 4)``, for matrices on- different devices or with different dtypes and, outside graph capture, for different intrinsics or a- zero or reversed baseline. Left and right matrices with different batch sizes raise a plain+ different devices or with different dtypes and, outside graph capture, for a different ``fx``, ``fy`` or+ ``cy`` or a zero or reversed baseline. Left and right matrices with different batch sizes raise a plain:class:`RuntimeError` instead, except a right batch of 1, which is paired with every left matrix. Themethod raises :class:`StereoException` for a disparity map that is not a floating ``(B, H, W, 1)``tensor. An integer rig is accepted; its ``Q`` is in the default floating dtype... warning::- A differing ``cx`` is **rejected**, although ``Q[3, 3] = fy * (cx_left - cx_right)`` exists for that- case, so it is zero on every rig the constructor accepts outside graph capture:- `#4270 <https://github.com/kornia/kornia/issues/4270>`_. Under graph capture the check is skipped and- ``W = Q[3, 3] - fy * d``, so a nonzero disparity with ``fy * d = Q[3, 3]`` also makes ``W = 0``. On a- rig with equal ``cx``, a zero disparity (a point at infinity) makes ``W = -fy * d = 0``. Wherever+ ``W = Q[3, 3] - fy * d`` with ``Q[3, 3] = fy * (cx_left - cx_right)``, so ``W = 0`` where the disparity+ equals ``cx_left - cx_right``: a point at infinity, which is ``d = 0`` on a rig with equal ``cx``. Wherever``abs(W) <= 1e-8``, which includes small nonzero disparities such as ``d = 1e-9`` at ``fy = 1``, the divideis skipped and a finite placeholder, behind the camera on a real rig, is returned, so ``d > 0`` alone doesnot select points in front of the rig. Request@@ -146,10 +145,11 @@ class StereoCamera:- :func:`reproject_disparity_to_3D`: the same reprojection from a ``Q`` matrix instead of the twoprojection matrices.- :func:`~kornia.geometry.depth.depth_from_disparity`: a depth map, ``fx * tx / d`` at every pixel,- instead of points.+ instead of points. It equals ``Z`` on a rig with equal ``cx``; otherwise pass+ ``d - (cx_left - cx_right)`` as the disparity.- :func:`~kornia.geometry.depth.depth_to_3d_v2`: points from a depth map; after- :func:`~kornia.geometry.depth.depth_from_disparity`, the same points up to the ``1e-8`` that function- adds to the disparity.+ :func:`~kornia.geometry.depth.depth_from_disparity` of that same disparity, the same points up to the+ ``1e-8`` that function adds to the disparity.- :class:`~kornia.geometry.camera.pinhole.PinholeCamera`: a single camera with intrinsics andworld-to-camera extrinsics."""@@ -222,15 +222,17 @@ class StereoCamera:f"Got {rectified_left_camera.dtype} and {rectified_right_camera.dtype}.")- # Ensure all intrinsics parameters (fx, fy, cx, cy) are the same in both cameras.+ # Ensure fx, fy and cy are the same in both cameras. cx may differ, as a rectification that keeps each+ # camera's principal point produces (OpenCV's stereoRectify without CALIB_ZERO_DISPARITY).# The check reads the data, which graph capture cannot do; skip it under any capture (torch.compile,# torch.export).- if not is_compiling() and not torch.all(- torch.eq(rectified_left_camera[..., :, :3], rectified_right_camera[..., :, :3])+ if not is_compiling() and not (+ torch.all(torch.eq(rectified_left_camera[..., :, :2], rectified_right_camera[..., :, :2]))+ and torch.all(torch.eq(rectified_left_camera[..., 1:, 2], rectified_right_camera[..., 1:, 2]))):raise StereoException(- "Expected 'left_rectified_camera' and 'rectified_right_camera' to have"- "same parameters except for the last column."+ "Expected 'rectified_left_camera' and 'rectified_right_camera' to have the same fx, fy and cy; "+ "only cx and the last column may differ. "f"Got {rectified_left_camera[..., :, :3]} and {rectified_right_camera[..., :, :3]}.")diff --git a/tests/geometry/camera/test_stereo.py b/tests/geometry/camera/test_stereo.pyindex 397acd30c..255910a27 100644--- a/tests/geometry/camera/test_stereo.py+++ b/tests/geometry/camera/test_stereo.py@@ -550,7 +550,7 @@ class TestStereoCamera(BaseTester):def test_convention_tx_is_the_right_translation_over_fx_and_fixes_q(self, device, dtype):# tx = -P_right[0, 3] / fx, and Q is built from it with Q[0, 0] = fy * (-tx), Q[1, 1] = fx * (-tx): the# 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).+ # there. Q[3, 3] = fy * (cx_left - cx_right) is 0 on this equal-cx fixture (#4270, below).cam = self._asymmetric_stereo(device, dtype)assert cam.Q.dtype == dtypeassert cam.Q.device == device@@ -610,14 +610,69 @@ class TestStereoCamera(BaseTester):assert bool((points[0, :, :, 0] == points[0, :1, :, 0]).all())assert bool((points[0, :, :, 1] == points[0, :, :1, 1]).all())- def test_wart_stereo_rejects_differing_principal_points_4270(self, device, dtype):- # Wart pin for #4270: Q[3, 3] = fy * (cx_left - cx_right) exists for a differing cx, but the constructor- # rejects one, so Q[3, 3] is always 0. Delete when #4270 is repaired.- with pytest.raises(StereoException, match="same parameters except for the last column"):- self._asymmetric_stereo(device, dtype, cx_right=5.0)+ def test_stereo_accepts_differing_principal_points_4270(self, device, dtype):+ # Differing cx is accepted (#4270): Q[3, 3] = fy * (cx_left - cx_right), as in OpenCV's Q without+ # CALIB_ZERO_DISPARITY.+ cam = self._asymmetric_stereo(device, dtype, cx_right=5.0)+ assert not torch.equal(cam.cx_left, cam.cx_right)+ self.assert_close(cam.Q[0, 3, 3], cam.fy[0] * (cam.cx_left[0] - cam.cx_right[0]))++ @pytest.mark.parametrize("row, col", [(0, 0), (1, 1), (1, 2)], ids=["fx", "fy", "cy"])+ def test_convention_stereo_rejects_differing_fx_fy_or_cy_4270(self, row, col, device, dtype):+ # Differing cx is allowed (#4270); a mismatch in fx, fy or cy is still rejected.cam = self._asymmetric_stereo(device, dtype)- assert torch.equal(cam.cx_left, cam.cx_right)- assert cam.Q[0, 3, 3].item() == 0.0+ right = cam.rectified_right_camera.clone()+ right[0, row, col] = right[0, row, col] + 1.0+ with pytest.raises(StereoException, match="the same fx, fy and cy"):+ StereoCamera(cam.rectified_left_camera, right)++ def test_convention_stereo_matches_opencv_q_without_zero_disparity_4270(self, device, dtype):+ # Generated with OpenCV 5.0.0 (opencv-python-headless):+ # K1 = [[700, 0, 320], [0, 700, 240], [0, 0, 1]]; K2 = [[700, 0, 340], [0, 700, 245], [0, 0, 1]]+ # _, _, P1, P2, Q, _, _ = cv2.stereoRectify(K1, zeros(5), K2, zeros(5), (640, 480), eye(3),+ # [-0.12, 0, 0], flags=0, alpha=0)+ # point = cv2.reprojectImageTo3D(full((4, 5), 30, float32), Q)[2, 3]+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("float16 overflows fx * fy in Q at this focal length; bfloat16 rounds Q beyond this comparison")+ p1 = torch.tensor(+ [+ [+ [707.4786324786324, 0.0, 320.0, 0.0],+ [0.0, 707.4786324786324, 242.5, 0.0],+ [0.0, 0.0, 1.0, 0.0],+ ]+ ],+ device=device,+ dtype=dtype,+ )+ p2 = torch.tensor(+ [+ [+ [707.4786324786324, 0.0, 340.0, -84.8974358974359],+ [0.0, 707.4786324786324, 242.5, 0.0],+ [0.0, 0.0, 1.0, 0.0],+ ]+ ],+ device=device,+ dtype=dtype,+ )+ q_opencv = torch.tensor(+ [+ [1.0, 0.0, 0.0, -320.0],+ [0.0, 1.0, 0.0, -242.5],+ [0.0, 0.0, 0.0, 707.4786324786324],+ [0.0, 0.0, 8.333333333333334, 166.66666666666669],+ ],+ device=device,+ dtype=dtype,+ )+ point_opencv = torch.tensor(+ [-0.7608000040054321, -0.5771999955177307, 1.697948694229126], device=device, dtype=dtype+ )+ cam = StereoCamera(p1, p2)+ self.assert_close(cam.Q[0] / cam.Q[0, 3, 2], q_opencv / q_opencv[3, 2])+ disparity = torch.full((1, 4, 5, 1), 30.0, device=device, dtype=dtype)+ self.assert_close(reproject_disparity_to_3D(disparity, cam.Q)[0, 2, 3], point_opencv)@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):