Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Depth to 3d improvements (#2557)

Edgar Ribac86df685c2e9
diff --git a/docs/source/geometry.depth.rst b/docs/source/geometry.depth.rst
index 9f407dc59..614838125 100644
--- a/docs/source/geometry.depth.rst
+++ b/docs/source/geometry.depth.rst
@@ -5,5 +5,7 @@ kornia.geometry.depth
.. autofunction:: depth_from_disparity
.. autofunction:: depth_to_3d
+.. autofunction:: depth_to_3d_v3
+.. autofunction:: unproject_meshgrid
.. autofunction:: depth_to_normals
.. autofunction:: warp_frame_depth
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index 424fab722..d0f733489 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -13,6 +13,7 @@ from ._backend import (
einsum,
eye,
linspace,
+ map_coordinates,
normalize,
ones,
ones_like,
@@ -54,4 +55,5 @@ __all__ = [
"linspace",
"diag",
"TensorWrapper",
+ "map_coordinates",
]
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
index df8f4c366..422a0fe6a 100644
--- a/kornia/core/_backend.py
+++ b/kornia/core/_backend.py
@@ -29,6 +29,7 @@ where = torch.where
complex = torch.complex
diag = torch.diag
softmax = torch.nn.functional.softmax
+map_coordinates = torch.nn.functional.grid_sample
# constructors
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index e96737c5a..21356f761 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -2,23 +2,115 @@
from __future__ import annotations
import torch
-import torch.nn.functional as F
-from kornia.core import Module, Tensor, concatenate, tensor
+import kornia.core as kornia_ops
+from kornia.core import Module, Tensor, tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters.sobel import spatial_gradient
from kornia.utils import create_meshgrid
from .camera import PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_points
-from .conversions import normalize_pixel_coordinates
+from .conversions import normalize_pixel_coordinates, normalize_points_with_intrinsics
from .linalg import compose_transformations, convert_points_to_homogeneous, inverse_transformation, transform_points
-__all__ = ["depth_to_3d", "depth_to_normals", "warp_frame_depth", "DepthWarper", "depth_warp", "depth_from_disparity"]
+__all__ = [
+ "depth_to_3d",
+ "depth_to_3d_v2",
+ "depth_to_normals",
+ "warp_frame_depth",
+ "depth_warp",
+ "DepthWarper",
+ "depth_from_disparity",
+ "unproject_meshgrid",
+]
+
+
+def unproject_meshgrid(
+ height: int, width: int, camera_matrix: Tensor, normalize_points: bool = False, device=None, dtype=None
+) -> Tensor:
+ """Compute a 3d point per pixel given its depth value and the camera intrinsics.
+
+ .. tip::
+
+ This function should be used in conjunction with :py:func:`kornia.geometry.depth.depth_to_3d_v2` to cache
+ the meshgrid computation when warping multiple frames with the same camera intrinsics.
+
+ Args:
+ camera_matrix: tensor containing the camera intrinsics with shape :math:`(3, 3)`.
+ normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth is
+ represented as the Euclidean ray length from the camera position.
+
+ Return:
+ tensor with a 3d point per pixel of the same resolution as the input :math:`(*, H, W, 3)`.
+ """
+ KORNIA_CHECK_SHAPE(camera_matrix, ["3", "3"])
+
+ # create base coordinates grid
+ points_uv: Tensor = create_meshgrid(
+ height, width, normalized_coordinates=False, device=device, dtype=dtype
+ ).squeeze() # HxWx2
+
+ points_xy = normalize_points_with_intrinsics(points_uv, camera_matrix) # HxWx2
+
+ # unproject pixels to camera frame
+ points_xyz = convert_points_to_homogeneous(points_xy) # HxWx3
+
+ if normalize_points:
+ points_xyz = kornia_ops.normalize(points_xyz, dim=-1, p=2)
+
+ return points_xyz
+
+
+def depth_to_3d_v2(
+ depth: Tensor, camera_matrix: Tensor, normalize_points: bool = False, xyz_grid: Tensor | None = None
+) -> Tensor:
+ """Compute a 3d point per pixel given its depth value and the camera intrinsics.
+
+ .. note::
+
+ This is an alternative implementation of :py:func:`kornia.geometry.depth.depth_to_3d`
+ that does not require the creation of a meshgrid.
+
+ 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)`.
+ normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth is
+ represented as the Euclidean ray length from the camera position.
+
+ Return:
+ tensor with a 3d point per pixel of the same resolution as the input :math:`(*, H, W, 3)`.
+
+ Example:
+ >>> depth = torch.rand(4, 4)
+ >>> K = torch.eye(3)
+ >>> depth_to_3d(depth, K).shape
+ torch.Size([4, 4, 3])
+ """
+ KORNIA_CHECK_SHAPE(depth, ["*", "H", "W"])
+ KORNIA_CHECK_SHAPE(camera_matrix, ["*", "3", "3"])
+
+ # create base grid if not provided
+ points_xyz = xyz_grid
+ if xyz_grid is None:
+ height, width = depth.shape[-2:]
+ points_xyz = unproject_meshgrid(height, width, camera_matrix, normalize_points, depth.device, depth.dtype)
+
+ KORNIA_CHECK_SHAPE(points_xyz, ["*", "H", "W", "3"])
+
+ return points_xyz * depth[..., None] # HxWx3
+
+
+# NOTE: this function should replace the old depth_to_3d
def depth_to_3d(depth: Tensor, camera_matrix: Tensor, normalize_points: bool = False) -> Tensor:
"""Compute a 3d point per pixel given its depth value and the camera intrinsics.
+ .. 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.
+
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)`.
@@ -103,7 +195,7 @@ def depth_to_normals(depth: Tensor, camera_matrix: Tensor, normalize_points: boo
a, b = gradients[:, :, 0], gradients[:, :, 1] # Bx3xHxW
normals: Tensor = torch.cross(a, b, dim=1) # Bx3xHxW
- return F.normalize(normals, dim=1, p=2)
+ return kornia_ops.normalize(normals, dim=1, p=2)
def warp_frame_depth(
@@ -148,6 +240,7 @@ def warp_frame_depth(
if not (len(camera_matrix.shape) == 3 and camera_matrix.shape[-2:] == (3, 3)):
raise ValueError(f"Input camera_matrix must have a shape (B, 3, 3). Got: {camera_matrix.shape}.")
+
# unproject source points to camera frame
points_3d_dst: Tensor = depth_to_3d(depth_dst, camera_matrix, normalize_points) # Bx3xHxW
@@ -165,7 +258,7 @@ def warp_frame_depth(
height, width = depth_dst.shape[-2:]
points_2d_src_norm: Tensor = normalize_pixel_coordinates(points_2d_src, height, width) # BxHxWx2
- return F.grid_sample(image_src, points_2d_src_norm, align_corners=True)
+ return kornia_ops.map_coordinates(image_src, points_2d_src_norm, align_corners=True)
class DepthWarper(Module):
@@ -247,7 +340,7 @@ class DepthWarper(Module):
z = 1.0 / flow[:, 2]
_x = flow[:, 0] * z
_y = flow[:, 1] * z
- return concatenate([_x, _y], 1)
+ return kornia_ops.concatenate([_x, _y], 1)
def compute_subpixel_step(self) -> Tensor:
"""Compute the required inverse depth step to achieve sub pixel accurate sampling of the depth cost volume,
@@ -327,7 +420,7 @@ class DepthWarper(Module):
>>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
>>> image_src = warper(depth_src, image_dst) # NxCxHxW
"""
- return F.grid_sample(
+ return kornia_ops.map_coordinates(
patch_dst,
self.warp_grid(depth_src),
mode=self.mode,
diff --git a/kornia/utils/pointcloud_io.py b/kornia/utils/pointcloud_io.py
index c6e2aa7c0..ac38b5282 100644
--- a/kornia/utils/pointcloud_io.py
+++ b/kornia/utils/pointcloud_io.py
@@ -18,7 +18,7 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
if not torch.is_tensor(pointcloud):
raise TypeError(f"Input pointcloud type is not a torch.Tensor. Got {type(pointcloud)}")
- if not len(pointcloud.shape) == 3 and pointcloud.shape[-1] == 3:
+ if not len(pointcloud.shape) >= 2 and pointcloud.shape[-1] == 3:
raise TypeError(f"Input pointcloud must be in the following shape HxWx3. Got {pointcloud.shape}.")
# flatten the input pointcloud in a vector to iterate points
@@ -32,9 +32,9 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
if not bool(torch.isfinite(xyz).any()):
num_points -= 1
continue
- x: float = xyz[0].item()
- y: float = xyz[1].item()
- z: float = xyz[2].item()
+ x: float = float(xyz[0])
+ y: float = float(xyz[1])
+ z: float = float(xyz[2])
data_str += f'{x} {y} {z}\n'
f.write("ply\n")
diff --git a/test/geometry/test_depth.py b/test/geometry/test_depth.py
index 60dd90a56..967b05c6a 100644
--- a/test/geometry/test_depth.py
+++ b/test/geometry/test_depth.py
@@ -31,6 +31,24 @@ class TestDepthTo3d:
points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix)
assert points3d.shape == (batch_size, 3, 3, 4)
+ def test_depth_to_3d_v2(self, device, dtype):
+ depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
+ camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
+
+ points3d = kornia.geometry.depth.depth_to_3d(depth, camera_matrix)
+
+ # TODO: implement me with batch
+ points3d_v2 = kornia.geometry.depth.depth_to_3d_v2(depth[0, 0], camera_matrix[0])
+ assert_close(points3d[0].permute(1, 2, 0), points3d_v2)
+
+ def test_unproject_meshgrid(self, device, dtype):
+ # TODO: implement me with batch
+ camera_matrix = torch.eye(3, device=device, dtype=dtype)
+ grid = kornia.geometry.unproject_meshgrid(3, 4, camera_matrix, device=device, dtype=dtype)
+ assert grid.shape == (3, 4, 3)
+ # test for now that the grid is correct and have homogeneous coords
+ assert_close(grid[..., 2], torch.ones_like(grid[..., 2]))
+
def test_unproject_denormalized(self, device, dtype):
# this is for default normalize_points=False
depth = 2 * torch.tensor(