π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
implement project_points
edgarriba09b5f37834db
diff --git a/kornia/geometry/camera/__init__.py b/kornia/geometry/camera/__init__.pyindex 43fb34dee..e3b90ea70 100644--- a/kornia/geometry/camera/__init__.py+++ b/kornia/geometry/camera/__init__.py@@ -1,9 +1,10 @@from .pinhole import PinholeCamera, pixel2cam, cam2pixel-from .perspective import unproject_points+from .perspective import unproject_points, project_points__all__ = ["PinholeCamera","pixel2cam","cam2pixel","unproject_points",+ "project_points",]diff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.pyindex ba912800e..fd8e3ca1a 100644--- a/kornia/geometry/camera/perspective.py+++ b/kornia/geometry/camera/perspective.py@@ -3,7 +3,55 @@ from typing import Optionalimport torchimport torch.nn.functional as F-from kornia.geometry.conversions import convert_points_to_homogeneous+from kornia.geometry.linalg import transform_points+from kornia.geometry.conversions import (+ convert_points_to_homogeneous, convert_points_from_homogeneous+)+++def project_points(+ point_3d: torch.Tensor,+ camera_matrix: torch.Tensor) -> torch.Tensor:+ r"""Projects a 3d point onto the 2d camera plane.++ Args:+ point3d (torch.Tensor): tensor containing the 3d points to be projected+ to the camera plane. The shape of the tensor can be (*, 3).+ camera_matrix (torch.Tensor): tensor containing the intrinsics camera+ matrix. The tensor shape must be Bx4x4.++ Returns:+ torch.Tensor: array of (u, v) cam coordinates with shape (*, 2).+ """+ if not torch.is_tensor(point_3d):+ raise TypeError("Input point_3d type is not a torch.Tensor. Got {}"+ .format(type(points_3d)))+ 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_3d.device == camera_matrix.device):+ raise ValueError("Input tensors must be all in the same device.")+ if not point_3d.shape[-1] == 3:+ raise ValueError("Input points_3d must be in the shape of (*, 3)."+ " Got {}".format(point_3d.shape))+ if not camera_matrix.shape[-2:] == (3, 3):+ raise ValueError("Input camera_matrix must be in the shape of (*, 3, 3).")+ # projection eq. [u, v, w]' = K * [x y z 1]'+ # project back using depth dividing in a safe way+ xy_coords: torch.Tensor = convert_points_from_homogeneous(point_3d)+ x_coord: torch.Tensor = xy_coords[..., 0]+ y_coord: torch.Tensor = xy_coords[..., 1]++ # unpack intrinsics+ fx: torch.Tensor = camera_matrix[..., 0, 0]+ fy: torch.Tensor = camera_matrix[..., 1, 1]+ cx: torch.Tensor = camera_matrix[..., 0, 2]+ cy: torch.Tensor = camera_matrix[..., 1, 2]++ # apply intrinsics ans return+ u_coord: torch.Tensor = x_coord * fx + cx+ v_coord: torch.Tensor = y_coord * fy + cy+ return torch.stack([u_coord, v_coord], dim=-1)def unproject_points(@@ -16,18 +64,18 @@ def unproject_points(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.+ point2d (torch.Tensor): tensor containing the 2d to be projected to+ world coordinates. The shape of the tensor can be (*, 2).+ depth (torch.Tensor): tensor containing the depth value of each 2d+ points. The tensor shape must be equal to point2d (*, 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. Thismust be set to `True` when the depth is represented as the Euclideanray length from the camera position. Default is `False`.Returns:- torch.Tensor: array of (u, v, 1) cam coordinates with shape (*, 3).+ torch.Tensor: tensor of (x, y, z) world coordinates with shape (*, 3)."""if not torch.is_tensor(point_2d):raise TypeError("Input point_2d type is not a torch.Tensor. Got {}"@@ -57,7 +105,7 @@ def unproject_points(# apply inverse intrinsics to pointsxyz: torch.Tensor = torch.matmul(- camera_matrix.view(-1, 3, 3), uvw.view(-1, 3, 1))+ camera_matrix_inv.view(-1, 3, 3), uvw.view(-1, 3, 1))# back to input shape and normalize if specifiedxyz_norm: torch.Tensor = xyz.view((*point_2d.shape[:-1], 3))diff --git a/test/geometry/test_perspective.py b/test/geometry/test_perspective.pyindex b806feff2..f80956755 100644--- a/test/geometry/test_perspective.py+++ b/test/geometry/test_perspective.py@@ -8,6 +8,62 @@ from torch.autograd import gradcheckfrom torch.testing import assert_allclose+class TestProjectPoints:+ def test_smoke(self):+ point_3d = torch.zeros(1, 3)+ camera_matrix = torch.eye(3).expand(1, -1, -1)+ point_2d = kornia.project_points(point_3d, camera_matrix)+ assert point_2d.shape == (1, 2)++ def test_smoke_batch(self):+ point_3d = torch.zeros(2, 3)+ camera_matrix = torch.eye(3).expand(2, -1, -1)+ point_2d = kornia.project_points(point_3d, camera_matrix)+ assert point_2d.shape == (2, 2)++ def test_smoke_batch_multi(self):+ point_3d = torch.zeros(2, 4, 3)+ camera_matrix = torch.eye(3).expand(2, 4, -1, -1)+ point_2d = kornia.project_points(point_3d, camera_matrix)+ assert point_2d.shape == (2, 4, 2)++ def test_project_and_unproject(self):+ point_3d = torch.tensor([[10., 2., 30.]])+ depth = point_3d[..., -1:]+ camera_matrix = torch.tensor([[+ [2746., 0., 991.],+ [0., 2748., 619.],+ [0., 0., 1.],+ ]])+ point_2d = kornia.project_points(point_3d, camera_matrix)+ point_3d_hat = kornia.unproject_points(point_2d, depth, camera_matrix)+ assert_allclose(point_3d, point_3d_hat)++ def test_gradcheck(self):+ # TODO: point [0, 0, 0] crashes+ points_3d = torch.ones(1, 3)+ camera_matrix = torch.eye(3).expand(1, -1, -1)++ # evaluate function gradient+ points_3d = tensor_to_gradcheck_var(points_3d)+ camera_matrix = tensor_to_gradcheck_var(camera_matrix)+ assert gradcheck(kornia.project_points,+ (points_3d, camera_matrix),+ raise_exception=True)++ def test_jit(self):+ @torch.jit.script+ def op_script(points_3d, camera_matrix):+ return kornia.project_points(points_3d, camera_matrix)++ points_3d = torch.zeros(1, 3)+ camera_matrix = torch.eye(3).expand(1, -1, -1)+ actual = op_script(points_3d, camera_matrix)+ expected = kornia.project_points(points_3d, camera_matrix)++ assert_allclose(actual, expected)++class TestUnprojectPoints:def test_smoke(self):points_2d = torch.zeros(1, 2)@@ -54,6 +110,18 @@ class TestUnprojectPoints:actual = kornia.unproject_points(point_2d, depth, camera_matrix, True)assert_allclose(actual, expected)+ def test_unproject_and_project(self):+ point_2d = torch.tensor([[0., 0.]])+ depth = torch.tensor([[2.]])+ camera_matrix = torch.tensor([+ [1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.],+ ])+ point_3d = kornia.unproject_points(point_2d, depth, camera_matrix)+ point_2d_hat = kornia.project_points(point_3d, camera_matrix)+ assert_allclose(point_2d, point_2d_hat)+def test_gradcheck(self):points_2d = torch.zeros(1, 2)depth = torch.ones(1, 1)