π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
simplify DepthWarper API removing input iterable
edgarriba3ee24751e3b8
diff --git a/test/test_depth_warper.py b/test/test_depth_warper.pyindex 2a62aacc8..24b5bfcb8 100644--- a/test/test_depth_warper.py+++ b/test/test_depth_warper.py@@ -26,13 +26,13 @@ class TestDepthWarper:return pinhole_src, pinhole_dst@pytest.mark.parametrize("batch_size", (1, 2,))- def test_compute_projection_matrix_one_cam(self, batch_size):+ def test_compute_projection_matrix(self, batch_size):height, width = 3, 5 # output shapepinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)pinhole_dst.tx += 1. # apply offset to tx# create warper- warper = tgm.DepthWarper([pinhole_dst, ], height, width)+ warper = tgm.DepthWarper(pinhole_dst, height, width)assert warper._dst_proj_src is None# initialize projection matrices@@ -49,30 +49,7 @@ class TestDepthWarper:assert utils.check_equal_torch(dst_proj_src, dst_proj_src_expected)@pytest.mark.parametrize("batch_size", (1, 2,))- def test_compute_projection_matrix_two_cams(self, batch_size):- height, width = 3, 5 # output shape- pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)- pinhole_dst.tx += 1. # apply offset to tx-- # create warper- warper = tgm.DepthWarper([pinhole_dst, pinhole_src], height, width)- assert warper._dst_proj_src is None-- # initialize projection matrices- warper.compute_projection_matrix(pinhole_src)- assert warper._dst_proj_src is not None-- # retreive computed projection matrix and compare to expected- dst_proj_src = warper._dst_proj_src- dst_proj_src_expected = torch.eye(- 4)[None, None].repeat(1, 2, 1, 1) # BxNx4x4- dst_proj_src_expected[..., 0, -2] += pinhole_src.cx- dst_proj_src_expected[..., 1, -2] += pinhole_src.cy- dst_proj_src_expected[..., 0, 0, -1] += 1. # offset to x-axis- assert utils.check_equal_torch(dst_proj_src, dst_proj_src_expected)-- @pytest.mark.parametrize("batch_size", (1, 2,))- def test_warp_grid_offset_x1_depth1_one_cam(self, batch_size):+ def test_warp_grid_offset_x1_depth1(self, batch_size):height, width = 3, 5 # output shapepinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)pinhole_dst.tx += 1. # apply offset to tx@@ -81,7 +58,7 @@ class TestDepthWarper:depth_src = torch.ones(batch_size, 1, height, width)# create warper, initialize projection matrices and warp grid- warper = tgm.DepthWarper([pinhole_dst, ], height, width)+ warper = tgm.DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)grid_warped = warper.warp_grid(depth_src)@@ -109,7 +86,7 @@ class TestDepthWarper:depth_src = torch.ones(batch_size, 1, height, width)# create warper, initialize projection matrices and warp grid- warper = tgm.DepthWarper([pinhole_dst, ], height, width)+ warper = tgm.DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)grid_warped = warper.warp_grid(depth_src)@@ -126,37 +103,6 @@ class TestDepthWarper:assert utils.check_equal_torch(grid_norm[..., -1, :, 1], grid_warped[..., -2, :, 1])- @pytest.mark.parametrize("batch_size", (1, 2,))- def test_warp_grid_offset_x1y1_depth1_two_cams(self, batch_size):- height, width = 3, 5 # output shape- pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)- pinhole_dst.tx += 1. # apply offset to tx- pinhole_dst.ty += 1. # apply offset to ty- num_cams = 2-- # initialize depth to one- depth_src = torch.ones(batch_size, 1, height, width)-- # create warper, initialize projection matrices and warp grid- warper = tgm.DepthWarper([pinhole_dst, pinhole_src], height, width)- warper.compute_projection_matrix(pinhole_src)-- grid_warped = warper.warp_grid(depth_src)- assert grid_warped.shape == (batch_size * num_cams, height, width, 2)-- # normalize base meshgrid- grid = warper.grid[..., :2]- grid_norm = normalize_pixel_coordinates(grid, height, width)-- # check offset in x-axis in the first camera- assert utils.check_equal_torch(- grid_norm[0:1, ..., -1, 0], grid_warped[0:1, ..., -2, 0])- # check offset in y-axis in the first camera- assert utils.check_equal_torch(- grid_norm[0:1, ..., -1, :, 1], grid_warped[0:1, ..., -2, :, 1])- # check that second camera grid is the same- assert utils.check_equal_torch(grid_norm, grid_warped[1:2])-@pytest.mark.parametrize("batch_size", (1, 2,))def test_warp_tensor_offset_x1y1(self, batch_size):channels, height, width = 3, 3, 5 # output shape@@ -168,7 +114,7 @@ class TestDepthWarper:depth_src = torch.ones(batch_size, 1, height, width)# create warper, initialize projection matrices and warp grid- warper = tgm.DepthWarper([pinhole_dst, ], height, width)+ warper = tgm.DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)# create patch to warp@@ -182,43 +128,13 @@ class TestDepthWarper:assert utils.check_equal_torch(patch_dst[..., 1:, 1:], patch_src[..., :2, :4])- @pytest.mark.parametrize("batch_size", (1,))- def test_warp_tensor_offset_x1y1_two_cams(self, batch_size):- # prepare data- num_cameras = 2- channels, height, width = 3, 3, 5 # output shape- pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)- pinhole_dst.tx += 1. # apply offset to tx- pinhole_dst.ty += 1. # apply offset to ty-- # initialize depth to one- depth_src = torch.ones(batch_size, 1, height, width)-- # create warper, initialize projection matrices and warp grid- warper = tgm.DepthWarper([pinhole_dst, pinhole_src], height, width)- warper.compute_projection_matrix(pinhole_src)-- # create patch to warp- patch_dst = torch.arange(float(height * width))[None, None, None]- patch_dst = patch_dst.repeat(batch_size, num_cameras, channels, 1, 1)- patch_dst[:, 1] *= 2- patch_dst = patch_dst.view(-1, channels, height, width)-- # warpd source patch by depth- patch_src = warper(depth_src, patch_dst)-- # compare patches- assert utils.check_equal_torch(- patch_dst[:1, ..., 1:, 1:], patch_src[:1, ..., :2, :4])- assert utils.check_equal_torch(patch_dst[1:], patch_src[1:])-@pytest.mark.parametrize("batch_size", (1, 2,))def test_compute_projection(self, batch_size):height, width = 3, 5 # output shapepinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)# create warper, initialize projection matrices and warp grid- warper = tgm.DepthWarper([pinhole_dst, ], height, width)+ warper = tgm.DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)# test compute_projection@@ -231,7 +147,7 @@ class TestDepthWarper:pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)# create warper, initialize projection matrices and warp grid- warper = tgm.DepthWarper([pinhole_dst, ], height, width)+ warper = tgm.DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)# test compute_subpixel_step@@ -254,8 +170,7 @@ class TestDepthWarper:# evaluate function gradientassert gradcheck(tgm.depth_warp,- ([pinhole_dst,- ],+ (pinhole_dst,pinhole_src,depth_src,img_dst,diff --git a/torchgeometry/core/depth_warper.py b/torchgeometry/core/depth_warper.pyindex 8aa76b3b2..284695ca4 100644--- a/torchgeometry/core/depth_warper.py+++ b/torchgeometry/core/depth_warper.py@@ -1,4 +1,4 @@-from typing import Optional, Iterable, Union+from typing import Optional, Unionimport torchimport torch.nn as nnimport torch.nn.functional as F@@ -27,8 +27,8 @@ class DepthWarper(nn.Module):I_{src} = \\omega(I_{dst}, P_{src}^{\{dst\}}, D_{src})Args:- pinholes_dst (Iterable[PinholeCamera]): the pinhole models for the- destination frame.+ pinholes_dst (PinholeCamera): the pinhole models for the destination+ frame.height (int): the height of the image to warp.width (int): the width of the image to warp.mode (Optional[str]): interpolation mode to calculate output values@@ -38,7 +38,7 @@ class DepthWarper(nn.Module):"""def __init__(self,- pinholes_dst: Iterable[PinholeCamera],+ pinhole_dst: PinholeCamera,height: int, width: int,mode: Optional[str] = 'bilinear',padding_mode: Optional[str] = 'zeros'):@@ -51,7 +51,7 @@ class DepthWarper(nn.Module):self.eps = 1e-6# state members- self._pinhole_dst: PinholeCamerasList = PinholeCamerasList(pinholes_dst)+ self._pinhole_dst: PinholeCamera = pinhole_dstself._pinhole_src: Union[None, PinholeCamera] = Noneself._dst_proj_src: Union[None, torch.Tensor] = None@@ -67,39 +67,32 @@ class DepthWarper(nn.Module):self, pinhole_src: PinholeCamera) -> 'DepthWarper':r"""Computes the projection matrix from the source to destinaion frame."""+ if not isinstance(self._pinhole_dst, PinholeCamera):+ raise TypeError("Member self._pinhole_dst expected to be of class "+ "PinholeCamera. Got {}"+ .format(type(self._pinhole_dst)))if not isinstance(pinhole_src, PinholeCamera):raise TypeError("Argument pinhole_src expected to be of class ""PinholeCamera. Got {}".format(type(pinhole_src)))# compute the relative pose between the non reference and the reference# camera frames.- batch_size: int = pinhole_src.batch_size- num_cameras: int = self._pinhole_dst.num_cameras-- extrinsics_src: torch.Tensor = pinhole_src.extrinsics[:, None].expand(- -1, num_cameras, -1, -1) # BxNx4x4- extrinsics_src = extrinsics_src.contiguous().view(-1, 4, 4) # (B*N)x4x4- extrinsics_dst: torch.Tensor = self._pinhole_dst.extrinsics.view(- -1, 4, 4) # (B*N)x4x4dst_trans_src: torch.Tensor = relative_transformation(- extrinsics_src, extrinsics_dst)+ pinhole_src.extrinsics, self._pinhole_dst.extrinsics)# compute the projection matrix between the non reference cameras and# the reference.- intrinsics_dst: torch.Tensor = self._pinhole_dst.intrinsics.view(- -1, 4, 4)dst_proj_src: torch.Tensor = torch.matmul(- intrinsics_dst, dst_trans_src)+ self._pinhole_dst.intrinsics, dst_trans_src)# update class membersself._pinhole_src = pinhole_src- self._dst_proj_src = dst_proj_src.view(- pinhole_src.batch_size, -1, 4, 4)+ self._dst_proj_src = dst_proj_srcreturn selfdef _compute_projection(self, x, y, invd):point = torch.FloatTensor([[[x], [y], [1.0], [invd]]])flow = torch.matmul(- self._dst_proj_src[:, 0], point.to(self._dst_proj_src.device))+ self._dst_proj_src, point.to(self._dst_proj_src.device))z = 1. / flow[:, 2]x = (flow[:, 0] * z)y = (flow[:, 1] * z)@@ -155,16 +148,9 @@ class DepthWarper(nn.Module):self._pinhole_src.intrinsics_inverse().to(dtype),pixel_coords) # BxHxWx3- # create views from tensors to match with cam2pixel expected shapes- cam_coords_src = cam_coords_src[:, None].expand(- -1, self._pinhole_dst.num_cameras, -1, -1, -1) # BxNxHxWx3- cam_coords_src = cam_coords_src.contiguous().view(- -1, height, width, 3) # (B*N)xHxWx3- dst_proj_src: torch.Tensor = self._dst_proj_src.view(-1, 4, 4)-# reproject the camera coordinates to the pixelpixel_coords_src: torch.Tensor = cam2pixel(- cam_coords_src, dst_proj_src.to(dtype)) # (B*N)xHxWx2+ cam_coords_src, self._dst_proj_src.to(dtype)) # (B*N)xHxWx2# normalize between -1 and 1 the coordinatespixel_coords_src_norm: torch.Tensor = normalize_pixel_coordinates(@@ -195,12 +181,12 @@ class DepthWarper(nn.Module):>>> pinhole_dst = tgm.PinholeCamera(...)>>> pinhole_src = tgm.PinholeCamera(...)>>> # create the depth warper, compute the projection matrix- >>> warper = tgm.DepthWarper([pinhole_dst, ], height, width)+ >>> warper = tgm.DepthWarper(pinhole_dst, height, width)>>> warper.compute_projection_matrix(pinhole_src)>>> # warp the destionation frame to reference by depth>>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW>>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW- >>> image_src = warper(depth_src, image_dst) # NxCxHxW+ >>> image_src = warper(depth_src, image_dst) # NxCxHxW"""return F.grid_sample(patch_dst, self.warp_grid(depth_src),mode=self.mode, padding_mode=self.padding_mode)@@ -208,7 +194,7 @@ class DepthWarper(nn.Module):# functional api-def depth_warp(pinholes_dst: Iterable[PinholeCamera],+def depth_warp(pinhole_dst: PinholeCamera,pinhole_src: PinholeCamera,depth_src: torch.Tensor,patch_dst: torch.Tensor,@@ -225,9 +211,9 @@ def depth_warp(pinholes_dst: Iterable[PinholeCamera],>>> # warp the destionation frame to reference by depth>>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW>>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW- >>> image_src = tgm.depth_warp([pinhole_dst, ], pinhole_src,+ >>> image_src = tgm.depth_warp(pinhole_dst, pinhole_src,>>> depth_src, image_dst, height, width) # NxCxHxW"""- warper = DepthWarper(pinholes_dst, height, width)+ warper = DepthWarper(pinhole_dst, height, width)warper.compute_projection_matrix(pinhole_src)return warper(depth_src, patch_dst)