π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Adds depth from plane equation (#3040)
Dmytro Mishkin71d50979c6db
diff --git a/docs/source/geometry.depth.rst b/docs/source/geometry.depth.rstindex 382c44482..068733ad4 100644--- a/docs/source/geometry.depth.rst+++ b/docs/source/geometry.depth.rst@@ -8,4 +8,5 @@ kornia.geometry.depth.. autofunction:: depth_to_3d_v2.. autofunction:: unproject_meshgrid.. autofunction:: depth_to_normals+.. autofunction:: depth_from_plane_equation.. autofunction:: warp_frame_depthdiff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 52a5aaa1d..9f79d152e 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -1175,20 +1175,11 @@ def normalize_points_with_intrinsics(point_2d: Tensor, camera_matrix: Tensor) -># y = (v - cy) * Z / fy# unpack coordinates- u_coord: Tensor = point_2d[..., 0]- v_coord: Tensor = point_2d[..., 1]-- # unpack intrinsics- fx: Tensor = camera_matrix[..., 0, 0]- fy: Tensor = camera_matrix[..., 1, 1]- cx: Tensor = camera_matrix[..., 0, 2]- cy: Tensor = camera_matrix[..., 1, 2]-- # projective- x_coord: Tensor = (u_coord - cx) / fx- y_coord: Tensor = (v_coord - cy) / fy-- xy: Tensor = stack([x_coord, y_coord], dim=-1)+ cxcy = camera_matrix[..., :2, 2]+ fxfy = camera_matrix[..., :2, :2].diagonal(dim1=-2, dim2=-1)+ if len(cxcy.shape) < len(point_2d.shape): # broadcast intrinsics:+ cxcy, fxfy = cxcy.unsqueeze(-2), fxfy.unsqueeze(-2)+ xy = (point_2d - cxcy) / fxfyreturn xy@@ -1226,6 +1217,9 @@ def denormalize_points_with_intrinsics(point_2d_norm: Tensor, camera_matrix: Tencx: Tensor = camera_matrix[..., 0, 2]cy: Tensor = camera_matrix[..., 1, 2]+ if len(cx.shape) < len(x_coord.shape): # broadcast intrinsics+ cx, cy, fx, fy = cx.unsqueeze(-1), cy.unsqueeze(-1), fx.unsqueeze(-1), fy.unsqueeze(-1)+# apply intrinsics ans returnu_coord: Tensor = x_coord * fx + cxv_coord: Tensor = y_coord * fy + cydiff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex e6a343578..7c85db649 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -25,6 +25,7 @@ __all__ = ["depth_warp","DepthWarper","depth_from_disparity",+ "depth_from_plane_equation","unproject_meshgrid",]@@ -113,7 +114,7 @@ def depth_to_3d_v2(@deprecated(replace_with="depth_to_3d_v2",- version="0.7.0",+ version="0.8.0",extra_reason=(" This function will be replaced with the `depth_to_3d_v2` behaviour, where the that does not require the"" creation of a meshgrid. The return shape can be not backward compatible between these implementations."@@ -142,17 +143,10 @@ def depth_to_3d(depth: Tensor, camera_matrix: Tensor, normalize_points: bool = F>>> depth_to_3d(depth, K).shapetorch.Size([1, 3, 4, 4])"""- if not isinstance(depth, Tensor):- raise TypeError(f"Input depht type is not a 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, Tensor):- raise TypeError(f"Input camera_matrix type is not a Tensor. Got {type(camera_matrix)}.")-- 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}.")+ KORNIA_CHECK_IS_TENSOR(depth)+ KORNIA_CHECK_IS_TENSOR(camera_matrix)+ KORNIA_CHECK_SHAPE(depth, ["B", "1", "H", "W"])+ KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])# create base coordinates grid_, _, height, width = depth.shape@@ -189,17 +183,10 @@ def depth_to_normals(depth: Tensor, camera_matrix: Tensor, normalize_points: boo>>> depth_to_normals(depth, K).shapetorch.Size([1, 3, 4, 4])"""- if not isinstance(depth, Tensor):- raise TypeError(f"Input depht type is not a 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, Tensor):- raise TypeError(f"Input camera_matrix type is not a Tensor. Got {type(camera_matrix)}.")-- 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}.")+ KORNIA_CHECK_IS_TENSOR(depth)+ KORNIA_CHECK_IS_TENSOR(camera_matrix)+ KORNIA_CHECK_SHAPE(depth, ["B", "1", "H", "W"])+ KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])# compute the 3d points from depthxyz: Tensor = depth_to_3d(depth, camera_matrix, normalize_points) # Bx3xHxW@@ -214,6 +201,49 @@ def depth_to_normals(depth: Tensor, camera_matrix: Tensor, normalize_points: booreturn kornia_ops.normalize(normals, dim=1, p=2)+def depth_from_plane_equation(+ plane_normals: Tensor,+ plane_offsets: Tensor,+ points_uv: Tensor,+ camera_matrix: Tensor,+ eps: float = 1e-8+) -> Tensor:+ """+ Compute depth values from plane equations and pixel coordinates.++ Parameters:+ plane_normals (Tensor): Plane normal vectors of shape (B, 3).+ plane_offsets (Tensor): Plane offsets of shape (B, 1).+ points_uv (Tensor): Pixel coordinates of shape (B, N, 2).+ camera_matrix (Tensor): Camera intrinsic matrix of shape (B, 3, 3).++ Returns:+ Tensor: Computed depth values at the given pixels, shape (B, N).+ """+ KORNIA_CHECK_SHAPE(plane_normals, ["B", "3"])+ KORNIA_CHECK_SHAPE(plane_offsets, ["B", "1"])+ KORNIA_CHECK_SHAPE(points_uv, ["B", "N", "2"])+ KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])++ # Normalize pixel coordinates+ points_xy = normalize_points_with_intrinsics(points_uv, camera_matrix) # (B, N, 2)+ rays = convert_points_to_homogeneous(points_xy) # (B, N, 3)++ # Reshape plane normals to match rays+ plane_normals_exp = plane_normals.unsqueeze(1) # (B, 1, 3)+ # No need to unsqueeze plane_offsets; it is already (B, 1)++ # Compute the denominator of the depth equation+ denom = torch.sum(rays * plane_normals_exp, dim=-1) # (B, N)+ denom_abs = torch.abs(denom)+ zero_mask = denom_abs < eps+ denom = torch.where(zero_mask, eps * torch.sign(denom), denom)++ # Compute depth from plane equation+ depth = plane_offsets / denom # plane_offsets: (B, 1), denom: (B, N) -> depth: (B, N)+ return depth++def warp_frame_depth(image_src: Tensor, depth_dst: Tensor, src_trans_dst: Tensor, camera_matrix: Tensor, normalize_points: bool = False) -> Tensor:@@ -233,29 +263,10 @@ def warp_frame_depth(Return:the warped tensor in the source frame with shape :math:`(B,3,H,W)`."""- if not isinstance(image_src, Tensor):- raise TypeError(f"Input image_src type is not a Tensor. Got {type(image_src)}.")-- if not len(image_src.shape) == 4:- raise ValueError(f"Input image_src musth have a shape (B, D, H, W). Got: {image_src.shape}")-- if not isinstance(depth_dst, Tensor):- raise TypeError(f"Input depht_dst type is not a Tensor. Got {type(depth_dst)}.")-- if not (len(depth_dst.shape) == 4 and depth_dst.shape[-3] == 1):- raise ValueError(f"Input depth_dst musth have a shape (B, 1, H, W). Got: {depth_dst.shape}")-- if not isinstance(src_trans_dst, Tensor):- raise TypeError(f"Input src_trans_dst type is not a Tensor. Got {type(src_trans_dst)}.")-- if not (len(src_trans_dst.shape) == 3 and src_trans_dst.shape[-2:] == (4, 4)):- raise ValueError(f"Input src_trans_dst must have a shape (B, 4, 4). Got: {src_trans_dst.shape}.")-- if not isinstance(camera_matrix, Tensor):- raise TypeError(f"Input camera_matrix type is not a Tensor. Got {type(camera_matrix)}.")-- 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}.")+ KORNIA_CHECK_SHAPE(image_src, ["B", "D", "H", "W"])+ KORNIA_CHECK_SHAPE(depth_dst, ["B", "1", "H", "W"])+ KORNIA_CHECK_SHAPE(src_trans_dst, ["B", "4", "4"])+ KORNIA_CHECK_SHAPE(camera_matrix, ["B", "3", "3"])# unproject source points to camera framepoints_3d_dst: Tensor = depth_to_3d(depth_dst, camera_matrix, normalize_points) # Bx3xHxWdiff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex dc61f5670..4b7fa0805 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -889,6 +889,12 @@ class TestDenormalizePointsWithIntrinsics(BaseTester):points_norm = kornia.geometry.conversions.denormalize_points_with_intrinsics(points_2d, camera_matrix)assert points_norm.shape == (2, 2)+ def test_smoke_batch_n(self, device, dtype):+ points_2d = torch.zeros(2, 9, 2, device=device, dtype=dtype)+ camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(2, -1, -1)+ points_norm = kornia.geometry.conversions.denormalize_points_with_intrinsics(points_2d, camera_matrix)+ assert points_norm.shape == (2, 9, 2)+def test_toy(self, device, dtype):point_2d = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)camera_matrix = torch.tensor(@@ -930,6 +936,12 @@ class TestNormalizePointsWithIntrinsics(BaseTester):points_norm = kornia.geometry.conversions.normalize_points_with_intrinsics(points_2d, camera_matrix)assert points_norm.shape == (2, 2)+ def test_smoke_batch_n(self, device, dtype):+ points_2d = torch.zeros(2, 10, 2, device=device, dtype=dtype)+ camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(2, -1, -1)+ points_norm = kornia.geometry.conversions.normalize_points_with_intrinsics(points_2d, camera_matrix)+ assert points_norm.shape == (2, 10, 2)+def test_norm_unnorm(self, device, dtype):point_2d = torch.tensor([[128.0, 128.0]], device=device, dtype=dtype)camera_matrix = torch.tensor(diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex 21912f77e..88670583f 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -387,3 +387,96 @@ class TestDepthFromDisparity(BaseTester):# evaluate function gradientself.gradcheck(kornia.geometry.depth.depth_from_disparity, (disparity, baseline, focal))+++class TestDepthFromPlaneEquation(BaseTester):+ def test_smoke(self, device, dtype):+ B = 2+ N = 10+ plane_normals = torch.randn(B, 3, device=device, dtype=dtype)+ plane_offsets = torch.randn(B, 1, device=device, dtype=dtype)+ points_uv = torch.randn(B, N, 2, device=device, dtype=dtype)+ camera_matrix = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).repeat(B, 1, 1)++ depth = kornia.geometry.depth.depth_from_plane_equation(plane_normals, plane_offsets, points_uv, camera_matrix)+ assert depth.shape == (B, N), f"Expected depth shape to be ({B}, {N}), but got {depth.shape}"++ @pytest.mark.parametrize("batch_size", [1, 2, 4])+ def test_shapes(self, batch_size, device, dtype):+ B = batch_size+ N = 10+ plane_normals = torch.randn(B, 3, device=device, dtype=dtype)+ plane_offsets = torch.randn(B, 1, device=device, dtype=dtype)+ points_uv = torch.randn(B, N, 2, device=device, dtype=dtype)+ camera_matrix = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).repeat(B, 1, 1)++ depth = kornia.geometry.depth.depth_from_plane_equation(plane_normals, plane_offsets, points_uv, camera_matrix)+ assert depth.shape == (B, N), f"Expected depth shape to be ({B}, {N}), but got {depth.shape}"++ @pytest.mark.parametrize("batch_size", [1, 2, 4])+ def test_shapes_broadcast(self, batch_size, device, dtype):+ B = batch_size+ N = 10+ plane_normals = torch.randn(1, 3, device=device, dtype=dtype) # Broadcasting plane normals+ plane_offsets = torch.randn(1, 1, device=device, dtype=dtype)+ points_uv = torch.randn(B, N, 2, device=device, dtype=dtype)+ camera_matrix = torch.eye(3, device=device, dtype=dtype)++ depth = kornia.geometry.depth.depth_from_plane_equation(+ plane_normals.expand(B, -1),+ plane_offsets.expand(B, -1),+ points_uv,+ camera_matrix.expand(B, -1, -1)+ )+ assert depth.shape == (B, N), f"Expected depth shape to be ({B}, {N}), but got {depth.shape}"++ def test_simple(self, device, dtype):+ """+ Test the function with a simple plane equation to verify numerical correctness.+ Plane equation: z = 2 (plane normal [0, 0, 1], offset 2)+ Expected depth for any point is 2.+ """+ # Define plane parameters+ plane_normals = torch.tensor([[0.0, 0.0, 1.0]], device=device, dtype=dtype) # Shape: (B, 3)+ plane_offsets = torch.tensor([[2.0]], device=device, dtype=dtype)++ # Define pixel coordinates+ points_uv = torch.tensor(+ [+ [[0.0, 0.0],+ [1.0, 0.0],+ [0.0, 1.0],+ [1.0, 1.0]]+ ],+ device=device,+ dtype=dtype,+ ) # Shape: (B, N, 2)++ # Camera intrinsic matrix (identity)+ camera_matrix = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # Shape: (B, 3, 3)++ # Expected depth values+ depth_expected = torch.tensor([[2.0, 2.0, 2.0, 2.0]], device=device, dtype=dtype) # Shape: (B, N)++ # Compute depth+ depth = kornia.geometry.depth.depth_from_plane_equation(plane_normals, plane_offsets, points_uv, camera_matrix)++ # Assert that the computed depth matches the expected depth+ self.assert_close(depth, depth_expected, rtol=1e-6, atol=1e-6)++ def test_gradcheck(self, device):+ B = 2+ N = 5+ plane_normals = torch.rand(B, 3, device=device, dtype=torch.float64, requires_grad=True)+ plane_offsets = torch.rand(B, 1, device=device, dtype=torch.float64, requires_grad=True)+ points_uv = torch.rand(B, N, 2, device=device, dtype=torch.float64, requires_grad=True)+ camera_matrix = torch.eye(3, device=device, dtype=torch.float64).unsqueeze(0).repeat(B, 1, 1)+ camera_matrix.requires_grad_()++ # Perform gradient check+ self.gradcheck(+ kornia.geometry.depth.depth_from_plane_equation,+ (plane_normals, plane_offsets, points_uv, camera_matrix),+ eps=1e-6,+ atol=1e-4,+ )