Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] Stereo camera class (#1102)

copaah0b8fa03faef7
diff --git a/docs/source/geometry.camera.rst b/docs/source/geometry.camera.rst
index 0e5423cf1..d57e51440 100644
--- a/docs/source/geometry.camera.rst
+++ b/docs/source/geometry.camera.rst
@@ -8,3 +8,4 @@ kornia.geometry.camera
geometry.camera.pinhole
geometry.camera.perspective
+ geometry.camera.stereo
diff --git a/docs/source/geometry.camera.stereo.rst b/docs/source/geometry.camera.stereo.rst
new file mode 100644
index 000000000..abe99b043
--- /dev/null
+++ b/docs/source/geometry.camera.stereo.rst
@@ -0,0 +1,160 @@
+Stereo Camera
+-------------
+
+.. currentmodule:: kornia.geometry.camera.stereo
+
+In this module we provide the :class:`StereoCamera` that contains functionality for working with a horizontal stereo camera setup.
+
+The horizontal stereo camera setup is assumed to be calibrated and rectified such that the setup can be described by two camera matrices:
+
+The *left rectified camera matrix*:
+
+.. math::
+ P_0 = \begin{bmatrix}
+ fx & 0 & cx & 0 \\
+ 0 & fy & cy & 0 \\
+ 0 & 0 & 1 & 0
+ \end{bmatrix}
+
+The *right rectified camera matrix*:
+
+.. math::
+ P_1 = \begin{bmatrix}
+ fx & 0 & cx & tx * fx \\
+ 0 & fy & cy & 0 \\
+ 0 & 0 & 1 & 0
+ \end{bmatrix}
+
+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:`cy` is the y-coordinate of the principal point in pixels.
+ * :math:`tx` is the horizontal baseline in metric units.
+
+These camera matrices are obtained by calibrating your stereo camera setup which can be done `in OpenCV <https://docs.opencv.org/master/d9/d0c/group__calib3d.html#ga91018d80e2a93ade37539f01e6f07de5>`_.
+
+The :class:`StereoCamera` allows you to convert disparity maps to the real world 3D geometry represented by a point cloud.
+
+This is done by forming the :math:`Q` matrix.
+
+Using the pinhole camera model to project :math:`[X Y Z 1]` in world coordinates to :math:`uv` pixels in the left and right camera frame respectively:
+
+.. math::
+
+ \begin{bmatrix}
+ u \\
+ v \\
+ 1
+ \end{bmatrix} = P_0 *
+ \begin{bmatrix}
+ X \\
+ Y \\
+ Z \\
+ 1
+ \end{bmatrix} \\
+ \begin{bmatrix}
+ u-d \\
+ v \\
+ 1
+ \end{bmatrix} = P_1 *
+ \begin{bmatrix}
+ X \\
+ Y \\
+ Z \\
+ 1
+ \end{bmatrix}
+
+Where :math:`d` is the disparity between pixels in left and right image.
+
+Combining these two expressions let us write it as one matrix multiplication
+
+.. math::
+ \begin{bmatrix}
+ u \\
+ v \\
+ u-d \\
+ 1
+ \end{bmatrix} =
+ \begin{bmatrix}
+ fx & 0 & cx_{left} & 0 \\
+ 0 & fy & cy & 0 \\
+ fx & 0 & cx_{right} & fx * tx \\
+ 0 & 0 & 1 & 0
+ \end{bmatrix}
+ \begin{bmatrix}
+ X \\
+ Y \\
+ Z \\
+ 1
+ \end{bmatrix}
+
+Now subtract the first from the third row and invert the expression and you'll get:
+
+.. math::
+ \begin{bmatrix}
+ u \\
+ v \\
+ d \\
+ 1
+ \end{bmatrix} =
+ \begin{bmatrix}
+ fy * tx & 0 & 0 & -fy * cx * tx \\
+ 0 & fx * tx & 0 & -fx * cy * tx \\
+ 0 & 0 & 0 & fx * fy * tx \\
+ 0 & 0 & -fy & fy * (cx_{left} -cx_{right})
+ \end{bmatrix}
+ \begin{bmatrix}
+ X \\
+ Y \\
+ Z \\
+ 1
+ \end{bmatrix}
+
+Where :math:`Q` is
+
+.. math::
+
+ Q = \begin{bmatrix}
+ fy * tx & 0 & 0 & -fy * cx * tx \\
+ 0 & fx * tx & 0 & -fx * cy * tx \\
+ 0 & 0 & 0 & fx * fy * tx \\
+ 0 & 0 & -fy & fy * (cx_{left} -cx_{right})
+ \end{bmatrix}
+
+Notice here that the x-coordinate for the principal point in the left and right camera :math:`cx` might differ, which is being taken into account here.
+
+Assuming :math:`fx = fy` you can further reduce this to:
+
+.. math::
+ Q = \begin{bmatrix}
+ 1 & 0 & 0 & -cx \\
+ 0 & 1 & 0 & -cy \\
+ 0 & 0 & 0 & fx \\
+ 0 & 0 & -1/tx & (cx_{left} -cx_{right} / tx)
+ \end{bmatrix}
+
+But we'll use the general :math:`Q` matrix.
+
+Using the :math:`Q` matrix we can obtain the 3D points by:
+
+.. math::
+ \begin{bmatrix}
+ X \\
+ Y \\
+ Z \\
+ W
+ \end{bmatrix} = Q *
+ \begin{bmatrix}
+ u \\
+ v \\
+ disparity(y, v) \\
+ z
+ \end{bmatrix}
+
+.. autoclass:: StereoCamera
+ :members:
+
+ .. automethod:: __init__
+
+.. autofunction:: reproject_disparity_to_3D
diff --git a/kornia/geometry/camera/__init__.py b/kornia/geometry/camera/__init__.py
index c43a56ed0..0630c94d3 100644
--- a/kornia/geometry/camera/__init__.py
+++ b/kornia/geometry/camera/__init__.py
@@ -1,4 +1,5 @@
from .perspective import project_points, unproject_points
from .pinhole import cam2pixel, PinholeCamera, pixel2cam
+from .stereo import StereoCamera
-__all__ = ["PinholeCamera", "pixel2cam", "cam2pixel", "unproject_points", "project_points"]
+__all__ = ["PinholeCamera", "StereoCamera", "pixel2cam", "cam2pixel", "unproject_points", "project_points"]
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
new file mode 100644
index 000000000..a647150c2
--- /dev/null
+++ b/kornia/geometry/camera/stereo.py
@@ -0,0 +1,307 @@
+import torch
+
+from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
+from kornia.geometry.linalg import transform_points
+from kornia.utils.grid import create_meshgrid
+
+
+class StereoException(Exception):
+ def __init__(self, msg: str, *args, **kwargs):
+ """
+ Custom exception for the :module:`~kornia.geometry.camera.stereo` module. Adds a general helper module
+ redirecting the user to the proper documentation site.
+ Args:
+ msg (str): Custom message to add to the general message.
+ *args:
+ **kwargs:
+ """
+ doc_help = (
+ "\n Please check documents here: "
+ "https://kornia.readthedocs.io/en/latest/geometry.camera.stereo.html for further information and examples."
+ )
+ final_msg = msg + doc_help
+ # type ignore becauce of mypy error:
+ # Too many arguments for "__init__" of "BaseException"
+ super().__init__(final_msg, *args, **kwargs) # type: ignore
+
+
+class StereoCamera:
+ def __init__(self, rectified_left_camera: torch.Tensor, rectified_right_camera: torch.Tensor):
+ """
+ Class representing a horizontal stereo camera setup.
+
+ Args:
+ rectified_left_camera (torch.Tensor): The rectified left camera projection matrix
+ of shape :math:`(B, 3, 4)`
+ rectified_right_camera (torch.Tensor): The rectified right camera projection matrix
+ of shape :math:`(B, 3, 4)`
+ """
+ self._check_stereo_camera(rectified_left_camera, rectified_right_camera)
+ self.rectified_left_camera: torch.Tensor = rectified_left_camera
+ self.rectified_right_camera: torch.Tensor = rectified_right_camera
+
+ self.device: torch.device = self.rectified_left_camera.device
+ self.dtype: torch.dtype = self.rectified_left_camera.dtype
+
+ self._Q_matrix = self._init_Q_matrix()
+
+ @staticmethod
+ def _check_stereo_camera(rectified_left_camera: torch.Tensor, rectified_right_camera: torch.Tensor):
+ """
+ Utility function to ensure user specified correct camera matrices.
+ Args:
+ rectified_left_camera (torch.Tensor): The rectified left camera projection matrix
+ of shape :math:`(B, 3, 4)`
+ rectified_right_camera (torch.Tensor): The rectified right camera projection matrix
+ of shape :math:`(B, 3, 4)`
+ """
+ # Ensure correct shapes
+ if rectified_left_camera.ndim != 3:
+ raise StereoException(
+ f"Expected 'rectified_left_camera' to have 3 dimensions. " f"Got {rectified_left_camera.ndim}."
+ )
+
+ if rectified_right_camera.ndim != 3:
+ raise StereoException(
+ f"Expected 'rectified_right_camera' to have 3 dimension. " f"Got {rectified_right_camera.ndim}."
+ )
+
+ if rectified_left_camera.shape[:1] == (3, 4):
+ raise StereoException(
+ f"Expected each 'rectified_left_camera' to be of shape (3, 4)."
+ f"Got {rectified_left_camera.shape[:1]}."
+ )
+
+ if rectified_right_camera.shape[:1] == (3, 4):
+ raise StereoException(
+ f"Expected each 'rectified_right_camera' to be of shape (3, 4)."
+ f"Got {rectified_right_camera.shape[:1]}."
+ )
+
+ # Ensure same devices for cameras.
+ if rectified_left_camera.device != rectified_right_camera.device:
+ raise StereoException(
+ f"Expected 'rectified_left_camera' and 'rectified_right_camera' "
+ f"to be on the same devices."
+ f"Got {rectified_left_camera.device} and {rectified_right_camera.device}."
+ )
+
+ # Ensure same dtypes for cameras.
+ if rectified_left_camera.dtype != rectified_right_camera.dtype:
+ raise StereoException(
+ f"Expected 'rectified_left_camera' and 'rectified_right_camera' to"
+ f"have same dtype."
+ 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.
+ if not torch.all(torch.eq(rectified_left_camera[..., :, :3], rectified_right_camera[..., :, :3])):
+ raise StereoException(
+ f"Expected 'left_rectified_camera' and 'rectified_right_camera' to have"
+ f"same parameters except for the last column."
+ f"Got {rectified_left_camera[..., :, :3]} and {rectified_right_camera[..., :, :3]}."
+ )
+
+ # Ensure that tx * fx is negative and exists.
+ tx_fx = rectified_right_camera[..., 0, 3]
+ if torch.all(torch.gt(tx_fx, 0)):
+ raise StereoException(f"Expected :math:`T_x * f_x` to be negative." f"Got {tx_fx}.")
+
+ @property
+ def batch_size(self) -> int:
+ r"""Returns the batch size of the storage.
+
+ Returns:
+ int: scalar with the batch size
+ """
+ return self.rectified_left_camera.shape[0]
+
+ @property
+ def fx(self) -> torch.Tensor:
+ r"""Returns the focal length in the x-direction. Note that the focal lengths of the rectified left and right
+ camera are assumed to be equal.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
+ return self.rectified_left_camera[..., 0, 0]
+
+ @property
+ def fy(self) -> torch.Tensor:
+ r"""Returns the focal length in the y-direction. Note that the focal lengths of the rectified left and right
+ camera are assumed to be equal.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
+ return self.rectified_left_camera[..., 1, 1]
+
+ @property
+ def cx_left(self) -> torch.Tensor:
+ r"""Returns the x-coordinate of the principal point for the left camera.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
+ return self.rectified_left_camera[..., 0, 2]
+
+ @property
+ def cx_right(self) -> torch.Tensor:
+ r"""Returns the x-coordinate of the principal point for the right camera.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
+ return self.rectified_right_camera[..., 0, 2]
+
+ @property
+ def cy(self) -> torch.Tensor:
+ r"""Returns the y-coordinate of the principal point. Note that the y-coordinate of the principal points
+ is assumed to be equal for the left and right camera.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
+ return self.rectified_left_camera[..., 1, 2]
+
+ @property
+ def tx(self) -> torch.Tensor:
+ """
+ The horizontal baseline between the two cameras.
+
+ Returns:
+ torch.tensor: Tensor of shape :math:`(B)`
+
+ """
+ return -self.rectified_right_camera[..., 0, 3] / self.fx
+
+ @property
+ def Q(self) -> torch.Tensor:
+ """
+ The Q matrix of the horizontal stereo setup. This matrix is used for reprojecting a disparity tensor to
+ the corresponding point cloud. Note that this is in a general form that allows different focal
+ lengths in the x and y direction.
+
+ Return:
+ torch.Tensor: The Q matrix of shape :math:`(B, 4, 4)`.
+ """
+ return self._Q_matrix
+
+ def _init_Q_matrix(self) -> torch.Tensor:
+ """
+ Initialized the Q matrix of the horizontal stereo setup. See the Q property.
+
+ Returns:
+ torch.Tensor: The Q matrix of shape :math:`(B, 4, 4)`.
+
+ """
+ Q = torch.zeros((self.batch_size, 4, 4), device=self.device, dtype=self.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.
+ return Q
+
+ def reproject_disparity_to_3D(self, disparity_tensor: torch.Tensor) -> torch.Tensor:
+ """
+ Reproject the disparity tensor to a 3D point cloud.
+
+ Args:
+ disparity_tensor (torch.Tensor): Disparity tensor of shape :math:`(B, 1, H, W)`.
+
+ Returns:
+ torch.Tensor: The 3D point cloud of shape :math:`(B, H, W, 3)`
+ """
+ return reproject_disparity_to_3D(disparity_tensor, self.Q)
+
+
+def _check_disparity_tensor(disparity_tensor: torch.Tensor):
+ """
+ Utility function to ensure correct user provided correct disparity tensor.
+
+ Args:
+ disparity_tensor (torch.Tensor): The disparity tensor of shape :math:`(B, 1, H, W)`.
+ """
+ if not isinstance(disparity_tensor, torch.Tensor):
+ raise StereoException(
+ f"Expected 'disparity_tensor' to be an instance of torch.Tensor but got {type(disparity_tensor)}."
+ )
+
+ if disparity_tensor.ndim != 4:
+ raise StereoException(f"Expected 'disparity_tensor' to have 4 dimensions." f"Got {disparity_tensor.ndim}.")
+
+ if disparity_tensor.shape[-1] != 1:
+ raise StereoException(
+ f"Expected dimension 1 of 'disparity_tensor' to be 1 for as single channeled disparity map."
+ f"Got {disparity_tensor.shape}."
+ )
+
+ if disparity_tensor.dtype not in (torch.float16, torch.float32, torch.float64):
+ raise StereoException(
+ f"Expected 'disparity_tensor' to have dtype torch.float16, torch.float32 or torch.float64."
+ f"Got {disparity_tensor.dtype}"
+ )
+
+
+def _check_Q_matrix(Q_matrix: torch.Tensor):
+ """
+ Utility function to ensure Q matrix is of correct form.
+ Args:
+ Q_matrix (torch.Tensor): The Q matrix for reprojecting disparity to a point cloud of shape :math:`(B, 4, 4)`
+ """
+
+ if not isinstance(Q_matrix, torch.Tensor):
+ raise StereoException(f"Expected 'Q_matrix' to be an instance of torch.Tensor but got {type(Q_matrix)}.")
+
+ if not Q_matrix.ndim == 3:
+ raise StereoException(f"Expected 'Q_matrix' to have 3 dimenstions." f"Got {Q_matrix.ndim}")
+
+ if not Q_matrix.shape[1:] == (4, 4):
+ raise StereoException(
+ f"Expected last two dimensions of 'Q_matrix' to be of shape (4, 4)." f"Got {Q_matrix.shape}"
+ )
+
+ if Q_matrix.dtype not in (torch.float16, torch.float32, torch.float64):
+ raise StereoException(
+ f"Expected 'Q_matrix' to be of type torch.float16, torch.float32 or torch.float64." f"Got {Q_matrix.dtype}"
+ )
+
+
+def reproject_disparity_to_3D(disparity_tensor: torch.Tensor, Q_matrix: torch.Tensor) -> torch.Tensor:
+ """
+ Reproject the disparity tensor to a 3D point cloud.
+
+ Args:
+ disparity_tensor (torch.Tensor): Disparity tensor of shape :math:`(B, 1, H, W)`.
+ Q_matrix (torch.Tensor): Tensor of Q matrices of shapes :math:`(B, 4, 4)`.
+
+ Returns:
+ torch.Tensor: The 3D point cloud of shape :math:`(B, H, W, 3)`
+ """
+ _check_Q_matrix(Q_matrix)
+ _check_disparity_tensor(disparity_tensor)
+
+ batch_size, rows, cols, _ = disparity_tensor.shape
+ dtype = disparity_tensor.dtype
+ device = disparity_tensor.device
+
+ 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)
+ 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)
+
+ # Final check that everything went well.
+ if not points.shape == (batch_size, rows, cols, 3):
+ raise StereoException(
+ f"Something went wrong in `reproject_disparity_to_3D`. Expected the final output"
+ f"to be of shape {(batch_size, rows, cols, 3)}."
+ f"But the computed point cloud had shape {points.shape}. "
+ f"Please ensure input are correct. If this is an error, please submit an issue."
+ )
+ return points
diff --git a/test/geometry/test_stereo.py b/test/geometry/test_stereo.py
new file mode 100644
index 000000000..702c8fc8b
--- /dev/null
+++ b/test/geometry/test_stereo.py
@@ -0,0 +1,257 @@
+from typing import Type
+
+import pytest
+import torch
+from torch.testing import assert_allclose
+
+from kornia.geometry.camera.stereo import StereoCamera
+
+
[email protected](params=[1, 2, 4])
+def batch_size(request):
+ return request.param
+
+
+class _TestParams:
+ """Collection of test parameters for smoke test."""
+
+ height = 4
+ width = 6
+ fx = 1
+ fy = 2
+ cx = width / 2
+ cy = height / 2
+
+
+class _RealTestData:
+ """Collection of data from a real stereo setup."""
+
+ @property
+ def height(self):
+ return 375
+
+ @property
+ def width(self):
+ return 1242
+
+ @staticmethod
+ def _get_real_left_camera(batch_size, device, dtype):
+ cam = torch.tensor(
+ [
+ 9.9640068207290187e02,
+ 0.0,
+ 3.7502582168579102e02,
+ 0.0,
+ 0.0,
+ 9.9640068207290187e02,
+ 2.4026374816894531e02,
+ 0.0,
+ 0.0,
+ 0.0,
+ 1.0,
+ 0.0,
+ ],
+ device=device,
+ dtype=dtype,
+ ).reshape(3, 4)
+ return cam.expand(batch_size, -1, -1)
+
+ @staticmethod
+ def _get_real_right_camera(batch_size, device, dtype):
+ cam = torch.tensor(
+ [
+ 9.9640068207290187e02,
+ 0.0,
+ 3.7502582168579102e02,
+ -5.4301732344712009e03,
+ 0.0,
+ 9.9640068207290187e02,
+ 2.4026374816894531e02,
+ 0.0,
+ 0.0,
+ 0.0,
+ 1.0,
+ 0.0,
+ ],
+ device=device,
+ dtype=dtype,
+ ).reshape(3, 4)
+ return cam.expand(batch_size, -1, -1)
+
+ @staticmethod
+ def _get_real_stereo_camera(batch_size, device, dtype):
+ return (
+ _RealTestData._get_real_left_camera(batch_size, device, dtype),
+ _RealTestData._get_real_right_camera(batch_size, device, dtype),
+ )
+
+ @staticmethod
+ def _get_real_disparity(batch_size, device, dtype):
+ # First 10 cols of 1 row in a real disparity map.
+ disp = torch.tensor(
+ [
+ [
+ [
+ [67.5039],
+ [67.5078],
+ [67.5117],
+ [67.5156],
+ [67.5195],
+ [67.5234],
+ [67.5273],
+ [67.5312],
+ [67.5352],
+ [67.5391],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ).permute(0, 2, 3, 1)
+ return disp.expand(batch_size, -1, -1, -1)
+
+ @staticmethod
+ def _get_real_point_cloud(batch_size, device, dtype):
+ # First 10 cols of 1 row in the ground truth point cloud computed from above disparity map.
+ pc = torch.tensor(
+ [
+ [
+ [[-30.2769, -19.3972, 80.4424]],
+ [[-30.1945, -19.3961, 80.4377]],
+ [[-30.1120, -19.3950, 80.4330]],
+ [[-30.0295, -19.3938, 80.4284]],
+ [[-29.9471, -19.3927, 80.4237]],
+ [[-29.8646, -19.3916, 80.4191]],
+ [[-29.7822, -19.3905, 80.4144]],
+ [[-29.6998, -19.3893, 80.4098]],
+ [[-29.6174, -19.3882, 80.4051]],
+ [[-29.5350, -19.3871, 80.4005]],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ return pc.expand(batch_size, -1, -1, -1)
+
+
+class _SmokeTestData:
+ """Collection of smoke test data."""
+
+ @staticmethod
+ def _create_rectified_camera(params: Type[_TestParams], batch_size, device, dtype, tx_fx=None):
+ intrinsics = torch.zeros((3, 4), device=device, dtype=dtype)
+ intrinsics[..., 0, 0] = params.fx
+ intrinsics[..., 1, 1] = params.fy
+ intrinsics[..., 0, 2] = params.cx
+ intrinsics[..., 1, 2] = params.cy
+
+ if tx_fx:
+ intrinsics[..., 0, 3] = tx_fx
+
+ return intrinsics.expand(batch_size, -1, -1)
+
+ @staticmethod
+ def _create_left_camera(batch_size, device, dtype):
+ return _SmokeTestData._create_rectified_camera(_TestParams, batch_size, device, dtype)
+
+ @staticmethod
+ def _create_right_camera(batch_size, device, dtype, tx_fx):
+ return _SmokeTestData._create_rectified_camera(_TestParams, batch_size, device, dtype, tx_fx=tx_fx)
+
+ @staticmethod
+ def _create_stereo_camera(batch_size, device, dtype, tx_fx):
+ left_rectified_camera = _SmokeTestData._create_left_camera(batch_size, device, dtype)
+ right_rectified_camera = _SmokeTestData._create_right_camera(batch_size, device, dtype, tx_fx)
+ return left_rectified_camera, right_rectified_camera
+
+
+class TestStereoCamera:
+ """Test class for :class:`~kornia.geometry.camera.stereo.StereoCamera`"""
+
+ @staticmethod
+ def _create_disparity_tensor(batch_size, height, width, max_disparity, device, dtype):
+ size = (batch_size, height, width, 1)
+ return torch.randint(size=size, low=0, high=max_disparity, device=device, dtype=dtype)
+
+ @staticmethod
+ def test_stereo_camera_attributes_smoke(batch_size, device, dtype):
+ """Test proper setup of the class for smoke data."""
+ tx_fx = -10
+ left_rectified_camera, right_rectified_camera = _SmokeTestData._create_stereo_camera(
+ batch_size, device, dtype, tx_fx
+ )
+
+ stereo_camera = StereoCamera(left_rectified_camera, right_rectified_camera)
+
+ def _assert_all(x, y):
+ assert torch.all(torch.eq(x, y))
+
+ _assert_all(stereo_camera.fx, _TestParams.fx)
+ _assert_all(stereo_camera.fy, _TestParams.fy)
+ _assert_all(stereo_camera.cx_left, _TestParams.cx)
+ _assert_all(stereo_camera.cy, _TestParams.cy)
+ _assert_all(stereo_camera.tx, -tx_fx / _TestParams.fx)
+
+ assert stereo_camera.Q.shape == (batch_size, 4, 4)
+ assert stereo_camera.Q.dtype in (torch.float16, torch.float32, torch.float64)
+
+ @staticmethod
+ def test_stereo_camera_attributes_real(batch_size, device, dtype):
+ """Test proper setup of the class for real data."""
+ left_rectified_camera, right_rectified_camera = _RealTestData._get_real_stereo_camera(batch_size, device, dtype)
+
+ stereo_camera = StereoCamera(left_rectified_camera, right_rectified_camera)
+ assert_allclose(stereo_camera.fx, left_rectified_camera[..., 0, 0])
+ assert_allclose(stereo_camera.fy, left_rectified_camera[..., 1, 1])
+ assert_allclose(stereo_camera.cx_left, left_rectified_camera[..., 0, 2])
+ assert_allclose(stereo_camera.cy, left_rectified_camera[..., 1, 2])
+ assert_allclose(stereo_camera.tx, -right_rectified_camera[..., 0, 3] / right_rectified_camera[..., 0, 0])
+
+ assert stereo_camera.Q.shape == (batch_size, 4, 4)
+ assert stereo_camera.Q.dtype in (torch.float16, torch.float32, torch.float64)
+
+ def test_reproject_disparity_to_3D_smoke(self, batch_size, device, dtype):
+ """Test reprojecting of disparity to 3D for smoke data."""
+ tx_fx = -10
+ left_rectified_camera, right_rectified_camera = _SmokeTestData._create_stereo_camera(
+ batch_size, device, dtype, tx_fx
+ )
+ disparity_tensor = self._create_disparity_tensor(
+ batch_size, _TestParams.height, _TestParams.width, max_disparity=2, device=device, dtype=dtype
+ )
+ stereo_camera = StereoCamera(left_rectified_camera, right_rectified_camera)
+ xyz = stereo_camera.reproject_disparity_to_3D(disparity_tensor)
+
+ assert xyz.shape == (batch_size, _TestParams.height, _TestParams.width, 3)
+ assert xyz.dtype in (torch.float16, torch.float32, torch.float64)
+ assert xyz.device == device
+
+ @staticmethod
+ def test_reproject_disparity_to_3D_real(batch_size, device, dtype):
+ """Test reprojecting of disparity to 3D for known outcome."""
+ disparity_tensor = _RealTestData._get_real_disparity(batch_size, device, dtype)
+ xyz_gt = _RealTestData._get_real_point_cloud(batch_size, device, dtype)
+
+ left_rectified_camera, right_rectified_camera = _RealTestData._get_real_stereo_camera(batch_size, device, dtype)
+ stereo_camera = StereoCamera(left_rectified_camera, right_rectified_camera)
+
+ xyz = stereo_camera.reproject_disparity_to_3D(disparity_tensor)
+
+ assert_allclose(xyz, xyz_gt)
+
+ 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
+ max_disparity = 80
+ disparity_tensor = self._create_disparity_tensor(
+ batch_size, height, width, max_disparity=max_disparity, device=device, dtype=dtype
+ )
+ left_rectified_camera, right_rectified_camera = _RealTestData._get_real_stereo_camera(batch_size, device, dtype)
+ stereo_camera = StereoCamera(left_rectified_camera, right_rectified_camera)
+
+ xyz = stereo_camera.reproject_disparity_to_3D(disparity_tensor)
+
+ assert xyz.shape == (batch_size, height, width, 3)
+ assert xyz.dtype in (torch.float16, torch.float32, torch.float64)
+ assert xyz.dtype == dtype