Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement unproject points

edgarriba47fc1bd93929
diff --git a/kornia/geometry/camera/__init__.py b/kornia/geometry/camera/__init__.py
index 7429d9655..43fb34dee 100644
--- a/kornia/geometry/camera/__init__.py
+++ b/kornia/geometry/camera/__init__.py
@@ -1,7 +1,9 @@
from .pinhole import PinholeCamera, pixel2cam, cam2pixel
+from .perspective import unproject_points
__all__ = [
"PinholeCamera",
"pixel2cam",
"cam2pixel",
+ "unproject_points",
]
diff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.py
new file mode 100644
index 000000000..c353161bb
--- /dev/null
+++ b/kornia/geometry/camera/perspective.py
@@ -0,0 +1,68 @@
+from typing import Optional
+
+import torch
+
+from kornia.geometry.conversions import convert_points_to_homogeneous
+
+
+def unproject_points(
+ point_2d: torch.Tensor,
+ depth: torch.Tensor,
+ camera_matrix: torch.Tensor,
+ normalize: Optional[bool] = False) -> torch.Tensor:
+ r"""Unprojects a 2d point in 3d.
+
+ Transform coordinates in the pixel frame to the camera frame.
+
+ Args:
+ point2d (torch.Tensor): the 2d to be projected to world coordinates.
+ The shape of the tensor can be (*, 2).
+ depth (torch.Tensor): the depth value of each 2d points. The tensor
+ shape must be equal to point2d (*, 1).
+ camera_matrix (torch.Tensor): the intrinsics camera matrix. The tensor
+ shape must be Bx4x4.
+ normalize (Optional[bool]): 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`.
+
+ Returns:
+ torch.Tensor: array of (u, v, 1) cam coordinates with shape (*, 3).
+ """
+ if not torch.is_tensor(point_2d):
+ raise TypeError("Input point_2d type is not a torch.Tensor. Got {}"
+ .format(type(points_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).")
+ # projection eq. K_inv * [u v 1]'
+ # inverse the camera matrix
+ camera_matrix_inv: torch.Tensor = torch.inverse(camera_matrix)
+
+ # compute ray from center to camera
+ uvw: torch.Tensor = convert_points_to_homogeneous(point_2d)
+
+ # apply inverse intrinsics to points
+ xyz: torch.Tensor = torch.matmul(
+ camera_matrix.view(-1, 3, 3), uvw.view(-1, 3, 1))
+
+ # back to input shape and normalize if specified
+ xyz_norm: torch.Tensor = xyz.view((*point_2d.shape[:-1], 3))
+
+ if normalize:
+ xyz_norm = F.normalize(x, dim=-1, p=2)
+
+ # apply depth
+ return xyz_norm * depth
diff --git a/test/geometry/test_perspective.py b/test/geometry/test_perspective.py
new file mode 100644
index 000000000..96a2c3efa
--- /dev/null
+++ b/test/geometry/test_perspective.py
@@ -0,0 +1,69 @@
+import pytest
+
+import kornia
+from kornia.testing import tensor_to_gradcheck_var
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
+class TestUnprojectPoints:
+ def test_smoke(self):
+ points_2d = torch.zeros(1, 2)
+ depth = torch.ones(1, 1)
+ camera_matrix = torch.eye(3).expand(1, -1, -1)
+ point_3d = kornia.unproject_points(points_2d, depth, camera_matrix)
+ assert point_3d.shape == (1, 3)
+
+ def test_smoke_batch(self):
+ points_2d = torch.zeros(2, 2)
+ depth = torch.ones(2, 1)
+ camera_matrix = torch.eye(3).expand(2, -1, -1)
+ point_3d = kornia.unproject_points(points_2d, depth, camera_matrix)
+ assert point_3d.shape == (2, 3)
+
+ def test_smoke_multi_batch(self):
+ points_2d = torch.zeros(2, 3, 2)
+ depth = torch.ones(2, 3, 1)
+ camera_matrix = torch.eye(3).expand(2, 3, -1, -1)
+ point_3d = kornia.unproject_points(points_2d, depth, camera_matrix)
+ assert point_3d.shape == (2, 3, 3)
+
+ def test_unproject_center(self):
+ point_2d = torch.tensor([[0., 0.]])
+ depth = torch.tensor([[2.]])
+ camera_matrix = torch.tensor([
+ [1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.],
+ ])
+ expected = torch.tensor([[0., 0., 2.]])
+ actual = kornia.unproject_points(point_2d, depth, camera_matrix)
+ assert_allclose(actual, expected)
+
+ def test_gradcheck(self):
+ points_2d = torch.zeros(1, 2)
+ depth = torch.ones(1, 1)
+ camera_matrix = torch.eye(3).expand(1, -1, -1)
+
+ # evaluate function gradient
+ points_2d = tensor_to_gradcheck_var(points_2d)
+ depth = tensor_to_gradcheck_var(depth)
+ camera_matrix = tensor_to_gradcheck_var(camera_matrix)
+ assert gradcheck(kornia.unproject_points,
+ (points_2d, depth, camera_matrix),
+ raise_exception=True)
+
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(points_2d, depth, camera_matrix):
+ return kornia.unproject_points(points_2d, depth, camera_matrix, False)
+
+ points_2d = torch.zeros(1, 2)
+ depth = torch.ones(1, 1)
+ camera_matrix = torch.eye(3).expand(1, -1, -1)
+ actual = op_script(points_2d, depth, camera_matrix)
+ expected = kornia.unproject_points(points_2d, depth, camera_matrix)
+
+ assert_allclose(actual, expected)