π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(geometry): Convention blocks for camera (batch 5c: depth and stereo) (#4317)
Dmytro Mishkinf36ab6de5344
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6b14b32ed..979bb1f46 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+* Documented depth and stereo conventions (the two meanings of depth, the `(B, 3, H, W)` versus+ `(B, H, W, 3)` layouts, the opposite source/destination naming of `warp_frame_depth` and+ `DepthWarper`, the rectified stereo `Q` matrix) and added executable pins for `kornia.geometry.depth`+ and `StereoCamera`, including dtype promotion, extra-axis broadcasting, subpixel border sampling,+ and singular stereo reprojection. Remaining defects are tracked in dedicated issues. (#4317)* Documented camera distortion and calibration conventions (normalized versus pixel inputs, thecoefficient layout, the `new_K`/`K` roles, the iterative inverses) and added executable pins for`kornia.geometry.camera`'s distortion models and `kornia.geometry.calibration`, with thediff --git a/docs/source/geometry.camera.stereo.rst b/docs/source/geometry.camera.stereo.rstindex 23d3b7e26..03953ebb1 100644--- a/docs/source/geometry.camera.stereo.rst+++ b/docs/source/geometry.camera.stereo.rst@@ -125,7 +125,9 @@ where :math:`Q` is0 & 0 & -fy & fy * (cx_{left} -cx_{right})\end{bmatrix}-Notice that the x-coordinate of the principal point, :math:`cx`, may differ between the left and right cameras, which is taken into account here.+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 :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>`_.Assuming :math:`fx = fy` you can further reduce this to:diff --git a/docs/source/geometry.depth.rst b/docs/source/geometry.depth.rstindex 9e2217684..11c477fcf 100644--- a/docs/source/geometry.depth.rst+++ b/docs/source/geometry.depth.rst@@ -13,3 +13,7 @@ kornia.geometry.depth.. autofunction:: depth_to_normals.. autofunction:: depth_from_plane_equation.. autofunction:: warp_frame_depth+.. autofunction:: depth_warp++.. autoclass:: DepthWarper+ :members:diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.pyindex 62ca66fc4..2cd2852dc 100644--- a/kornia/geometry/camera/stereo.py+++ b/kornia/geometry/camera/stereo.py@@ -51,9 +51,78 @@ class StereoException(Exception):class StereoCamera:"""Represent a horizontal stereo camera setup for depth estimation.+ Convention:+ - the two arguments are the **rectified projection matrices** of the left and the right camera, each of+ shape :math:`(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.+ - the baseline is read back from that column as ``tx = -P_right[0, 3] / fx``, and :attr:`Q` is built+ from ``fx``, ``fy``, ``cx_left``, ``cy`` and that ``tx``. Note which focal length sits in which row:+ ``Q[0, 0]`` carries ``fy`` and ``Q[1, 1]`` carries ``fx``, while the homogeneous divide is by+ ``-fy * disparity``, so the two cancel and the first output coordinate ends up scaled by ``1 / fx``+ and the second by ``1 / fy``.+ - a point cloud is a homogeneous transform by :attr:`Q` followed by the divide by ``W``. When+ ``abs(W) > 1e-8``, an overall sign on :attr:`Q` cancels, so :attr:`Q` and its negation return the+ same points. For ``abs(W) <= 1e-8``, the homogeneous conversion returns the numerator unchanged,+ 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.+ - 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)`+ layout the rest of kornia uses for images is rejected -- and the returned point cloud is+ :math:`(B, H, W, 3)`.+ - 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>`_ and pinned by+ ``test_wart_reproject_disparity_reads_u_from_the_row_index_4269``,+ ``test_wart_reproject_disparity_x_varies_with_the_row_and_y_with_the_column_4269`` and the strict+ ``xfail`` ``test_convention_reproject_disparity_uses_the_column_as_u_4269`` in+ ``tests/geometry/camera/test_stereo.py``.++ .. 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. An empty batch is rejected by that+ guard as well, because ``torch.all`` of an empty tensor is ``True``+ (`#4281 <https://github.com/kornia/kornia/issues/4281>`_). The per-camera :math:`(3, 4)` shape check+ compares ``shape[:1]`` rather than ``shape[-2:]``, so it can never fire and a :math:`(B, 4, 4)` pair+ is accepted, building the same :math:`(B, 4, 4)` ``Q`` as the :math:`(B, 3, 4)` pair it should have+ required. 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``,+ ``test_wart_stereo_accepts_a_four_by_four_pair_4270`` and+ ``test_wart_stereo_rejects_an_empty_batch_4281`` in ``tests/geometry/camera/test_stereo.py``.++ .. warning::+ The module-level :func:`~kornia.geometry.camera.stereo.reproject_disparity_to_3D` is rendered on+ :doc:`/geometry.camera.stereo` but is in no ``__all__``, so it is not reachable as+ ``kornia.geometry.reproject_disparity_to_3D``. Tracked as+ `#4275 <https://github.com/kornia/kornia/issues/4275>`_.+Args:- rectified_left_camera: The intrinsic matrix for the left camera.- rectified_right_camera: The intrinsic matrix for the right camera.+ rectified_left_camera: The rectified left camera projection matrix of shape :math:`(B, 3, 4)`.+ rectified_right_camera: The rectified right camera projection matrix of shape :math:`(B, 3, 4)`."""def __init__(self, rectified_left_camera: torch.Tensor, rectified_right_camera: torch.Tensor) -> None:@@ -253,8 +322,10 @@ class StereoCamera:def reproject_disparity_to_3D(self, disparity_tensor: torch.Tensor) -> torch.Tensor:r"""Reproject the disparity torch.Tensor to a 3D point cloud.+ See the Convention block on :class:`~kornia.geometry.camera.stereo.StereoCamera`.+Args:- disparity_tensor: Disparity torch.Tensor of shape :math:`(B, 1, H, W)`.+ disparity_tensor: Disparity torch.Tensor of shape :math:`(B, H, W, 1)`.Returns:The 3D point cloud of shape :math:`(B, H, W, 3)`@@ -267,7 +338,7 @@ def _check_disparity_tensor(disparity_tensor: torch.Tensor) -> None:r"""Ensure correct user provided correct disparity torch.Tensor.Args:- disparity_tensor: The disparity torch.Tensor of shape :math:`(B, 1, H, W)`.+ disparity_tensor: The disparity torch.Tensor of shape :math:`(B, H, W, 1)`."""if not isinstance(disparity_tensor, torch.Tensor):@@ -317,6 +388,8 @@ def _check_Q_matrix(Q_matrix: torch.Tensor) -> None:def reproject_disparity_to_3D(disparity_tensor: torch.Tensor, Q_matrix: torch.Tensor) -> torch.Tensor:r"""Reproject the disparity torch.Tensor to a 3D point cloud.+ See the Convention block on :class:`~kornia.geometry.camera.stereo.StereoCamera`.+Args:disparity_tensor: Disparity torch.Tensor of shape :math:`(B, H, W, 1)`.Q_matrix: torch.Tensor of Q matrices of shapes :math:`(B, 4, 4)`.diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex f6132c90a..2176801da 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -63,17 +63,48 @@ def unproject_meshgrid(This function should be used in conjunction with :py:func:`kornia.geometry.depth.depth_to_3d_v2` to cachethe meshgrid computation when warping multiple frames with the same camera intrinsics.+ Convention:+ - the result is the ray through each pixel at depth 1, in the :math:`(B, H, W, 3)` layout, so+ multiplying it by a :math:`(B, H, W)` depth map reproduces+ :func:`~kornia.geometry.depth.depth_to_3d_v2` exactly -- which is what makes it usable as that+ function's ``xyz_grid`` cache.+ - 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`: pixel ``(0, 0)`` is centred at ``(0, 0)``.+ ``camera_matrix`` is the :math:`(3, 3)` ``[[fx, 0, cx], [0, fy, cy], [0, 0, 1]]`` of that grid and+ there are no extrinsics, so the rays are in the **camera** frame.+ - ``camera_matrix`` is batched: the supported form is :math:`(B, 3, 3)`, which returns+ :math:`(B, H, W, 3)`. Extra leading dimensions are not part of the contract: today a singleton one+ passes through by accident -- a :math:`(2, 1, 3, 3)` intrinsics returns :math:`(2, 1, H, W, 3)` --+ and non-singleton ones either raise ``RuntimeError`` or broadcast against the pixel axes (an extra+ axis matching ``W`` applies different intrinsics to each column); both are the subject of the+ warning below. An unbatched :math:`(3, 3)` raises ``ShapeError`` (below).+ - ``normalize_points=True`` returns the unit ray instead of the ray whose ``z`` is 1, which is the form+ :func:`~kornia.geometry.depth.depth_to_3d_v2` needs when its depth is a Euclidean ray length rather+ than a camera-frame ``z``.++ .. warning::+ The shape guard is written ``["*", "3", "3"]``, so a bare :math:`(3, 3)` ``camera_matrix`` passes it+ and then raises a ``ShapeError`` further into the body, whose message describes a shape the caller+ never passed rather than the one it did. The same guard admits non-singleton extra leading dimensions,+ which then broadcast against the pixel axes instead of being rejected (above). Tracked as+ `#4271 <https://github.com/kornia/kornia/issues/4271>`_ and pinned by+ ``test_wart_unproject_meshgrid_rejects_unbatched_intrinsics_4271``,+ ``test_wart_unproject_meshgrid_extra_camera_axis_broadcasts_over_columns_4271`` and the strict ``xfail``+ ``test_convention_unproject_meshgrid_error_names_the_shape_the_caller_passed_4271`` in+ ``tests/geometry/test_depth.py``.+Args:height: height of image.width: width of image.- camera_matrix: tensor containing the camera intrinsics with shape :math:`(3, 3)`.+ camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.normalize_points: whether to normalize the pointcloud. This must be set to `True` when the depth isrepresented as the Euclidean ray length from the camera position.device: device to place the result on.dtype: dtype of the result.Return:- tensor with a 3d point per pixel of the same resolution as the input :math:`(*, H, W, 3)`.+ tensor with a 3d point per pixel, with shape :math:`(B, H, W, 3)`."""KORNIA_CHECK_SHAPE(camera_matrix, ["*", "3", "3"])@@ -114,6 +145,27 @@ def depth_to_3d_v2(This is an alternative implementation of :py:func:`kornia.geometry.depth.depth_to_3d`that does not require the creation of a meshgrid.+ Convention:+ - ``depth`` is the camera-frame ``z`` of each pixel and the result is the camera-frame point+ ``((u - cx) z / fx, (v - cy) z / fy, z)``, laid out channels-**last** as :math:`(*, H, W, 3)`.+ :func:`~kornia.geometry.depth.depth_to_3d` computes the same points in the :math:`(B, 3, H, W)`+ layout, and the two are equal after ``permute(0, 2, 3, 1)``.+ - ``u`` and ``v`` are the column and the row of the integer-centre pixel grid that+ :func:`~kornia.geometry.depth.unproject_meshgrid` builds, described in the Convention block on+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`. There are no extrinsics, so the points are in+ the **camera** frame.+ - ``camera_matrix`` needs a leading batch dimension: a bare :math:`(3, 3)` passes this function's own+ guard and, when ``xyz_grid`` is not given, is then rejected inside+ :func:`~kornia.geometry.depth.unproject_meshgrid`+ (`#4271 <https://github.com/kornia/kornia/issues/4271>`_). When ``xyz_grid`` is given,+ ``camera_matrix`` is never read, so any matrix that passes the ``(*, 3, 3)`` guard -- a bare+ :math:`(3, 3)` included -- is silently accepted.+ - ``normalize_points=True`` reads ``depth`` as the Euclidean ray length from the camera centre instead+ of as ``z``, so the returned point has that norm rather than that ``z``.+ - passing ``xyz_grid`` skips the grid construction and uses the given rays instead; the two forms give+ the same result when ``xyz_grid`` is what+ :func:`~kornia.geometry.depth.unproject_meshgrid` returns for the same camera.+Args:depth: image tensor containing a depth value per pixel with shape :math:`(*, H, W)`.camera_matrix: tensor containing the camera intrinsics with shape :math:`(*, 3, 3)`.@@ -122,7 +174,10 @@ def depth_to_3d_v2(xyz_grid: explicit xyz point values.Return:- tensor with a 3d point per pixel of the same resolution as the input :math:`(*, H, W, 3)`.+ tensor with a 3d point per pixel of the same resolution as the input, :math:`(*, H, W, 3)`, whose+ leading dimensions are the broadcast of ``depth``'s and ``camera_matrix``'s: the Example broadcasts a+ :math:`(4, 4)` depth against a :math:`(2, 3, 3)` camera to :math:`(2, 4, 4, 3)`, and a+ :math:`(B, T, H, W)` depth with a :math:`(B, 1, 3, 3)` camera returns :math:`(B, T, H, W, 3)`.Example:>>> depth = torch.rand(4, 4)@@ -152,8 +207,25 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poin.. note::- This is an alternative implementation of `depth_to_3d` that does not require the creation of a meshgrid.- In future, we will support only this implementation.+ :py:func:`kornia.geometry.depth.depth_to_3d_v2` computes the same points without building a meshgrid,+ in the :math:`(B, H, W, 3)` layout, and is the newer of the two. Which of them survives,+ and on what deprecation path, is a coordinated decision that has not been taken: the two are kept side+ by side as they are and this function emits no ``DeprecationWarning``.++ Convention:+ - ``depth`` is the camera-frame ``z`` of each pixel and the result is the camera-frame point+ ``((u - cx) z / fx, (v - cy) z / fy, z)``, laid out channels-**first** as :math:`(B, 3, H, W)`.+ :func:`~kornia.geometry.depth.depth_to_3d_v2` computes the same points in the :math:`(B, H, W, 3)`+ layout, and the two are equal after ``permute(0, 2, 3, 1)``.+ - ``u`` and ``v`` are the column and the row of the integer pixel centres that+ :func:`~kornia.geometry.grid.create_meshgrid` enumerates, described in the Convention block on+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`: pixel ``(0, 0)`` is centred at ``(0, 0)``.+ ``camera_matrix`` is the :math:`(3, 3)` ``[[fx, 0, cx], [0, fy, cy], [0, 0, 1]]`` of that grid and+ there are no extrinsics, so the points are in the **camera** frame.+ - ``normalize_points=True`` reads ``depth`` as the Euclidean ray length from the camera centre instead+ of as ``z``, so the returned point has that norm rather than that ``z``.+ - an integer ``depth`` map is promoted through arithmetic with ``camera_matrix``: with floating-point+ intrinsics the point cloud follows their dtype (for example, ``float32`` or ``float64``).Args:depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.@@ -197,6 +269,18 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poindef depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:"""Compute the normal surface per pixel.+ Convention:+ - the normal is the cross product of the two spatial gradients of the unprojected point cloud, taken in+ the order ``d/dx`` cross ``d/dy`` and then normalized to unit length, so a fronto-parallel plane gets+ the normal ``(0, 0, 1)``: ``+z`` points **away** from the camera, along the viewing direction, and+ not back towards it.+ - the same order fixes the two in-plane signs: a depth that grows along the column axis tilts the+ normal towards ``-x``, and a depth that grows along the row axis tilts it towards ``-y``.+ - ``depth``, ``camera_matrix`` and ``normalize_points`` mean here what they mean for+ :func:`~kornia.geometry.depth.depth_to_3d`, whose Convention block states the pixel grid, the camera+ frame and the two readings of ``depth``; the result carries that function's :math:`(B, 3, H, W)`+ layout, with the three normal components on the channel axis.+Args:depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.@@ -241,7 +325,22 @@ def depth_from_plane_equation(camera_matrix: torch.Tensor,eps: float = 1e-8,) -> torch.Tensor:- """Compute depth values from plane equations and pixel coordinates.+ r"""Compute depth values from plane equations and pixel coordinates.++ Convention:+ - the plane is given in Hessian form :math:`n \cdot X = d`, with the normal ``plane_normals`` and the+ offset ``plane_offsets`` in the **camera** frame: ``n = (0, 0, 1)`` with ``d = 2`` is the plane+ ``z = 2``, and every pixel on it has depth 2.+ - ``points_uv`` are pixel coordinates on the integer-centre grid described in the Convention block on+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`; this function normalizes them with+ ``camera_matrix`` itself, so they are pixels and not normalized coordinates.+ - the result is the camera-frame ``z`` of each of those pixels, one value per pixel, in the+ :math:`(B, N)` layout of ``points_uv`` -- a list of depths rather than a depth map.+ - the ray-plane dot product is clamped, in a masked branch, to :math:`\pm` ``eps`` when it falls+ strictly inside :math:`(-eps, eps)`, keeping the sign of the denominator, so a nearly-grazing ray+ returns a large signed depth. An exactly zero denominator is replaced by positive ``eps``.+ The result is finite when representable in the input dtype; small ``eps`` can still underflow+ or produce overflow in ``float16``. Nothing outside the mask is touched.Args:plane_normals (torch.Tensor): Plane normal vectors of shape (B, 3).@@ -300,6 +399,38 @@ def warp_frame_depth(Compute 3d points from the depth, transform them using given transformation, then project the point cloud to animage plane.+ Convention:+ - the depth belongs to the **destination** frame (``depth_dst``) and the image to the **source** frame+ (``image_src``), and ``src_trans_dst`` maps destination-frame points into the source frame. With+ ``fx = fy = 1`` and a unit depth, a :math:`+1` translation in ``x`` therefore samples ``image_src``+ one pixel to the right of each destination pixel.+ - the unprojection is :func:`~kornia.geometry.depth.depth_to_3d_v2` and the reprojection+ :func:`~kornia.geometry.camera.perspective.project_points`, so the pixel grid, the camera frame and+ the two readings of ``depth`` selected by ``normalize_points`` are the ones stated in that function's+ Convention block.+ - the sampling is ``grid_sample`` with ``align_corners=True`` and the default+ ``padding_mode="zeros"``, both baked in: the function exposes neither. Bilinear interpolation blends in-bounds+ neighbors with the zero extension outside the image, so subpixel samples just beyond the border+ can be nonzero; samples whose entire interpolation footprint is outside return 0.+ - the result carries ``image_src``'s channel count, whatever it is: the output is :math:`(B, D, H, W)`.++ .. warning::+ :class:`~kornia.geometry.depth.DepthWarper` performs the same warp under the **opposite** naming: the+ frame this function calls ``dst`` (the one holding the depth) is that class's ``src``, and the image it+ calls ``image_src`` is that class's ``patch_dst``. The Convention block on+ :class:`~kornia.geometry.depth.DepthWarper` states the mapping in full. Tracked as+ `#4273 <https://github.com/kornia/kornia/issues/4273>`_ and pinned by+ ``test_wart_warp_frame_depth_and_depth_warper_name_the_depth_frame_oppositely_4273`` in+ ``tests/geometry/test_depth.py``.++ .. warning::+ An empty batch (:math:`B = 0`) raises ``ZeroDivisionError`` from ``transform_points`` -- its+ batch-repeat count is ``0 // 0`` -- before any sampling runs, rather than returning an empty result,+ although the shape guards on the way in accept it and+ :func:`~kornia.geometry.depth.depth_to_3d` -- the same unprojection in the other layout -- returns an+ empty point cloud. Tracked as `#4281 <https://github.com/kornia/kornia/issues/4281>`_ and pinned by+ ``test_wart_warp_frame_depth_rejects_an_empty_batch_4281`` in ``tests/geometry/test_depth.py``.+Args:image_src: image tensor in the source frame with shape :math:`(B,D,H,W)`.depth_dst: depth tensor in the destination frame with shape :math:`(B,1,H,W)`.@@ -309,7 +440,7 @@ def warp_frame_depth(is represented as the Euclidean ray length from the camera position.Return:- the warped tensor in the source frame with shape :math:`(B,3,H,W)`.+ ``image_src`` resampled onto the destination pixel grid, with shape :math:`(B,D,H,W)`."""KORNIA_CHECK_SHAPE(image_src, ["B", "D", "H", "W"])@@ -342,8 +473,64 @@ class DepthWarper(nn.Module):I_{src} = \\omega(I_{dst}, P_{src}^{\{dst\}}, D_{src})+ Convention:+ - the depth lives in the **source** frame and the image in the **destination** frame:+ :meth:`forward` takes ``(depth_src, patch_dst)``, samples ``patch_dst`` at the pixels the+ source-frame depth projects to, and returns a :math:`(B, C, H, W)` tensor carrying ``patch_dst``'s+ channel count.+ - this is a two-step API: :meth:`compute_projection_matrix` has to be called first. Until it has+ been, :meth:`warp_grid` and :meth:`forward` raise ``ValueError`` and :meth:`compute_subpixel_step`+ raises ``RuntimeError``.+ - :meth:`compute_projection_matrix` stores exactly the matrix of the equation above,+ ``K_dst @ (E_dst @ inverse(E_src))``, with ``K_dst`` and ``E_dst`` the ``intrinsics`` and+ ``extrinsics`` of the ``pinhole_dst`` given to the constructor and ``E_src`` the ``extrinsics`` of+ the ``pinhole_src`` given to that method. The source extrinsics are inverted, not transposed, so the+ translation is carried through.+ - both cameras are :class:`~kornia.geometry.camera.pinhole.PinholeCamera` objects, so their+ ``intrinsics`` are the :math:`(B, 4, 4)` matrix and their ``extrinsics`` the world-to-camera+ transform that class's Convention block describes.+ - the ``grid`` attribute is this instance's own grid of integer pixel centres -- the grid+ :func:`~kornia.geometry.grid.create_meshgrid` enumerates and the Convention block on+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera` describes -- in homogeneous form: pixel+ ``(0, 0)`` is ``(0, 0, 1)``. :meth:`warp_grid` returns something else: the sampling positions in+ ``grid_sample``'s ``align_corners=True`` normalized coordinates, in which the **destination**+ image's integer-centre pixel ``(0, 0)`` is ``(-1, -1)`` and its pixel ``(H - 1, W - 1)`` is+ ``(1, 1)``. Where each destination pixel actually lands is wherever the reprojection sends it: an+ identity camera pair leaves pixel ``(0, 0)`` at ``(-1, -1)``, a rotated and translated one sends+ it elsewhere.+ - ``align_corners`` defaults to ``True``; it is handed to ``grid_sample`` unchanged, together with+ ``mode`` and ``padding_mode``.+ - :func:`~kornia.geometry.depth.depth_warp` is the functional form of this class -- it builds one,+ calls :meth:`compute_projection_matrix` and forwards -- and returns a result equal to it bit for bit.+ It exposes ``align_corners`` only; ``mode`` and ``padding_mode`` keep their defaults there.++ .. warning::+ :func:`~kornia.geometry.depth.warp_frame_depth` performs the same warp under the **opposite** naming.+ The frame this class calls ``src``, the one holding the depth, is that function's ``dst``+ (``depth_dst``), and the image this class takes as ``patch_dst`` is that function's ``image_src``;+ reading "dst" as "dst" across the two APIs gives the inverse warp. The two also differ arithmetically:+ they build the sampling grid by different routes -- :func:`~kornia.geometry.depth.depth_to_3d_v2` and+ :func:`~kornia.geometry.camera.perspective.project_points` here, ``pixel2cam`` and ``cam2pixel`` there+ -- so the grid, and with it the resampled image, can differ in the last bits. Where the two grids come+ out bit-identical, so do the images. Wherever the transformed points keep a camera-frame ``z`` away+ from zero, the two agree at the working dtype's tolerance in float32 and float64; in float16 and+ bfloat16 the gap is wider than that tolerance, which is why the pin below states the claim for the two+ single- and double-precision dtypes only. At ``z = 0`` the two split outright, because their two+ projection routes guard the singularity differently:+ :func:`~kornia.geometry.camera.perspective.project_points` skips the homogeneous divide when+ ``abs(z) <= 1e-8``, so :func:`~kornia.geometry.depth.warp_frame_depth` samples ``image_src`` at the+ undivided ``(x, y)`` and returns image content, while ``cam2pixel`` divides by ``z + 1e-12`` and sends+ the same pixel to a coordinate of order ``1e12``, far outside the image. That split is one instance of+ `#4267 <https://github.com/kornia/kornia/issues/4267>`_, the namespace-wide ``z = 0`` conflict, and is+ pinned by ``test_wart_warp_frame_depth_and_depth_warper_split_at_zero_transformed_depth_4267``. The+ naming conflict is tracked as `#4273 <https://github.com/kornia/kornia/issues/4273>`_ and pinned by+ ``test_wart_warp_frame_depth_and_depth_warper_name_the_depth_frame_oppositely_4273``; the agreement away+ from ``z = 0`` is pinned by+ ``test_convention_warp_frame_depth_matches_depth_warper_without_being_bitwise_equal``. All three pins are in+ ``tests/geometry/test_depth.py``.+Args:- pinholes_dst: the pinhole models for the destination frame.+ pinhole_dst: the pinhole model for the destination frame.height: the height of the image to warp.width: the width of the image to warp.mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.@@ -387,7 +574,10 @@ class DepthWarper(nn.Module):return convert_points_to_homogeneous(grid) # append ones to last dimdef compute_projection_matrix(self, pinhole_src: PinholeCamera) -> DepthWarper:- """Compute the projection matrix from the source to destination frame."""+ """Compute the projection matrix from the source to destination frame.++ See the Convention block on :class:`~kornia.geometry.depth.DepthWarper`.+ """# Inline type checks for faster fail-fastif type(self._pinhole_dst) is not PinholeCamera:raise TypeError(@@ -446,6 +636,8 @@ class DepthWarper(nn.Module):def compute_subpixel_step(self) -> torch.Tensor:"""Compute the inverse depth step for sub pixel accurate sampling of the depth cost volume, per camera.+ See the Convention block on :class:`~kornia.geometry.depth.DepthWarper`.+Szeliski, Richard, and Daniel Scharstein. "Symmetric sub-pixel stereo matching." European Conference on ComputerVision. Springer Berlin Heidelberg, 2002."""@@ -483,6 +675,8 @@ class DepthWarper(nn.Module):def warp_grid(self, depth_src: torch.Tensor) -> torch.Tensor:"""Compute a grid for warping a given the depth from the reference pinhole camera.+ See the Convention block on :class:`~kornia.geometry.depth.DepthWarper`.+The function `compute_projection_matrix` has to be called beforehand in order to have precomputed the relativeprojection matrices encoding the relative pose and the intrinsics between the reference and a non referencecamera.@@ -519,6 +713,8 @@ class DepthWarper(nn.Module):def forward(self, depth_src: torch.Tensor, patch_dst: torch.Tensor) -> torch.Tensor:"""Warp a tensor from destination frame to reference given the depth in the reference frame.+ See the Convention block on :class:`~kornia.geometry.depth.DepthWarper`.+Args:depth_src: the depth in the reference frame. The tensor must have a shape :math:`(B, 1, H, W)`.patch_dst: the patch in the destination frame. The tensor must have a shape :math:`(B, C, H, W)`.@@ -527,7 +723,8 @@ class DepthWarper(nn.Module):the warped patch from destination frame to reference.Shape:- - Output: :math:`(N, C, H, W)` where C = number of channels.+ - Input: :math:`(B, 1, H, W)` and :math:`(B, C, H, W)`.+ - Output: :math:`(B, C, H, W)` where C = number of channels.Example:>>> # pinholes camera models@@ -564,7 +761,12 @@ def depth_warp() -> torch.Tensor:"""Warp a tensor from destination frame to reference given the depth in the reference frame.- See :class:`~kornia.geometry.warp.DepthWarper` for details.+ See the Convention block on :class:`~kornia.geometry.depth.DepthWarper`.++ This function is that class's functional form: it constructs a+ :class:`~kornia.geometry.depth.DepthWarper`, calls its ``compute_projection_matrix`` and returns its+ output, which is equal to the class's bit for bit under the default ``mode`` and ``padding_mode``, the only+ ones this function offers (``align_corners`` is forwarded).Example:>>> # pinholes camera models@@ -593,10 +795,33 @@ def depth_from_disparity() -> torch.Tensor:"""Compute depth from disparity.+ Convention:+ - the depth is ``baseline * focal / disparity``, elementwise: ``baseline`` is the distance between the+ two camera centres and ``focal`` the focal length in pixels, so a disparity of 2 with a baseline of+ 0.5 and a focal length of 100 gives a depth of 25.+ - ``baseline`` and ``focal`` are each a python ``float`` or a tensor of shape :math:`(1,)`. A 0-dim+ tensor -- what a reduction produces -- and a per-batch-element :math:`(B,)` tensor both raise+ ``ShapeError``, and a python ``int`` is rejected by the type check, so one value is shared by the+ whole batch.+ - ``disparity`` is :math:`(*, H, W)` and the result has its shape. Its sign is not checked, so a+ negative disparity gives a negative depth.++ .. warning::+ The epsilon is inside the arithmetic -- the divisor is ``disparity + 1e-8`` -- instead of selecting a+ branch, so a zero disparity, which is what a stereo matcher writes where it found no match, returns a+ large finite depth rather than ``inf`` in float32, float64 and bfloat16: ``baseline * focal / 1e-8``,+ ``5e9`` for a baseline of ``0.5`` and a focal length of ``100``, a value set by the epsilon as much as+ by the camera and one no caller can threshold against. In float16 the ``1e-8`` itself rounds to zero,+ so the same call divides by zero and returns ``inf`` after all. Tracked as+ `#4272 <https://github.com/kornia/kornia/issues/4272>`_ and pinned by+ ``test_wart_zero_disparity_gives_a_finite_depth_4272`` and+ ``test_wart_depth_from_disparity_rejects_a_batched_baseline_4272`` in ``tests/geometry/test_depth.py``.+Args:disparity: Disparity tensor of shape :math:`(*, H, W)`.- baseline: float/tensor containing the distance between the two lenses.- focal: float/tensor containing the focal length.+ baseline: a python ``float`` or a tensor of shape :math:`(1,)` containing the distance between the two+ lenses.+ focal: a python ``float`` or a tensor of shape :math:`(1,)` containing the focal length.Return:Depth map of the shape :math:`(*, H, W)`.diff --git a/tests/geometry/camera/test_stereo.py b/tests/geometry/camera/test_stereo.pyindex 33c9d6b4a..83b1077e5 100644--- a/tests/geometry/camera/test_stereo.py+++ b/tests/geometry/camera/test_stereo.py@@ -19,6 +19,7 @@ import pytestimport torchfrom kornia.geometry.camera import StereoCamera+from kornia.geometry.camera.stereo import StereoException, reproject_disparity_to_3Dfrom testing.base import BaseTester@@ -268,3 +269,317 @@ class TestStereoCamera(BaseTester):assert xyz.shape == (batch_size, height, width, 3)assert xyz.dtype in (torch.float16, torch.float32, torch.float64)assert xyz.dtype == dtype++ @staticmethod+ def _asymmetric_stereo(device, dtype, tx_fx=-50.0, fy=100.0, cx_right=4.0, batch=1):+ """Build a rectified pair with fx = 100, cx = 4, cy = 3 and a caller-chosen fy, tx * fx and right cx.++ cx = 4 != cy = 3 and the pins below use H = 3 != W = 5, so a row/column swap moves X and Y by different+ amounts; fy and tx * fx are parameters so a pin can vary one of them at a time. The right camera's last+ column is -tx * fx, so the default -50 is a baseline of tx = 0.5.+ """+ left = torch.tensor(+ [[[100.0, 0.0, 4.0, 0.0], [0.0, fy, 3.0, 0.0], [0.0, 0.0, 1.0, 0.0]]] * batch, device=device, dtype=dtype+ )+ right = torch.tensor(+ [[[100.0, 0.0, cx_right, tx_fx], [0.0, fy, 3.0, 0.0], [0.0, 0.0, 1.0, 0.0]]] * batch,+ device=device,+ dtype=dtype,+ )+ return StereoCamera(left, right)++ def test_convention_reproject_disparity_takes_bhw1(self, device, dtype):+ # Convention pin: the disparity map is+ # channels-LAST, (B, H, W, 1), for both the method and the module-level function, and the returned point+ # cloud is (B, H, W, 3). The channels-FIRST (B, 1, H, W) layout that the rest of kornia uses for images+ # is rejected, and so is an unbatched (B, H, W). The method's docstring used to say (B, 1, H, W) -- the+ # layout the shared guard rejects -- and now says (B, H, W, 1), matching the module-level function and+ # the private guard's own docstring. The guard's message still says "dimension 1" for a shape[-1] check+ # and never names (B, H, W, 1); that is kornia#4374, and the match below is on the current text.+ # The shape claim carries a value so it cannot pass on a dummy: with fx = 100 and tx = 0.5, a disparity+ # of 10 puts every point at Z = fx * tx / d = 5.+ # 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) -> shape (1, 3, 5, 3) with Z = 5.0,+ # and StereoException for the (1, 1, 3, 5) and (1, 3, 5) layouts, on cpu for float32, float64,+ # float16 and bfloat16 and on mps for float32 and float16.+ cam = self._asymmetric_stereo(device, dtype)+ disparity = torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype)+ points = cam.reproject_disparity_to_3D(disparity)+ assert points.shape == (1, 3, 5, 3)+ self.assert_close(points[0, 0, 0, 2], torch.tensor(5.0, device=device, dtype=dtype))+ with pytest.raises(StereoException, match="to be 1 for as single channeled disparity map"):+ cam.reproject_disparity_to_3D(torch.full((1, 1, 3, 5), 10.0, device=device, dtype=dtype))+ with pytest.raises(StereoException, match="to have 4 dimensions"):+ cam.reproject_disparity_to_3D(torch.full((1, 3, 5), 10.0, device=device, dtype=dtype))++ def test_convention_reproject_method_and_free_function_are_byte_identical(self, device, dtype):+ # Convention pin: the method is+ # a thin forwarder -- it passes ``self.Q`` to the module-level function and returns its result bit for+ # bit. ``Q`` is the cached tensor, not a fresh one, so the two calls see the same matrix. The result is+ # not a degenerate all-zero cloud (it reaches 5.0), so the equality is not the trivial one.+ # Snippet used to generate expected: torch.equal(cam.reproject_disparity_to_3D(d),+ # reproject_disparity_to_3D(d, cam.Q)) and cam.Q is cam._Q_matrix recorded in original commit 1a96bfd1+ # (torch 2.14.0) -> True and True on cpu for float32, float64, float16 and bfloat16 and on mps for+ # float32 and float16.+ cam = self._asymmetric_stereo(device, dtype)+ disparity = torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype)+ assert torch.equal(cam.reproject_disparity_to_3D(disparity), reproject_disparity_to_3D(disparity, cam.Q))+ assert cam.Q is cam._Q_matrix+ assert cam.reproject_disparity_to_3D(disparity).abs().max().item() > 0.1++ def test_convention_tx_is_the_right_translation_over_fx_and_fixes_q(self, device, dtype):+ # Convention pin: the baseline is read off the+ # right camera's last column, tx = -P_right[0, 3] / fx, and Q is built from it. Note which focal length+ # sits in which row: Q[0, 0] = fy * (-tx) and Q[1, 1] = fx * (-tx), i.e. the row that scales the FIRST+ # output coordinate carries fy. The fy = 50 arm varies exactly that one intrinsic and moves Q by 2500,+ # so a reading in which Q[0, 0] carried fx would fail here while passing on the fx = fy camera.+ # Q[3, 3] = fy * (cx_left - cx_right) is always 0, because the constructor rejects differing principal+ # points outright (pinned as a wart below).+ # Snippet used to generate expected, recorded in original commit 1a96bfd1 (torch 2.14.0) ->+ # [[[-50, 0, 0, 200], [0, -50, 0, 150], [0, 0, 0, -5000], [0, 0, -100, 0]]] for fy = 100 and+ # [[[-25, 0, 0, 100], [0, -50, 0, 150], [0, 0, 0, -2500], [0, 0, -50, 0]]] for fy = 50, on cpu for+ # float32, float64, float16 and bfloat16 and on mps for float32 and float16 (bfloat16 rounds the -5000+ # and -2500 entries to -4992 and -2496, hence the dtype tolerance rather than an exact comparison).+ cam = self._asymmetric_stereo(device, dtype)+ 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(+ [[[-50.0, 0.0, 0.0, 200.0], [0.0, -50.0, 0.0, 150.0], [0.0, 0.0, 0.0, -5000.0], [0.0, 0.0, -100.0, 0.0]]],+ device=device,+ dtype=dtype,+ )+ self.assert_close(cam.Q, symmetric_q)+ assert cam.Q[0, 3, 3].item() == 0.0+ asymmetric_q = torch.tensor(+ [[[-25.0, 0.0, 0.0, 100.0], [0.0, -50.0, 0.0, 150.0], [0.0, 0.0, 0.0, -2500.0], [0.0, 0.0, -50.0, 0.0]]],+ device=device,+ dtype=dtype,+ )+ self.assert_close(self._asymmetric_stereo(device, dtype, fy=50.0).Q, asymmetric_q)+ assert (symmetric_q - asymmetric_q).abs().max().item() > 1.0++ def test_convention_q_signs_only_cancel_away_from_a_zero_homogeneous_coordinate(self, device, dtype):+ # The homogeneous conversion divides by W only when abs(W) > 1e-8. With zero disparity, this Q gives+ # W = 0, so the conversion returns the homogeneous numerator. Negating Q therefore negates the result+ # instead of cancelling as it does for ordinary Euclidean points.+ # The map is a single pixel (u = v = 0) on purpose: the claim is about W = 0, and a 1 x 1 map reads the+ # same whichever index feeds which coordinate, so this pin survives the #4269 repair unchanged.+ # Snippet used to generate expected: reproject_disparity_to_3D(zeros(1, 1, 1, 1), q) and the same call+ # with -q, executed 2026-09-08 at commit 089daad9 (torch 2.14.0) -> [1, 2, 3] and its negation on cpu+ # for float32, float64, float16 and bfloat16 and on mps for float32 and float16.+ q = torch.tensor(+ [[[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 2.0], [0.0, 0.0, 0.0, 3.0], [0.0, 0.0, 1.0, 0.0]]],+ device=device,+ dtype=dtype,+ )+ disparity = torch.zeros(1, 1, 1, 1, device=device, dtype=dtype)+ points = reproject_disparity_to_3D(disparity, q)+ expected = torch.tensor([[[[1.0, 2.0, 3.0]]]], device=device, dtype=dtype)+ 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.+ 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(+ 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.+ 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))++ 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+ # the left and right cameras, which is taken into account here", and Q[3, 3] = fy * (cx_left -+ # cx_right) exists for exactly that case -- but the constructor requires the two camera matrices to be+ # equal outside the last column, so cx_left and cx_right can never differ and Q[3, 3] is always 0.+ # Snippet used to generate expected: StereoCamera(left, right) with the right camera's cx set to 5.0+ # recorded in original commit 1a96bfd1 (torch 2.14.0) -> StereoException("Expected+ # 'left_rectified_camera' and 'rectified_right_camera' to havesame parameters except for the last+ # column.") on cpu for float32, float64, float16 and bfloat16 and on mps for float32 and float16; on the+ # accepted camera, cx_left == cx_right (torch.equal True) and Q[3, 3] == 0.0.+ # Pins the CURRENT behavior; NOT a contract; 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)+ cam = self._asymmetric_stereo(device, dtype)+ 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.+ 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,+ )+ mixed = StereoCamera(left, mixed_right)+ self.assert_close(mixed.tx, torch.tensor([0.5, -0.5], device=device, dtype=dtype))+ 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)+ 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_wart_stereo_accepts_a_four_by_four_pair_4270(self, device, dtype):+ # Wart pin for kornia#4270: the per-camera shape check compares+ # ``shape[:1]`` -- the batch dimension alone -- with (3, 4) instead of ``shape[-2:]``, so it can never+ # fire. Only the rank check does any work: an unbatched (3, 4) pair is rejected for having 2 dimensions+ # rather than 3, while a (B, 4, 4) pair -- a projection matrix that kept its homogeneous bottom row --+ # sails through. The extra row is then ignored, and Q comes out (B, 4, 4) and EQUAL to the Q of the+ # (B, 3, 4) pair, so what is wrong here is the acceptance, not the shape of Q.+ # Snippet used to generate expected: StereoCamera(left, right) with a [0, 0, 0, 1] row appended to each+ # camera, recorded in original commit 1a96bfd1 (torch 2.14.0) -> accepted, Q shape (1, 4, 4) and+ # torch.equal to the (1, 3, 4) pair's Q; the unbatched pair raises StereoException("Expected+ # 'rectified_left_camera' to have 3 dimensions. Got 2."). 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.+ cam = self._asymmetric_stereo(device, dtype)+ bottom = torch.tensor([[[0.0, 0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ square = StereoCamera(+ torch.cat([cam.rectified_left_camera, bottom], dim=-2),+ torch.cat([cam.rectified_right_camera, bottom], dim=-2),+ )+ assert square.rectified_left_camera.shape == (1, 4, 4)+ assert square.Q.shape == (1, 4, 4)+ assert cam.Q.shape == (1, 4, 4)+ assert torch.equal(square.Q, cam.Q)+ with pytest.raises(StereoException, match="to have 3 dimensions"):+ StereoCamera(cam.rectified_left_camera[0], cam.rectified_right_camera[0])++ def test_wart_stereo_rejects_an_empty_batch_4281(self, device, dtype):+ # Wart pin for kornia#4281: ``torch.all`` of an empty tensor is True, so the+ # sign guard fires on an empty batch and B = 0 is rejected with a message about a tensor that has no+ # elements at all. kornia's degenerate-shape convention is empty in, empty out; the non-empty rig on the+ # same code path is accepted.+ # The match is on the EMPTY tensor in the message, not on "to be negative", because the all-positive rig+ # pinned above raises the same sentence -- ``Got tensor([50.])`` -- so a looser match would not tell the+ # two apart.+ # Snippet used to generate expected: StereoCamera(zeros(0, 3, 4), zeros(0, 3, 4)) recorded in+ # original commit 1a96bfd1 (torch 2.14.0) -> StereoException("Expected :math:`T_x * f_x` to be negative. Got+ # tensor([]).") on cpu float32, "... Got tensor([], dtype=torch.float64)." / "torch.float16" /+ # "torch.bfloat16" on the other cpu cells and "... Got tensor([], device='mps:0')." on mps -- so the+ # regex stops before the closing bracket. The all-positive rig raises "... Got tensor([50.])" in the+ # same cells and does not match it.+ # Pins the CURRENT behavior; NOT a contract; delete when #4281 is repaired.+ with pytest.raises(StereoException, match=r"Got tensor\(\[\]"):+ StereoCamera(+ torch.zeros(0, 3, 4, device=device, dtype=dtype), torch.zeros(0, 3, 4, device=device, dtype=dtype)+ )+ assert self._asymmetric_stereo(device, dtype, batch=2).Q.shape == (2, 4, 4)diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex 0ef1188d2..5cbf1b750 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -19,10 +19,63 @@ import pytestimport torchimport kornia+from kornia.core.exceptions import BaseError, ShapeError+from kornia.geometry.camera import PinholeCamera+from kornia.geometry.depth import (+ DepthWarper,+ depth_from_disparity,+ depth_from_plane_equation,+ depth_to_3d,+ depth_to_3d_v2,+ depth_to_normals,+ depth_warp,+ unproject_meshgrid,+ warp_frame_depth,+)from testing.base import BaseTester+def _k_asymmetric(device, dtype, fy=100.0):+ """Return (1, 3, 3) intrinsics with fx = 100, cx = 4, cy = 3 and a caller-chosen fy.++ cx != cy, so a row/column swap moves x and y by different amounts; fy is a parameter so a pin can vary one+ intrinsic at a time instead of proving its claim only on a symmetric camera.+ """+ return torch.tensor([[[100.0, 0.0, 4.0], [0.0, fy, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+++def _k44_warp(device, dtype):+ """Return the (1, 4, 4) PinholeCamera intrinsics matching ``_k53_warp``: fx = fy = 1, cx = 2, cy = 1.5."""+ return torch.tensor(+ [[[1.0, 0.0, 2.0, 0.0], [0.0, 1.0, 1.5, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],+ device=device,+ dtype=dtype,+ )+++def _k53_warp(device, dtype):+ """Return the (1, 3, 3) intrinsics used by the warp pins: fx = fy = 1, cx = 2, cy = 1.5.++ Unit focal lengths make a one-unit x translation move the sampling point by exactly one pixel at depth 1,+ which is what turns the warp-direction claim into an integer-valued pin.+ """+ return torch.tensor([[[1.0, 0.0, 2.0], [0.0, 1.0, 1.5], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+++def _eye4(device, dtype):+ return torch.eye(4, device=device, dtype=dtype)[None]+++def _tx_plus_one(device, dtype):+ """Return the (1, 4, 4) rigid transform with R = I and t = (1, 0, 0)."""+ return torch.tensor(+ [[[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],+ device=device,+ dtype=dtype,+ )++class TestDepthTo3d(BaseTester):def test_smoke(self, device, dtype):depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)@@ -180,6 +233,189 @@ class TestDepthTo3d(BaseTester):# evaluate function gradientself.gradcheck(kornia.geometry.depth.depth_to_3d, (depth, camera_matrix))+ def test_convention_pixel_origin_is_the_integer_centre(self, device, dtype):+ # Convention pin: pixel (0, 0) unprojects as+ # ((0 - cx) d / fx, (0 - cy) d / fy, d). kornia's pixel grid puts the centre of the first pixel at the+ # INTEGER coordinate 0 (the OpenCV convention that create_meshgrid already pins in+ # tests/geometry/test_conversions.py), and ``depth`` here is the camera-frame z, not a ray length.+ # A half-pixel (COLMAP) grid, whose first pixel centre is 0.5, would give+ # ((0.5 - 4) * 2 / 100, (0.5 - 3) * 2 / 100, 2) = (-0.07, -0.05, 2) instead -- a 0.01 gap in x and y,+ # far outside every dtype tolerance used here. cx = 4 != cy = 3 and H = 2 != W = 3, so a transposed+ # reading of the grid also changes the literal. depth_to_3d_v2 answers the same question in the+ # (B, H, W, 3) layout and gives the same triple.+ # Snippet used to generate expected: depth_to_3d(full((1, 1, 2, 3), 2.0), K)[0, :, 0, 0] executed+ # 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> cpu float32 and float64+ # [-0.07999999821186066, -0.05999999865889549, 2.0], cpu float16 [-0.08001708984375, -0.05999755859375,+ # 2.0], cpu bfloat16 [-0.080078125, -0.06005859375, 2.0]; mps float32 and float16 reproduce their cpu+ # cells exactly.+ camera_matrix = _k_asymmetric(device, dtype)+ depth = torch.full((1, 1, 2, 3), 2.0, device=device, dtype=dtype)+ expected = torch.tensor([-0.08, -0.06, 2.0], device=device, dtype=dtype)+ self.assert_close(depth_to_3d(depth, camera_matrix)[0, :, 0, 0], expected)+ self.assert_close(depth_to_3d_v2(depth[:, 0], camera_matrix)[0, 0, 0], expected)++ def test_convention_integer_depth_follows_intrinsics_dtype(self, device, dtype):+ # Integer sensor depth follows the floating calibration dtype for both layouts.+ # At pixel (0, 0): ((0 - 4) * 2 / 100, (0 - 3) * 2 / 100, 2).+ camera_matrix = _k_asymmetric(device, dtype)+ for int_dtype in (torch.int64, torch.int32):+ depth = torch.full((1, 1, 2, 3), 2, device=device, dtype=int_dtype)+ points = depth_to_3d(depth, camera_matrix)+ points_v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)+ assert points.dtype == dtype+ assert points_v2.dtype == dtype+ expected = torch.tensor([-0.08, -0.06, 2.0], device=device, dtype=dtype)+ self.assert_close(points[0, :, 0, 0], expected)+ self.assert_close(points_v2[0, 0, 0], expected)++ def test_convention_depth_to_3d_and_v2_agree_up_to_layout(self, device, dtype):+ # Convention pin: the two functions compute the same points in two+ # layouts -- (B, 3, H, W) for depth_to_3d, (B, H, W, 3) for depth_to_3d_v2 -- and are byte-identical+ # after the permutation, under an asymmetric camera (fx = 100 != fy = 50, cx = 4 != cy = 3), H = 3 != W+ # = 5 and a depth that varies at every pixel. The permutation is load-bearing rather than decorative:+ # the two flattened buffers are NOT equal, so a comparison that skipped the permute would fail here.+ # The W = 1 regression (kornia#4278) is pinned below too.+ # Snippet used to generate expected: torch.equal(depth_to_3d(d, K).permute(0, 2, 3, 1),+ # depth_to_3d_v2(d[:, 0], K)) and torch.equal(v1.reshape(-1), v2.reshape(-1)) on the depth ramp 1..15+ # executed 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> True and False respectively, on cpu for+ # float32, float64, float16 and bfloat16 and on mps for float32 and float16.+ camera_matrix = _k_asymmetric(device, dtype, fy=50.0)+ depth = torch.tensor(+ [[[[1.0, 2.0, 3.0, 4.0, 5.0], [6.0, 7.0, 8.0, 9.0, 10.0], [11.0, 12.0, 13.0, 14.0, 15.0]]]],+ device=device,+ dtype=dtype,+ )+ v1 = depth_to_3d(depth, camera_matrix)+ v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)+ assert v1.shape == (1, 3, 3, 5)+ assert v2.shape == (1, 3, 5, 3)+ assert torch.equal(v1.permute(0, 2, 3, 1), v2)+ assert not torch.equal(v1.reshape(-1), v2.reshape(-1))++ def test_convention_depth_to_3d_v2_keeps_the_w_one_axis_4278(self, device, dtype):+ # Regression for #4278 (repaired by #4298): a single column retains its width axis and agrees across+ # layouts, and the two public consumers of unproject_meshgrid that inherited the squeeze --+ # depth_to_normals and warp_frame_depth -- keep the axis too. At H = 1 the normals' VALUE is+ # device-dependent (all-zero on cpu, [-1, -1, -1] on mps, nan in float16), so only shapes are asserted+ # for those two.+ camera_matrix = _k_asymmetric(device, dtype)+ depth = torch.full((1, 1, 3, 1), 2.0, device=device, dtype=dtype)+ v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)+ assert v2.shape == (1, 3, 1, 3)+ assert torch.equal(depth_to_3d(depth, camera_matrix).permute(0, 2, 3, 1), v2)+ assert depth_to_normals(depth, camera_matrix).shape == (1, 3, 3, 1)+ assert depth_to_normals(depth.transpose(-1, -2).contiguous(), camera_matrix).shape == (1, 3, 1, 3)+ assert warp_frame_depth(depth, depth, _eye4(device, dtype), camera_matrix).shape == (1, 1, 3, 1)++ def test_convention_xyz_grid_bypasses_the_camera_matrix(self, device, dtype):+ # Convention pin: with ``xyz_grid`` given, depth_to_3d_v2 never reads ``camera_matrix`` beyond its+ # (*, 3, 3) guard, so the bare (3, 3) that the no-grid call rejects inside unproject_meshgrid (#4271)+ # is silently accepted here and the result is the batched call's, bit for bit.+ # Snippet used to generate expected: depth_to_3d_v2(ones(1, 3, 5), K[0], xyz_grid=unproject_meshgrid(3,+ # 5, K)) executed 2026-09-08 at commit 089daad9 (torch 2.14.0) -> shape (1, 3, 5, 3), torch.equal to+ # depth_to_3d_v2(ones(1, 3, 5), K); depth_to_3d_v2(ones(1, 3, 5), K[0]) -> ShapeError. Every cpu dtype+ # and mps float32/float16.+ camera_matrix = _k_asymmetric(device, dtype)+ depth = torch.ones(1, 3, 5, device=device, dtype=dtype)+ grid = unproject_meshgrid(3, 5, camera_matrix, device=device, dtype=dtype)+ bypassed = depth_to_3d_v2(depth, camera_matrix[0], xyz_grid=grid)+ assert bypassed.shape == (1, 3, 5, 3)+ assert torch.equal(bypassed, depth_to_3d_v2(depth, camera_matrix))+ with pytest.raises(ShapeError):+ depth_to_3d_v2(depth, camera_matrix[0])+++class TestUnprojectMeshgrid(BaseTester):+ def test_convention_returns_b_h_w_3_and_equals_depth_to_3d_v2_at_depth_one(self, device, dtype):+ # Convention pin: unproject_meshgrid is depth_to_3d_v2's+ # cache: it returns the per-pixel ray through each pixel at depth 1 in the (*, H, W, 3) layout, so+ # multiplying it by a depth map reproduces depth_to_3d_v2 exactly. The grid is not constant -- pixel+ # (0, 0) and pixel (1, 2) differ -- so the equality is not the trivial one.+ # The asymmetric arm varies ONE intrinsic: with fy = 50 instead of 100 only the y component of the+ # pixel-(1, 0) ray changes, which is what fixes fy as the divisor of the ROW index.+ # Snippet used to generate expected: unproject_meshgrid(2, 3, K, device=..., dtype=...) and+ # torch.equal(that, depth_to_3d_v2(ones(1, 2, 3), K)) executed 2026-09-06 at commit 1a96bfd1+ # (torch 2.14.0) -> shape (1, 2, 3, 3), pixel (0, 0) [-0.03999999910593033, -0.029999999329447746, 1.0]+ # and True, on cpu for float32, float64, float16 and bfloat16 and on mps for float32 and float16; with+ # fy = 50, pixel (0, 0) [-0.04, -0.06, 1.0] and pixel (1, 0) [-0.04, -0.04, 1.0].+ camera_matrix = _k_asymmetric(device, dtype)+ grid = unproject_meshgrid(2, 3, camera_matrix, device=device, dtype=dtype)+ assert grid.shape == (1, 2, 3, 3)+ self.assert_close(grid[0, 0, 0], torch.tensor([-0.04, -0.03, 1.0], device=device, dtype=dtype))+ self.assert_close(grid[0, 1, 2], torch.tensor([-0.02, -0.02, 1.0], device=device, dtype=dtype))+ assert torch.equal(grid, depth_to_3d_v2(torch.ones(1, 2, 3, device=device, dtype=dtype), camera_matrix))+ asymmetric = unproject_meshgrid(2, 3, _k_asymmetric(device, dtype, fy=50.0), device=device, dtype=dtype)+ self.assert_close(asymmetric[0, 0, 0], torch.tensor([-0.04, -0.06, 1.0], device=device, dtype=dtype))+ self.assert_close(asymmetric[0, 1, 0], torch.tensor([-0.04, -0.04, 1.0], device=device, dtype=dtype))++ def test_wart_unproject_meshgrid_rejects_unbatched_intrinsics_4271(self, device, dtype):+ # Wart pin for kornia#4271: the guard is written ["*", "3", "3"],+ # which admits a bare (3, 3) -- but the body then does ``camera_matrix[:, None, None]``, which on a 2-D+ # tensor produces a (3, 1, 1, 3) and trips a LATER check whose message describes that shape rather than+ # the one the caller passed. Singleton extra axes pass through, while non-singleton ones can+ # either fail or accidentally broadcast against the width. They are not a supported batch layout.+ # Snippet used to generate expected: unproject_meshgrid(2, 3, K, device=..., dtype=...) at four K+ # shapes, executed 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> (3, 3): ShapeError("Shape mismatch at+ # dimension 0: expected 3, got 1. ... Actual shape: [3, 1, 1, 3]"); (1, 3, 3): (1, 2, 3, 3);+ # (2, 1, 3, 3): (2, 1, 2, 3, 3); (2, 2, 3, 3): RuntimeError("The size of tensor a (3) must match the+ # size of tensor b (2) at non-singleton dimension 3"). All four on cpu for float32, float64, float16+ # and bfloat16 and on mps for float32 and float16.+ # Pins the CURRENT behavior; NOT a contract; delete when #4271 is repaired.+ camera_matrix = _k_asymmetric(device, dtype)+ with pytest.raises(ShapeError) as errinfo:+ unproject_meshgrid(2, 3, camera_matrix[0], device=device, dtype=dtype)+ assert "[3, 1, 1, 3]" in str(errinfo.value)+ assert unproject_meshgrid(2, 3, camera_matrix, device=device, dtype=dtype).shape == (1, 2, 3, 3)+ singleton = camera_matrix.expand(2, 3, 3).unsqueeze(1).contiguous()+ assert singleton.shape == (2, 1, 3, 3)+ assert unproject_meshgrid(2, 3, singleton, device=device, dtype=dtype).shape == (2, 1, 2, 3, 3)+ with pytest.raises(RuntimeError, match="must match the size of tensor"):+ unproject_meshgrid(2, 3, singleton.expand(2, 2, 3, 3).contiguous(), device=device, dtype=dtype)++ def test_wart_unproject_meshgrid_extra_camera_axis_broadcasts_over_columns_4271(self, device, dtype):+ # Wart pin for kornia#4271: the ["*", "3", "3"] guard admits a (2, 3, 3, 3) camera as readily as a+ # (2, 1, 3, 3), and an extra axis of size 3 == W then broadcasts against the pixel width instead of+ # being rejected, so each COLUMN is unprojected with a different cx. The (2, 2, 3, 3) case in the pin+ # above raises; this one silently succeeds. Neither is a supported layout.+ # Snippet used to generate expected: unproject_meshgrid(2, 3, K) with K = eye(3).expand(2, 3, 3, 3) and+ # K[:, :, 0, 2] = [0, 2, 4], executed 2026-09-08 at commit 26ddb21e (torch 2.14.0) -> shape+ # (2, 1, 2, 3, 3) with row 0 [[0, 0, 1], [-1, 0, 1], [-2, 0, 1]] on cpu for float32, float64, float16+ # and bfloat16 and on mps for float32 and float16.+ # Pins the CURRENT behavior; NOT a contract; delete when #4271 is repaired.+ camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3, 3).clone()+ camera_matrix[:, :, 0, 2] = torch.tensor([0.0, 2.0, 4.0], device=device, dtype=dtype)+ grid = unproject_meshgrid(2, 3, camera_matrix, device=device, dtype=dtype)+ assert grid.shape == (2, 1, 2, 3, 3)+ # Each column uses a different cx: u - cx = [0, -1, -2].+ expected = torch.tensor(+ [+ [[0.0, 0.0, 1.0], [-1.0, 0.0, 1.0], [-2.0, 0.0, 1.0]],+ [[0.0, 1.0, 1.0], [-1.0, 1.0, 1.0], [-2.0, 1.0, 1.0]],+ ],+ device=device,+ dtype=dtype,+ )+ self.assert_close(grid, expected.expand(2, 1, 2, 3, 3))++ @pytest.mark.xfail(+ strict=True, reason="kornia#4271: the guard reports a [3, 1, 1, 3] shape the caller never passed"+ )+ def test_convention_unproject_meshgrid_error_names_the_shape_the_caller_passed_4271(self, device, dtype):+ # Intended contract, asserted as a strict xfail so the repair makes it XPASS and forces this mark out:+ # whatever unproject_meshgrid decides about (3, 3), the error a caller sees has to name the shape the+ # caller actually passed. Today it names a (3, 1, 1, 3) built three lines into the body.+ # Settled by #4271's Expected section, which calls exactly this -- "the guard should reject a bare+ # (3, 3) at the guard rather than three lines later with a message about a (3, 1, 1, 3) shape the caller+ # never passed" -- a focused fix, welcome as a PR. #4271 deliberately does NOT settle whether (3, 3) is+ # then accepted, so this pin asserts only the message, not the acceptance: a repair that accepts (3, 3)+ # by unsqueezing it passes through the ``try`` and XPASSes just as a repair of the message does.+ camera_matrix = _k_asymmetric(device, dtype)+ try:+ unproject_meshgrid(2, 3, camera_matrix[0], device=device, dtype=dtype)+ except ShapeError as err:+ assert "[3, 3]" in str(err)+ assert "[3, 1, 1, 3]" not in str(err)+class TestDepthToNormals(BaseTester):def test_smoke(self, device, dtype):@@ -275,6 +511,42 @@ class TestDepthToNormals(BaseTester):# evaluate function gradientself.gradcheck(kornia.geometry.depth.depth_to_normals, (depth, camera_matrix))+ def test_convention_normals_point_away_from_the_camera_and_x_tracks_the_column(self, device, dtype):+ # Convention pin: depth_to_normals takes+ # the cross product of the spatial gradients of the unprojected point cloud in the order dx x dy, so a+ # fronto-parallel plane gets the unit normal (0, 0, 1) -- +z points AWAY from the camera, along the+ # viewing direction, not back towards it. The two ramps fix which axis is which: a depth that grows with+ # the COLUMN tilts the normal towards -x, a depth that grows with the ROW tilts it towards -y. The+ # magnitudes are dtype-dependent (float32 -0.99995, float16 -1.0), so this pin asserts the sign pattern+ # with separators far from every measured value, and only the flat plane as an exact triple.+ # The map is 3 x 4 with fx = 100 != fy = 50, so H != W and the two focal lengths differ: a transposed+ # depth map does not even have the right shape here, and a reading that swapped fx and fy would move the+ # ramp normals.+ # Snippet used to generate expected: depth_to_normals(depth, K)[0, :, 1, 1] on the 3 x 4 map executed+ # 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> flat plane exactly [0.0, 0.0, 1.0] (cpu+ # float32/float16/bfloat16) and [0.0, -0.0, 1.0] (cpu float64, mps float32); column ramp+ # [-0.9999499917030334, 0.0, -0.009999499656260014] on cpu float32, [-1.0, 0.0, -0.0099945068359375] on+ # cpu float16, [-1.0, 0.0, -0.010009765625] on cpu bfloat16 and [-0.9999499917030334, 3.49e-08,+ # -0.009999497793614864] on mps float32; row ramp [0.0, -1.0, 0.0] on cpu and+ # [0.0, -1.0, -4.656612873077393e-10] on mps float32.+ camera_matrix = _k_asymmetric(device, dtype, fy=50.0)+ flat = depth_to_normals(torch.full((1, 1, 3, 4), 2.0, device=device, dtype=dtype), camera_matrix)+ assert flat.shape == (1, 3, 3, 4)+ self.assert_close(+ flat[0, :, 1, 1], torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype), atol=0.0, rtol=0.0+ )+ columns = torch.arange(4.0, device=device, dtype=dtype) + 1.0+ by_column = depth_to_normals(columns.view(1, 1, 1, 4).expand(1, 1, 3, 4).contiguous(), camera_matrix)[+ 0, :, 1, 1+ ]+ assert by_column[0].item() < -0.9+ assert by_column[1].abs().item() < 0.01+ assert by_column[2].item() < -0.001+ rows = torch.arange(3.0, device=device, dtype=dtype) + 1.0+ by_row = depth_to_normals(rows.view(1, 1, 3, 1).expand(1, 1, 3, 4).contiguous(), camera_matrix)[0, :, 1, 1]+ assert by_row[1].item() < -0.9+ assert by_row[0].abs().item() < 0.01+class TestWarpFrameDepth(BaseTester):def test_smoke(self, device, dtype):@@ -339,6 +611,21 @@ class TestWarpFrameDepth(BaseTester):) # default is normalize_points=Falseself.assert_close(image_dst, image_dst_expected, rtol=1e-3, atol=1e-3)+ def test_convention_subpixel_border_blends_with_zero_padding(self, device, dtype):+ # Convention pin: the baked padding_mode="zeros" is a zero EXTENSION of the image, not a mask on the+ # sampling point: a quarter-pixel translation samples the last column at x = 2.25, and bilinear+ # interpolation blends the in-bounds neighbour (1.0, weight 0.75) with the padded zero (weight 0.25).+ # Snippet used to generate expected: warp_frame_depth(ones(1, 1, 2, 3), ones, T, eye(3)) with+ # T[0, 0, 3] = 0.25, executed 2026-09-08 at commit 26ddb21e (torch 2.14.0) -> [[1, 1, 0.75], [1, 1, 0.75]]+ # on cpu for float32, float64, float16 and bfloat16 and on mps for float32 and float16.+ image = torch.ones(1, 1, 2, 3, device=device, dtype=dtype)+ camera_matrix = torch.eye(3, device=device, dtype=dtype)[None]+ transform = torch.eye(4, device=device, dtype=dtype)[None]+ transform[0, 0, 3] = 0.25+ result = warp_frame_depth(image, torch.ones_like(image), transform, camera_matrix)+ expected = torch.tensor([[[[1.0, 1.0, 0.75], [1.0, 1.0, 0.75]]]], device=device, dtype=dtype)+ self.assert_close(result, expected)+def test_translation_normalized(self, device, dtype):# this is for normalize_points=Trueimage_src = torch.tensor(@@ -393,6 +680,380 @@ class TestWarpFrameDepth(BaseTester):# evaluate function gradientself.gradcheck(kornia.geometry.depth.warp_frame_depth, (image_src, depth_dst, src_trans_dst, camera_matrix))+ def test_convention_src_trans_dst_moves_the_sampling_point(self, device, dtype):+ # Convention pin: warp_frame_depth reads the depth in+ # the DESTINATION frame and the image in the SOURCE frame, and ``src_trans_dst`` maps destination-frame+ # points into the source frame. With fx = fy = 1 and depth 1, a +1 translation in x therefore samples+ # image_src one pixel to the RIGHT of each destination pixel: out[u] = image_src[u + 1], and the last+ # column samples outside the image, which the baked ``padding_mode="zeros"`` fills with 0.+ # An identity transform is frame-invariant and proves nothing about the direction, so it is used only as+ # the contrast: it returns the input byte for byte, while the +1 transform moves it by up to 19.0.+ # Snippet used to generate expected: warp_frame_depth(arange(20).view(1, 1, 4, 5), ones(1, 1, 4, 5), T,+ # K)[0, 0, 0] with T = eye(4) except T[0, 0, 3] = 1, executed 2026-09-06 at commit 1a96bfd1+ # (torch 2.14.0) -> [1.0, 2.0, 3.0, 4.0, 0.0] on cpu for float32, float64, float16 and bfloat16 and on+ # mps for float32 and float16; the identity call is torch.equal to the input in every one of those+ # cells, and the +1 call deviates from the input by 19.0.+ camera_matrix = _k53_warp(device, dtype)+ image_src = torch.arange(20.0, device=device, dtype=dtype).view(1, 1, 4, 5)+ depth_dst = torch.ones(1, 1, 4, 5, device=device, dtype=dtype)+ warped = warp_frame_depth(image_src, depth_dst, _tx_plus_one(device, dtype), camera_matrix)+ self.assert_close(warped[0, 0, 0], torch.tensor([1.0, 2.0, 3.0, 4.0, 0.0], device=device, dtype=dtype))+ assert (warped - image_src).abs().max().item() > 0.5+ assert torch.equal(warp_frame_depth(image_src, depth_dst, _eye4(device, dtype), camera_matrix), image_src)++ def test_wart_warp_frame_depth_rejects_an_empty_batch_4281(self, device, dtype):+ # Wart pin for kornia#4281: an empty batch raises a bare+ # ZeroDivisionError from transform_points (0 // 0 in its batch-repeat count) rather than returning an empty+ # result, although+ # every shape guard on the way in accepts B = 0 and depth_to_3d -- the same computation in the other+ # layout -- handles it. kornia's degenerate-shape convention is empty in, empty out.+ # Snippet used to generate expected: warp_frame_depth(zeros(0, 2, 4, 5), ones(0, 1, 4, 5),+ # zeros(0, 4, 4), zeros(0, 3, 3)) executed 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) ->+ # ZeroDivisionError("integer division or modulo by zero") on cpu for float32, float64, float16 and+ # bfloat16 and on mps for float32 and float16; depth_to_3d(zeros(0, 1, 4, 5), zeros(0, 3, 3)) returns+ # shape (0, 3, 4, 5) in the same cells.+ # Pins the CURRENT behavior; NOT a contract; delete when #4281 is repaired.+ with pytest.raises(ZeroDivisionError, match="integer division or modulo by zero"):+ warp_frame_depth(+ torch.zeros(0, 2, 4, 5, device=device, dtype=dtype),+ torch.ones(0, 1, 4, 5, device=device, dtype=dtype),+ torch.zeros(0, 4, 4, device=device, dtype=dtype),+ torch.zeros(0, 3, 3, device=device, dtype=dtype),+ )+ empty = depth_to_3d(+ torch.zeros(0, 1, 4, 5, device=device, dtype=dtype), torch.zeros(0, 3, 3, device=device, dtype=dtype)+ )+ assert empty.shape == (0, 3, 4, 5)+++class TestDepthWarperConventions(BaseTester):+ """Convention and wart pins for :class:`~kornia.geometry.depth.DepthWarper` and ``depth_warp``."""++ @staticmethod+ def _warper(device, dtype, dst_extrinsics, src_extrinsics):+ """Build a DepthWarper for a 4x5 image and run compute_projection_matrix on the source camera."""+ intrinsics = _k44_warp(device, dtype)+ height = torch.tensor([4], device=device)+ width = torch.tensor([5], device=device)+ warper = DepthWarper(PinholeCamera(intrinsics.clone(), dst_extrinsics.clone(), height, width), 4, 5)+ warper.compute_projection_matrix(PinholeCamera(intrinsics.clone(), src_extrinsics.clone(), height, width))+ return warper++ @staticmethod+ def _random_warp_inputs(device, dtype, batch, seed, rotate):+ """Generate a reproducible random camera pair.++ Everything is drawn on cpu from an explicitly seeded generator and moved to ``device`` afterwards, so+ the fixture is the same tensor on every device and dtype.+ """+ generator = torch.Generator().manual_seed(seed)+ height, width = 4, 5+ fx = torch.rand(batch, generator=generator) * 2 + 1.0+ fy = torch.rand(batch, generator=generator) * 2 + 1.0+ cx = torch.rand(batch, generator=generator) * 2 + 1.0+ cy = torch.rand(batch, generator=generator) * 2 + 1.0+ k3 = torch.zeros(batch, 3, 3)+ k3[:, 0, 0], k3[:, 1, 1], k3[:, 0, 2], k3[:, 1, 2], k3[:, 2, 2] = fx, fy, cx, cy, 1.0+ k4 = torch.eye(4)[None].repeat(batch, 1, 1).contiguous()+ k4[:, :3, :3] = k3+ axis_angle = torch.rand(batch, 3, generator=generator) * 0.2 if rotate else torch.zeros(batch, 3)+ transform = torch.eye(4)[None].repeat(batch, 1, 1).contiguous()+ transform[:, :3, :3] = kornia.geometry.conversions.axis_angle_to_rotation_matrix(axis_angle)+ transform[:, :3, 3] = torch.rand(batch, 3, generator=generator) * 0.4 - 0.2+ image = torch.rand(batch, 2, height, width, generator=generator)+ depth = torch.rand(batch, 1, height, width, generator=generator) + 1.0+ return (+ image.to(device, dtype),+ depth.to(device, dtype),+ transform.to(device, dtype),+ k3.to(device, dtype),+ k4.to(device, dtype),+ torch.tensor([height] * batch, device=device),+ torch.tensor([width] * batch, device=device),+ )++ def test_convention_projection_matrix_is_k_dst_times_dst_trans_src(self, device, dtype):+ # Convention pin: the class docstring's+ # ``P_src^{dst} = K_dst * T_src^{dst}`` is exactly what compute_projection_matrix stores --+ # ``_dst_proj_src == K_dst @ (E_dst @ inv(E_src))``, byte for byte, with K_dst and E_dst taken from the+ # DESTINATION camera passed to the constructor and E_src from the camera passed to+ # compute_projection_matrix. The extrinsics are inverted, not transposed: E_src here is a 90-degree+ # rotation about z with a translation, so the transposed reading (which ignores the translation and is+ # what a "R^T" shortcut would give) deviates from the stored matrix by 3.75.+ # The source inverse is written out as a literal rather than computed with torch.linalg.inv, so the pin+ # runs unchanged on mps and in half precision.+ # Snippet used to generate expected: torch.equal(warper._dst_proj_src, K44 @ (E_dst @ E_src_inv)) and+ # (K44 @ (E_dst @ E_src.transpose(-1, -2)) - K44 @ (E_dst @ E_src_inv)).abs().max() executed 2026-09-06+ # at commit 1a96bfd1 (torch 2.14.0) -> True and 3.75 on cpu for float32, float64, float16 and bfloat16 and+ # on mps for float32 and float16; the identity-source arm is True in the same cells.+ # The identity-source arm uses the ROTATION as the destination camera on purpose: a pure x translation+ # commutes with this K (K @ E - E @ K measures exactly 0.0), so it could not tell K @ E_dst from+ # E_dst @ K; with the rotation the two orders differ by 4.0.+ intrinsics = _k44_warp(device, dtype)+ dst_extrinsics = _tx_plus_one(device, dtype)+ src_extrinsics = torch.tensor(+ [[[0.0, -1.0, 0.0, 0.5], [1.0, 0.0, 0.0, -0.25], [0.0, 0.0, 1.0, 2.0], [0.0, 0.0, 0.0, 1.0]]],+ device=device,+ dtype=dtype,+ )+ src_inverse = torch.tensor(+ [[[0.0, 1.0, 0.0, 0.25], [-1.0, 0.0, 0.0, 0.5], [0.0, 0.0, 1.0, -2.0], [0.0, 0.0, 0.0, 1.0]]],+ device=device,+ dtype=dtype,+ )+ assert torch.equal(src_extrinsics @ src_inverse, _eye4(device, dtype))+ expected = intrinsics @ (dst_extrinsics @ src_inverse)+ warper = self._warper(device, dtype, dst_extrinsics, src_extrinsics)+ assert torch.equal(warper._dst_proj_src, expected)+ transposed_reading = intrinsics @ (dst_extrinsics @ src_extrinsics.transpose(-1, -2))+ assert (transposed_reading - expected).abs().max().item() > 0.5+ identity_source = self._warper(device, dtype, src_extrinsics, _eye4(device, dtype))+ assert torch.equal(identity_source._dst_proj_src, intrinsics @ src_extrinsics)+ assert (src_extrinsics @ intrinsics - intrinsics @ src_extrinsics).abs().max().item() > 0.5++ def test_convention_forward_returns_b_c_h_w_and_align_corners_defaults_to_true(self, device, dtype):+ # Convention pin: forward takes the depth in+ # the reference frame and the patch in the destination frame and returns a (B, C, H, W) tensor with the+ # patch's channel count, for any C. ``align_corners`` defaults to True; DepthWarper exposes all three+ # grid_sample knobs (mode, padding_mode, align_corners) while warp_frame_depth bakes all three in and has+ # no such parameter at all, which this pin records rather than repairs.+ # The shape claim is backed by a value: an identity camera pair returns the patch byte for byte in+ # float32, so the assertion cannot be satisfied by an all-zero padded result.+ # Snippet used to generate expected: DepthWarper(...).compute_projection_matrix(...)(ones(1, 1, 4, 5),+ # patch) for patch = arange(40).view(1, 2, 4, 5) and arange(100).view(1, 5, 4, 5), executed 2026-09-06+ # at commit 1a96bfd1 (torch 2.14.0) -> shapes (1, 2, 4, 5) and (1, 5, 4, 5) in every cell, and+ # torch.equal to the patch on cpu for float32, float16 and bfloat16 and on mps for float32 and float16;+ # in float64 the round trip is not bit-exact (the grid closes to 1e-12), so the value arm uses+ # assert_close rather than torch.equal. The identity pair alone would be frame-invariant, so a second+ # arm runs the same two channel counts through a +1 x translation and checks the output actually moved+ # (measured deviation from the patch: 39.0 for C = 2 and 99.0 for C = 5, cpu float32).+ identity = _eye4(device, dtype)+ depth_src = torch.ones(1, 1, 4, 5, device=device, dtype=dtype)+ warper = self._warper(device, dtype, identity, identity)+ assert warper.align_corners is True+ assert (+ DepthWarper(+ PinholeCamera(+ _k44_warp(device, dtype),+ identity,+ torch.tensor([4], device=device),+ torch.tensor([5], device=device),+ ),+ 4,+ 5,+ ).align_corners+ is True+ )+ moving = self._warper(device, dtype, _tx_plus_one(device, dtype), identity)+ for channels in (2, 5):+ patch = torch.arange(float(20 * channels), device=device, dtype=dtype).view(1, channels, 4, 5)+ warped = warper(depth_src, patch)+ assert warped.shape == (1, channels, 4, 5)+ self.assert_close(warped, patch)+ shifted = moving(depth_src, patch)+ assert shifted.shape == (1, channels, 4, 5)+ assert (shifted - patch).abs().max().item() > 0.5++ def test_convention_warp_grid_requires_compute_projection_matrix_first(self, device, dtype):+ # Convention pin: DepthWarper is a two-step API. Until+ # compute_projection_matrix has been called there is no relative pose, and both warp_grid and forward+ # raise ValueError("Please, call compute_projection_matrix."), while compute_subpixel_step raises+ # RuntimeError from the None projection matrix instead. Afterwards warp_grid returns the+ # grid_sample-ready NORMALIZED coordinates, (B, H, W, 2), in which pixel (0, 0) is (-1, -1) and pixel+ # (H - 1, W - 1) is (1, 1) -- not the integer pixel grid that DepthWarper.grid itself holds.+ # Snippet used to generate expected: DepthWarper(cam, 4, 5).warp_grid(ones(1, 1, 4, 5)) and the same+ # instance called as a module, executed 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> ValueError with+ # that message; compute_subpixel_step on the same bare instance -> RuntimeError("Expected torch.Tensor,+ # but got None Type from the projection matrix"); after compute_projection_matrix, shape (1, 4, 5, 2)+ # with first pixel [-1.0, -1.0] and last pixel [1.0, 1.0]. All hold on cpu for float32, float64,+ # float16 and bfloat16 and on mps for float32 and float16.+ identity = _eye4(device, dtype)+ depth_src = torch.ones(1, 1, 4, 5, device=device, dtype=dtype)+ bare = DepthWarper(+ PinholeCamera(+ _k44_warp(device, dtype), identity, torch.tensor([4], device=device), torch.tensor([5], device=device)+ ),+ 4,+ 5,+ )+ with pytest.raises(ValueError, match="Please, call compute_projection_matrix"):+ bare.warp_grid(depth_src)+ with pytest.raises(ValueError, match="Please, call compute_projection_matrix"):+ bare(depth_src, torch.zeros(1, 2, 4, 5, device=device, dtype=dtype))+ with pytest.raises(RuntimeError, match="but got None Type from the projection matrix"):+ bare.compute_subpixel_step()+ grid = self._warper(device, dtype, identity, identity).warp_grid(depth_src)+ assert grid.shape == (1, 4, 5, 2)+ self.assert_close(grid[0, 0, 0], torch.tensor([-1.0, -1.0], device=device, dtype=dtype))+ self.assert_close(grid[0, -1, -1], torch.tensor([1.0, 1.0], device=device, dtype=dtype))++ def test_convention_depth_warp_is_byte_identical_to_depth_warper(self, device, dtype):+ # Convention pin: depth_warp is a functional wrapper that constructs a+ # DepthWarper, calls compute_projection_matrix and forwards -- the results are equal bit for bit, on the+ # integer ramp and on the seeded random camera pair (random K, random rotation, B = 2). That is+ # what makes depth_warp a wrapper rather than a second implementation, unlike warp_frame_depth (pinned+ # below). The warp is a real one: it moves the image by 0.88 on the random pair.+ # Snippet used to generate expected: torch.equal(depth_warp(...), warper(...)) executed 2026-09-06 on+ # commit 1a96bfd1 (torch 2.14.0) -> True on cpu for float32, float64, float16 and bfloat16 and on mps for+ # float32 and float16, for both fixtures; the max deviation between the two is 0.0 in every cell.+ intrinsics = _k44_warp(device, dtype)+ dst_extrinsics = _tx_plus_one(device, dtype)+ identity = _eye4(device, dtype)+ height = torch.tensor([4], device=device)+ width = torch.tensor([5], device=device)+ image = torch.arange(20.0, device=device, dtype=dtype).view(1, 1, 4, 5)+ depth_src = torch.ones(1, 1, 4, 5, device=device, dtype=dtype)+ functional = depth_warp(+ PinholeCamera(intrinsics.clone(), dst_extrinsics.clone(), height, width),+ PinholeCamera(intrinsics.clone(), identity.clone(), height, width),+ depth_src,+ image,+ 4,+ 5,+ )+ assert torch.equal(functional, self._warper(device, dtype, dst_extrinsics, identity)(depth_src, image))+ assert (functional - image).abs().max().item() > 0.5+ img, dep, transform, _, k4, batch_h, batch_w = self._random_warp_inputs(device, dtype, 2, 11, True)+ batch_identity = torch.eye(4, device=device, dtype=dtype)[None].repeat(2, 1, 1).contiguous()+ warper = DepthWarper(PinholeCamera(k4.clone(), transform.clone(), batch_h, batch_w), 4, 5)+ warper.compute_projection_matrix(PinholeCamera(k4.clone(), batch_identity.clone(), batch_h, batch_w))+ by_class = warper(dep, img)+ by_function = depth_warp(+ PinholeCamera(k4.clone(), transform.clone(), batch_h, batch_w),+ PinholeCamera(k4.clone(), batch_identity.clone(), batch_h, batch_w),+ dep,+ img,+ 4,+ 5,+ )+ assert torch.equal(by_class, by_function)+ assert (by_class - img).abs().max().item() > 0.1++ def test_convention_warp_frame_depth_matches_depth_warper_without_being_bitwise_equal(self, device, dtype):+ # Convention pin: the two APIs compute the same warp+ # but not the same arithmetic -- warp_frame_depth unprojects through depth_to_3d_v2 and divides by z in+ # project_points, while DepthWarper unprojects through pixel2cam with the cached intrinsics_inverse and+ # divides in cam2pixel. They agree to the dtype tolerance and are NEVER bit-identical, on the+ # seeded random camera pair with and without rotation. Collapsing the two implementations changes bits.+ # The residual is a measured fact, not a bound, so no figure is asserted here.+ # Snippet used to generate expected: torch.equal / (a - b).abs().max() on _random_warp_inputs(2, 11,+ # True) and (2, 7, False), executed 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> equal False in every+ # cell; residual cpu float32 4.02e-07 and 5.36e-07, cpu float64 2.90e-12 and 2.25e-12, mps float32+ # 2.98e-07 and 4.77e-07.+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip(+ "half precision: the two paths diverge by 4.88e-03 (float16, seed 7) and 1.95e-02 (bfloat16, "+ "seed 11), outside the 2e-03 / 1.6e-02 assert_close tolerances; the claim is float32/float64"+ )+ for seed, rotate in ((11, True), (7, False)):+ img, dep, transform, k3, k4, batch_h, batch_w = self._random_warp_inputs(device, dtype, 2, seed, rotate)+ batch_identity = torch.eye(4, device=device, dtype=dtype)[None].repeat(2, 1, 1).contiguous()+ warper = DepthWarper(PinholeCamera(k4.clone(), transform.clone(), batch_h, batch_w), 4, 5)+ warper.compute_projection_matrix(PinholeCamera(k4.clone(), batch_identity.clone(), batch_h, batch_w))+ by_class = warper(dep, img)+ by_function = warp_frame_depth(img, dep, transform, k3)+ self.assert_close(by_function, by_class)+ assert not torch.equal(by_function, by_class)+ assert (by_class - img).abs().max().item() > 0.1++ def test_wart_warp_frame_depth_and_depth_warper_name_the_depth_frame_oppositely_4273(self, device, dtype):+ # Wart pin for kornia#4273: the two APIs produce the same+ # warp from OPPOSITE argument names, and this pin spells every argument as a KEYWORD so the clash is in+ # the source text and not only in the prose. The identical warp is written+ # warp_frame_depth(image_src=IMG, depth_dst=D, src_trans_dst=T) -- the depth is "dst"+ # DepthWarper(pinhole_dst=camera(T)).compute_projection_matrix(pinhole_src=camera(I))(+ # depth_src=D, patch_dst=IMG) -- the same depth is "src",+ # and the image the other one calls "src" is "patch_dst" here. A reader who maps "dst" to "dst" across+ # the two APIs gets the INVERSE warp, out[u] = image[u - 1], which is the swapped pair below.+ # The keywords are load-bearing: #4273's Expected section is a parameter RENAME+ # (depth_src -> depth_dst, patch_dst -> image_src, and the matching pinhole_dst / pinhole_src), so a+ # positional version of this pin would keep passing through the repair and never force its own deletion.+ # Snippet used to generate expected: the three row-0 calls executed 2026-09-06 at commit 1a96bfd1+ # (torch 2.14.0) -> warp_frame_depth [1.0, 2.0, 3.0, 4.0, 0.0]; DepthWarper(pinhole_dst = +1 tx) with an+ # identity pinhole_src [1.0, 2.0, 3.0, 4.0, 0.0] (float64: the last entry is 2.00e-11, hence assert_close+ # and not torch.equal); DepthWarper(pinhole_dst = identity) with a +1 tx pinhole_src+ # [0.0, 0.0, 1.0, 2.0, 3.0]. All three hold on cpu for float32, float64, float16 and bfloat16 and on mps+ # for float32 and float16.+ # Pins the CURRENT naming; NOT a contract; delete when #4273 aligns the two argument names.+ image = torch.arange(20.0, device=device, dtype=dtype).view(1, 1, 4, 5)+ depth = torch.ones(1, 1, 4, 5, device=device, dtype=dtype)+ identity = _eye4(device, dtype)+ tx_plus_one = _tx_plus_one(device, dtype)+ intrinsics = _k44_warp(device, dtype)+ height = torch.tensor([4], device=device)+ width = torch.tensor([5], device=device)+ shifted_right = torch.tensor([1.0, 2.0, 3.0, 4.0, 0.0], device=device, dtype=dtype)+ by_function = warp_frame_depth(+ image_src=image,+ depth_dst=depth,+ src_trans_dst=tx_plus_one,+ camera_matrix=_k53_warp(device, dtype),+ )[0, 0, 0]+ moving = DepthWarper(+ pinhole_dst=PinholeCamera(intrinsics.clone(), tx_plus_one.clone(), height, width), height=4, width=5+ )+ moving.compute_projection_matrix(pinhole_src=PinholeCamera(intrinsics.clone(), identity.clone(), height, width))+ by_class = moving(depth_src=depth, patch_dst=image)[0, 0, 0]+ self.assert_close(by_function, shifted_right)+ self.assert_close(by_class, shifted_right)+ naive = DepthWarper(+ pinhole_dst=PinholeCamera(intrinsics.clone(), identity.clone(), height, width), height=4, width=5+ )+ naive.compute_projection_matrix(+ pinhole_src=PinholeCamera(intrinsics.clone(), tx_plus_one.clone(), height, width)+ )+ swapped = naive(depth_src=depth, patch_dst=image)[0, 0, 0]+ self.assert_close(swapped, torch.tensor([0.0, 0.0, 1.0, 2.0, 3.0], device=device, dtype=dtype))+ assert (by_class - swapped).abs().max().item() > 0.5++ def test_wart_warp_frame_depth_and_depth_warper_split_at_zero_transformed_depth_4267(self, device, dtype):+ # Wart pin for kornia#4267: the two warps guard the z = 0 singularity differently. With K = I, unit+ # depth and a transform that moves every point by (+1, 0, -1), every destination pixel lands at+ # camera-frame z = 0 in the other view. warp_frame_depth projects through project_points, which SKIPS+ # the homogeneous divide when abs(z) <= 1e-8, so it samples image_src at the undivided (u + 1, v) and+ # returns the image shifted by one column; DepthWarper projects through cam2pixel, which divides by+ # z + 1e-12, so the same pixel is sent to a coordinate of order 1e12 (inf in float16, where 1e-12+ # rounds to 0) and nothing of the image comes back. One half unit closer (z = 0.5) the two agree, which+ # is the claim the pin above states for float32 and float64.+ # Snippet used to generate expected: warp_frame_depth(arange(1, 7).view(1, 1, 2, 3), ones, T, eye(3))+ # and the DepthWarper pair built from the same T, executed 2026-09-08 at commit 26ddb21e+ # (torch 2.14.0) -> warp_frame_depth [[2, 3, 0], [5, 6, 0]] in every cell (cpu float32, float64,+ # float16, bfloat16; mps float32, float16); DepthWarper all zeros on cpu float32, float64 and bfloat16,+ # nan on cpu float16, and backend-dependent values on mps (zeros in row 0, 1e24 in row 1 for float32) --+ # so the pin asserts warp_frame_depth's value and the 1e12 grid coordinate and never samples through that+ # grid: torch 2.5.1's aarch64 CPU grid_sample segfaults once one normalized coordinate exceeds 2**31 while+ # the other is in range (x = 2147483648.0, y = -1.0 crashes; x = 2147483000.0 does not), which is what+ # DepthWarper's grid holds here and what killed the macOS torch 2.5.1 CI legs on 2026-09-08; the+ # vectorized-kernel crash is the open pytorch/pytorch#24823 (expanded from #19826).+ # The z = 0.5 arm: max gap 0.0 (float32) and 2.4e-11 (float64) on cpu.+ # Pins the CURRENT behavior; NOT a contract; delete when #4267 settles one z = 0 policy.+ image = torch.arange(1.0, 7.0, device=device, dtype=dtype).view(1, 1, 2, 3)+ depth = torch.ones(1, 1, 2, 3, device=device, dtype=dtype)+ camera_matrix = torch.eye(3, device=device, dtype=dtype)[None]+ intrinsics = _eye4(device, dtype)+ height = torch.tensor([2], device=device)+ width = torch.tensor([3], device=device)++ def warper_for(transform):+ warper = DepthWarper(PinholeCamera(intrinsics.clone(), transform.clone(), height, width), 2, 3)+ warper.compute_projection_matrix(PinholeCamera(intrinsics.clone(), _eye4(device, dtype), height, width))+ return warper++ to_zero_depth = _eye4(device, dtype)+ to_zero_depth[0, 0, 3] = 1.0+ to_zero_depth[0, 2, 3] = -1.0+ by_function = warp_frame_depth(image, depth, to_zero_depth, camera_matrix)+ self.assert_close(by_function, torch.tensor([[[[2.0, 3.0, 0.0], [5.0, 6.0, 0.0]]]], device=device, dtype=dtype))+ singular = warper_for(to_zero_depth)+ # compared in float32: a float16 1e9 is itself inf, and inf > inf is False+ assert (singular.warp_grid(depth)[..., 0].abs().to(torch.float32) > 1.0e9).all()+ if dtype in (torch.float32, torch.float64):+ half_way = to_zero_depth.clone()+ half_way[0, 2, 3] = -0.5+ self.assert_close(+ warper_for(half_way)(depth, image), warp_frame_depth(image, depth, half_way, camera_matrix)+ )+class TestDepthFromDisparity(BaseTester):def test_smoke(self, device, dtype):@@ -450,6 +1111,72 @@ class TestDepthFromDisparity(BaseTester):# evaluate function gradientself.gradcheck(kornia.geometry.depth.depth_from_disparity, (disparity, baseline, focal))+ def test_wart_zero_disparity_gives_a_finite_depth_4272(self, device, dtype):+ # Wart pin for kornia#4272: depth_from_disparity computes+ # ``baseline * focal / (disparity + 1e-8)``, so the epsilon enters the arithmetic instead of guarding a+ # branch. A zero disparity -- the standard "no match here" fill value of every stereo matcher -- returns+ # 5e9 for baseline 0.5 and focal 100 rather than inf, and that number is a function of the epsilon, not+ # of the camera: it scales with baseline * focal and is nothing a caller can threshold against.+ # The working case is asserted beside it so the pin is not just about the singular input: disparity 2+ # gives 0.5 * 100 / 2 = 25.+ # Snippet used to generate expected: depth_from_disparity(zeros(1, 1, 1, 1), 0.5, 100.0).item() executed+ # 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> 5000000000.0 on cpu float32 and float64 and on mps+ # float32, 4999610368.0 on cpu bfloat16, and inf on cpu and mps float16 -- there the 1e-8 itself rounds+ # to 0 (zeros(1, 1, 1, 1, dtype=float16) + 1e-8 is exactly 0), the divide is by zero, and the "finite+ # depth" wart does not occur at all. The float16 arm asserts that inf instead of the finite value.+ # Pins the CURRENT value; NOT a contract; delete when #4272 is repaired.+ disparity = torch.zeros(1, 1, 1, 1, device=device, dtype=dtype)+ depth = depth_from_disparity(disparity, 0.5, 100.0)+ if dtype == torch.float16:+ assert (disparity + 1e-8).eq(0.0).all()+ assert torch.isinf(depth).all()+ return+ assert torch.isfinite(depth).all()+ self.assert_close(depth, torch.full((1, 1, 1, 1), 5.0e9, device=device, dtype=dtype))+ self.assert_close(+ depth_from_disparity(torch.full((1, 1, 1, 1), 2.0, device=device, dtype=dtype), 0.5, 100.0),+ torch.full((1, 1, 1, 1), 25.0, device=device, dtype=dtype),+ )++ def test_wart_depth_from_disparity_rejects_a_batched_baseline_4272(self, device, dtype):+ # Wart pin for kornia#4272: the+ # docstring says baseline and focal are "float/tensor", but the guard is KORNIA_CHECK_SHAPE(..., ["1"]),+ # so a tensor argument must have exactly shape (1,). A 0-dim tensor -- what ``torch.tensor(0.5)`` or any+ # reduction produces -- is rejected, and so is a per-batch-element (2,) baseline, even though the+ # disparity itself is batched. A python ``int`` is rejected outright by the type check, for either+ # argument -- so ``depth_from_disparity(d, 1, 100.0)`` fails while ``(d, 1.0, 100.0)`` works.+ # Snippet used to generate expected: depth_from_disparity(ones(1, 1, 2, 3), baseline, focal) executed+ # 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> ShapeError("Shape dimension mismatch: expected 1+ # dimensions, got 0.") for the 0-dim baseline and ShapeError("Shape mismatch at dimension 0: expected 1,+ # got 2.") for the (2,) baseline and the (2,) focal, on cpu for float32, float64, float16 and bfloat16+ # and on mps for float32 and float16; a python int raises BaseError("Input baseline should be either a+ # float or torch.Tensor. Got <class 'int'>") and the same sentence for ``focal`` in those cells, and+ # the (1,) form returns shape (1, 1, 2, 3).+ # Pins the CURRENT behavior; NOT a contract; delete when #4272 is repaired.+ disparity = torch.ones(1, 1, 2, 3, device=device, dtype=dtype)+ focal = torch.tensor([100.0], device=device, dtype=dtype)+ with pytest.raises(ShapeError, match="expected 1 dimensions, got 0"):+ depth_from_disparity(disparity, torch.tensor(0.5, device=device, dtype=dtype), focal)+ with pytest.raises(ShapeError, match="expected 1, got 2"):+ depth_from_disparity(disparity, torch.tensor([0.5, 0.5], device=device, dtype=dtype), focal)+ with pytest.raises(ShapeError, match="expected 1, got 2"):+ depth_from_disparity(+ disparity,+ torch.tensor([0.5], device=device, dtype=dtype),+ torch.tensor([100.0, 100.0], device=device, dtype=dtype),+ )+ with pytest.raises(BaseError, match=r"Input baseline should be either a float or torch\.Tensor"):+ depth_from_disparity(disparity, 1, 100.0)+ with pytest.raises(BaseError, match=r"Input focal should be either a float or torch\.Tensor"):+ depth_from_disparity(disparity, 0.5, 100)+ assert depth_from_disparity(disparity, 1.0, 100.0).shape == (1, 1, 2, 3)+ assert depth_from_disparity(disparity, torch.tensor([0.5], device=device, dtype=dtype), focal).shape == (+ 1,+ 1,+ 2,+ 3,+ )+class TestDepthFromPlaneEquation(BaseTester):def test_smoke(self, device, dtype):@@ -583,3 +1310,87 @@ class TestDepthFromPlaneEquation(BaseTester):eps=1e-6,atol=1e-4,)++ def test_convention_plane_z_equals_two_gives_depth_two(self, device, dtype):+ # Convention pin: the plane is given in the HESSIAN form+ # ``n . X = d`` with the normal and the offset in the CAMERA frame, and the pixels are pixel+ # coordinates that the function normalizes with the intrinsics itself. The fronto-parallel plane+ # n = (0, 0, 1), d = 2 is the plane z = 2, so every pixel -- the principal point and a far off-axis one+ # alike -- has depth exactly 2, and the output is (B, N), one depth per pixel, not a map.+ # The tilted arm is the one-parameter-away check: rotating the normal to (0, 0.5, 1) / |.| makes the two+ # pixels disagree (2.236 vs 1.491), so a reading in which the offset alone sets the depth fails.+ # Snippet used to generate expected: depth_from_plane_equation(n, offsets, pixels, K) executed+ # 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> [[2.0, 2.0]] and torch.equal to full(2.0) on cpu for+ # float32, float64, float16 and bfloat16 and on mps for float32 and float16; the tilted plane gives+ # [2.2360680103302, 1.49071204662323] on cpu float32, [2.23606797749979, 1.4907119849998598] on cpu+ # float64, [2.236328125, 1.490234375] on cpu float16 and [2.234375, 1.4921875] on cpu bfloat16.+ camera_matrix = _k_asymmetric(device, dtype)+ offsets = torch.tensor([[2.0]], device=device, dtype=dtype)+ pixels = torch.tensor([[[4.0, 3.0], [29.0, 53.0]]], device=device, dtype=dtype)+ depth = depth_from_plane_equation(+ torch.tensor([[0.0, 0.0, 1.0]], device=device, dtype=dtype), offsets, pixels, camera_matrix+ )+ assert depth.shape == (1, 2)+ self.assert_close(depth, torch.full((1, 2), 2.0, device=device, dtype=dtype), atol=0.0, rtol=0.0)+ tilted = depth_from_plane_equation(+ torch.tensor([[0.0, 0.4472135954999579, 0.8944271909999159]], device=device, dtype=dtype),+ offsets,+ torch.tensor([[[4.0, 3.0], [4.0, 103.0]]], device=device, dtype=dtype),+ camera_matrix,+ )+ self.assert_close(tilted, torch.tensor([[2.2360679774997896, 1.4907119849998598]], device=device, dtype=dtype))++ def test_convention_depth_from_plane_equation_clamps_a_tiny_denominator(self, device, dtype):+ # Convention pin: the ray-plane dot product is clamped, in a+ # masked branch, to +/- eps when it falls inside (-eps, eps), so a nearly-grazing ray returns a large+ # SIGNED finite depth (2 / 1e-8 = 2e8) instead of overflowing -- and the sign of the denominator is+ # preserved, so the two arms differ by their sign rather than only by magnitude. Nothing outside the+ # mask is touched, which is why the fronto-parallel pin above is exact. The mask+ # also clamps exactly zero (kornia#4280), pinned below.+ # ``eps`` is passed explicitly, equal to the function's own default, so the +/- 2e8 literal is a+ # statement about the CLAMP and not about a default that could move: at eps = 1e-6 the same input+ # returns +/- 2000000.0 instead (executed below).+ # Snippet used to generate expected: depth_from_plane_equation([[0, 1, 2.384185791015625e-09]], [[2.0]],+ # [[[4.0, 3.0]]], K, eps=1e-8) and the negated normal, executed 2026-09-06 at commit 1a96bfd1+ # (torch 2.14.0) -> 200000000.0 and -200000000.0 on cpu float32 and float64 and on mps float32,+ # 200278016.0 and -200278016.0 on cpu bfloat16; with eps=1e-6, 2000000.0 / -2000000.0 (cpu float32,+ # float64, mps float32) and 2007040.0 / -2007040.0 (cpu bfloat16). float16 is skipped:+ # 2.384185791015625e-09 underflows to 0 there, so the probe input is no longer inside the mask and the+ # call returns inf on both signs at either eps.+ if dtype == torch.float16:+ pytest.skip(+ "float16: the 2.384185791015625e-09 normal component underflows to 0, so the input is "+ "no longer a tiny-but-non-zero denominator and both signs return inf"+ )+ camera_matrix = _k_asymmetric(device, dtype)+ offsets = torch.tensor([[2.0]], device=device, dtype=dtype)+ principal_point = torch.tensor([[[4.0, 3.0]]], device=device, dtype=dtype)+ normal = torch.tensor([[0.0, 1.0, 2.384185791015625e-09]], device=device, dtype=dtype)+ positive = depth_from_plane_equation(normal, offsets, principal_point, camera_matrix, eps=1e-8)+ negative = depth_from_plane_equation(-normal, offsets, principal_point, camera_matrix, eps=1e-8)+ assert torch.isfinite(positive).all()+ assert torch.isfinite(negative).all()+ self.assert_close(positive, torch.full((1, 1), 2.0e8, device=device, dtype=dtype))+ self.assert_close(negative, torch.full((1, 1), -2.0e8, device=device, dtype=dtype))+ wider = depth_from_plane_equation(normal, offsets, principal_point, camera_matrix, eps=1e-6)+ self.assert_close(wider, torch.full((1, 1), 2.0e6, device=device, dtype=dtype))++ def test_convention_depth_from_plane_equation_clamps_the_singularity_4280(self, device, dtype):+ # Regression for #4280 (repaired by #4348): an exactly zero denominator is replaced by POSITIVE eps, so+ # the grazing ray returns +2 / 1e-8 = +2e8 for either sign of the normal -- there is no sign to keep at+ # zero, and the pin asserts the sign, not just the magnitude.+ # Snippet used to generate expected: depth_from_plane_equation([[0, +-1, 0]], [[2.0]], [[[4.0, 3.0]]], K)+ # executed 2026-09-08 at commit 089daad9 (torch 2.14.0) -> 200000000.0 for both normals on cpu float32,+ # float64 and bfloat16 and on mps float32; float16 is skipped because 2e8 is past its range.+ if dtype == torch.float16:+ pytest.skip("float16: 2 / 1e-8 = 2e8 overflows the float16 range, so the repaired value is inf too")+ camera_matrix = _k_asymmetric(device, dtype)+ for sign in (1.0, -1.0):+ grazing = depth_from_plane_equation(+ torch.tensor([[0.0, sign, 0.0]], device=device, dtype=dtype),+ torch.tensor([[2.0]], device=device, dtype=dtype),+ torch.tensor([[[4.0, 3.0]]], device=device, dtype=dtype),+ camera_matrix,+ )+ assert torch.isfinite(grazing).all()+ self.assert_close(grazing, torch.full((1, 1), 2.0e8, device=device, dtype=dtype))