Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement depth_to_3d

edgarriba2d3bd73ca317
diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.py
index bcec13427..55ab8fb4b 100644
--- a/kornia/geometry/__init__.py
+++ b/kornia/geometry/__init__.py
@@ -3,3 +3,4 @@ from kornia.geometry.conversions import *
from kornia.geometry.linalg import *
from kornia.geometry.transform import *
from kornia.geometry.warp import *
+from kornia.geometry.depth import *
diff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.py
index 3b5d1c34c..cbeebfa30 100644
--- a/kornia/geometry/camera/perspective.py
+++ b/kornia/geometry/camera/perspective.py
@@ -63,7 +63,7 @@ def unproject_points(
point_2d: torch.Tensor,
depth: torch.Tensor,
camera_matrix: torch.Tensor,
- normalize: Optional[bool] = False) -> torch.Tensor:
+ normalize: bool = False) -> torch.Tensor:
r"""Unprojects a 2d point in 3d.
Transform coordinates in the pixel frame to the camera frame.
@@ -75,7 +75,7 @@ def unproject_points(
points. The tensor shape must be equal to point2d :math:`(*, 1)`.
camera_matrix (torch.Tensor): tensor containing the intrinsics camera
matrix. The tensor shape must be Bx4x4.
- normalize (Optional[bool]): wether to normalize the pointcloud. This
+ normalize (bool, optional): wether to normalize the pointcloud. This
must be set to `True` when the depth is represented as the Euclidean
ray length from the camera position. Default is `False`.
@@ -86,20 +86,26 @@ def unproject_points(
if not torch.is_tensor(point_2d):
raise TypeError("Input point_2d type is not a torch.Tensor. Got {}"
.format(type(point_2d)))
+
if not torch.is_tensor(depth):
raise TypeError("Input depth type is not a torch.Tensor. Got {}"
.format(type(depth)))
+
if not torch.is_tensor(camera_matrix):
raise TypeError("Input camera_matrix type is not a torch.Tensor. Got {}"
.format(type(camera_matrix)))
+
if not (point_2d.device == depth.device == camera_matrix.device):
raise ValueError("Input tensors must be all in the same device.")
+
if not point_2d.shape[-1] == 2:
raise ValueError("Input points_2d must be in the shape of (*, 2)."
" Got {}".format(point_2d.shape))
+
if not depth.shape[-1] == 1:
raise ValueError("Input depth must be in the shape of (*, 1)."
" Got {}".format(depth.shape))
+
if not camera_matrix.shape[-2:] == (3, 3):
raise ValueError(
"Input camera_matrix must be in the shape of (*, 3, 3).")
@@ -108,6 +114,7 @@ def unproject_points(
# y = (v - cy) * Z / fy
# unpack coordinates
+
u_coord: torch.Tensor = point_2d[..., 0:1]
v_coord: torch.Tensor = point_2d[..., 1:2]
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
new file mode 100644
index 000000000..c1f16f526
--- /dev/null
+++ b/kornia/geometry/depth.py
@@ -0,0 +1,52 @@
+"""Module containing operators to work on RGB-Depth images."""
+
+import torch
+import torch.nn.functional as F
+
+from kornia.utils import create_meshgrid
+from kornia.geometry import unproject_points
+
+
+def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor) -> torch.Tensor:
+ """Compute a 3d point per pixel given its depth value and the camera intrinsics.
+
+ Args:
+ depth (torch.Tensor): image tensor containing a depth value per pixel.
+ camera_matrix (torch.Tensor): tensor containing the camera intrinsics.
+
+ Shape:
+ - Input: `:math:(B, 1, H, W)` and `:math:(B, 3, 3)`
+ - Output: `math:(B, 3, H, W)`
+
+ Return:
+ torch.Tensor: tensor with a 3d point per pixel of the same resolution as the input.
+
+ """
+ if not isinstance(depth, torch.Tensor):
+ raise TypeError(f"Input depht type is not a torch.Tensor. Got {type(depth)}.")
+
+ if not len(depth.shape) == 4 and depth.shape[-3] == 1:
+ raise ValueError(f"Input depth musth have a shape (B, 1, H, W). Got: {depth.shape}")
+
+ if not isinstance(camera_matrix, torch.Tensor):
+ raise TypeError(f"Input camera_matrix type is not a torch.Tensor. "
+ f"Got {type(camera_matrix)}.")
+
+ if not len(camera_matrix.shape) == 3 and camera_matrix.shape[-2:] == (3, 3):
+ raise ValueError(f"Input camera_matrix musth have a shape (B, 3, 3). "
+ f"Got: {camera_matrix.shape}.")
+
+ # create base coordinates grid
+ height, width = depth.shape[-2:]
+ points_2d: torch.Tensor = create_meshgrid(
+ height, width, normalized_coordinates=False) # 1xHxWx2
+ points_2d = points_2d.to(depth.device).to(depth.dtype)
+
+ # depth should come in Bx1xHxW
+ points_depth: torch.Tensor = depth.permute(0, 2, 3, 1) # 1xHxWx1
+
+ # project pixels to camera frame
+ points_3d: torch.Tensor = unproject_points(
+ points_2d, points_depth, camera_matrix, normalize=True) # BxHxWx3
+
+ return points_3d.permute(0, 3, 1, 2) # Bx3xHxW
diff --git a/test/geometry/test_depth.py b/test/geometry/test_depth.py
new file mode 100644
index 000000000..9bca8e03d
--- /dev/null
+++ b/test/geometry/test_depth.py
@@ -0,0 +1,31 @@
+import pytest
+
+import kornia
+import kornia.testing as utils # test utils
+from test.common import TEST_DEVICES
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
+class TestDepthTo3D:
+
+ def test_smoke(self):
+ depth = torch.rand(1, 1, 3, 4)
+ camera_matrix = torch.rand(1, 3, 3)
+
+ points3d = kornia.depth_to_3d(depth, camera_matrix)
+ assert points3d.shape == (1, 3, 3, 4)
+
+ def test_gradcheck(self):
+ # generate input data
+ depth = torch.rand(1, 1, 3, 4)
+ depth = utils.tensor_to_gradcheck_var(depth) # to var
+
+ camera_matrix = torch.rand(1, 3, 3)
+ camera_matrix = utils.tensor_to_gradcheck_var(camera_matrix) # to var
+
+ # evaluate function gradient
+ assert gradcheck(kornia.depth_to_3d, (depth, camera_matrix,),
+ raise_exception=True)