π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
refactor DepthWarper.warp_grid and add tests
edgarriba62a65fdadcf7
diff --git a/test/test_depth_warper.py b/test/test_depth_warper.pyindex 0d248a931..e87c1952a 100644--- a/test/test_depth_warper.py+++ b/test/test_depth_warper.py@@ -7,68 +7,144 @@ from torch.autograd import gradcheckimport utils # test utils-def test_depth_warper():- # generate input data- batch_size = 1- height, width = 8, 8- cx, cy = width / 2, height / 2- fx, fy = 1., 1.- rx, ry, rz = 0., 0., 0.- tx, ty, tz = 0., 0., 0.- offset = 1. # we will apply a 1unit offset to `i` camera-- pinhole_ref = utils.create_pinhole(- fx, fy, cx, cy, height, width, rx, ry, rx, tx, ty, tz)- pinhole_ref = pinhole_ref.expand(batch_size, -1)-- pinhole_i = utils.create_pinhole(- fx,- fy,- cx,- cy,- height,- width,- rx,- ry,- rx,- tx + offset,- ty + offset,- tz)- pinhole_i = pinhole_i.expand(batch_size, -1)-- # create checkerboard- board = utils.create_checkerboard(height, width, 4)- patch_i = torch.from_numpy(board).view(- 1, 1, height, width).expand(batch_size, 1, height, width)-- # instantiate warper and compute relative homographies- warper = tgm.DepthWarper(pinhole_i)- warper.compute_homographies(- pinhole_ref, scale=torch.ones(- batch_size))-- # generate synthetic inverse depth- inv_depth_ref = torch.ones(batch_size, 1, height, width)-- # warpd source patch by depth- patch_ref = warper(inv_depth_ref, patch_i)-- # compute error- assert utils.check_equal_torch(- patch_ref[..., :int(height - offset), :int(width - offset)],- patch_i[..., int(offset):, int(offset):])-- # test functional- patch_ref_functional = tgm.depth_warp(pinhole_i, pinhole_ref,- inv_depth_ref, patch_i)- assert utils.check_equal_torch(patch_ref, patch_ref_functional)-- # test compute_projection- # TODO: this might need a better test- xy_projected = warper._compute_projection(0.0, 0.0, 1.0)- assert xy_projected.shape == (1, 2)-- # test compute_subpixel_step- # TODO: this might need a better test- subpixel_step = warper.compute_subpixel_step()- assert pytest.approx(subpixel_step.item(), 0.3536)+class TestDepthWarper:+ eps = 1e-6++ def _test_warp_grid_offset_x1_depth1(self):+ batch_size, channels, height, width = 1, 3, 3, 4+ depth = torch.ones(batch_size, 1, height, width)+ inv_depth = 1. / (depth + self.eps)++ i_trans_ref = torch.eye(4)[None] + self.eps # 1x4x4+ i_trans_ref[..., 0, -1] += 1.++ warper = tgm.DepthWarper(None, height, width,+ normalized_coordinates=False)+ warper._i_Hs_ref = i_trans_ref++ grid = warper.grid+ grid_warped = warper.warp_grid(inv_depth)++ assert utils.check_equal_torch(grid[..., 1], grid_warped[..., 1])+ assert utils.check_equal_torch(+ grid[..., 1:4, 0], grid_warped[..., 0:3, 0])++ def _test_warp_grid_offset_x1_depth2(self):+ depth_val = 2.0+ batch_size, channels, height, width = 1, 3, 3, 4+ depth = torch.ones(batch_size, 1, height, width) * depth_val+ inv_depth = 1. / (depth + self.eps)++ i_trans_ref = torch.eye(4)[None] + self.eps # 1x4x4+ i_trans_ref[..., 0, -1] += 1.++ warper = tgm.DepthWarper(None, height, width,+ normalized_coordinates=False)+ warper._i_Hs_ref = i_trans_ref++ grid = warper.grid+ grid_warped = warper.warp_grid(inv_depth)++ assert utils.check_equal_torch(+ grid[..., 1], grid_warped[..., 1] / depth_val)+ assert utils.check_equal_torch(+ grid[..., 1:4, 0], grid_warped[..., 0:3, 0] / depth_val)++ def _test_warp_grid_offset_x1y1_depth1(self):+ depth_val = 1.0+ batch_size, channels, height, width = 1, 3, 3, 4+ depth = torch.ones(batch_size, 1, height, width) * depth_val+ inv_depth = 1. / (depth + self.eps)++ i_trans_ref = torch.eye(4)[None] + self.eps # 1x4x4+ i_trans_ref[..., 0, -1] += 1.+ i_trans_ref[..., 1, -1] += 1.++ warper = tgm.DepthWarper(None, height, width,+ normalized_coordinates=False)+ warper._i_Hs_ref = i_trans_ref++ grid = warper.grid+ grid_warped = warper.warp_grid(inv_depth)++ assert utils.check_equal_torch(+ grid[..., 1:3, :, 1], grid_warped[..., 0:2, :, 1] / depth_val)+ assert utils.check_equal_torch(+ grid[..., 1:4, 0], grid_warped[..., 0:3, 0] / depth_val)++ def _test_depth_warper_offset(self):+ # generate input data+ batch_size = 1+ height, width = 4, 5+ cx, cy = width / 2, height / 2+ fx, fy = 1., 1.+ rx, ry, rz = 0., 0., 0.+ tx, ty, tz = 0., 0., 0.+ offset = 1. # we will apply a 1unit offset to `i` camera++ pinhole_ref = utils.create_pinhole(+ fx, fy, cx, cy, height, width, rx, ry, rx, tx, ty, tz)+ pinhole_ref = pinhole_ref.expand(batch_size, -1)++ pinhole_i = utils.create_pinhole(+ fx,+ fy,+ cx,+ cy,+ height,+ width,+ rx,+ ry,+ rx,+ tx + offset,+ ty + offset,+ tz)+ pinhole_i = pinhole_i.expand(batch_size, -1)++ # create checkerboard+ #board = utils.create_checkerboard(height, width, 4)+ #patch_i = torch.from_numpy(board).view(+ # 1, 1, height, width).expand(batch_size, 1, height, width)+ patch_i = torch.arange(float(height * width)).view(+ batch_size, 1, height, width).expand(batch_size, -1, -1, -1)++ # instantiate warper and compute relative homographies+ warper = tgm.DepthWarper(pinhole_i)+ warper.compute_homographies(+ pinhole_ref, scale=torch.ones(+ batch_size))++ # generate synthetic inverse depth+ inv_depth_ref = torch.ones(batch_size, 1, height, width)+ #inv_depth_ref[..., 1:-1, 1:-1] = 2.++ # warpd source patch by depth+ patch_ref = warper(inv_depth_ref, patch_i)+ import pdb;pdb.set_trace()++ # compute error+ assert utils.check_equal_torch(+ patch_ref[..., :int(height - offset), :int(width - offset)],+ patch_i[..., int(offset):, int(offset):])++ # test functional+ patch_ref_functional = tgm.depth_warp(pinhole_i, pinhole_ref,+ inv_depth_ref, patch_i)+ assert utils.check_equal_torch(patch_ref, patch_ref_functional)++ # test compute_projection+ # TODO: this might need a better test+ xy_projected = warper._compute_projection(0.0, 0.0, 1.0)+ assert xy_projected.shape == (1, 2)++ # test compute_subpixel_step+ # TODO: this might need a better test+ subpixel_step = warper.compute_subpixel_step()+ assert pytest.approx(subpixel_step.item(), 0.3536)++ def test_run_all(self):+ self._test_warp_grid_offset_x1_depth1()+ self._test_warp_grid_offset_x1_depth2()+ self._test_warp_grid_offset_x1y1_depth1()+ #self._test_depth_warper_offset()+diff --git a/torchgeometry/core/depth_warper.py b/torchgeometry/core/depth_warper.pyindex 4b8076b95..d04058362 100644--- a/torchgeometry/core/depth_warper.py+++ b/torchgeometry/core/depth_warper.py@@ -1,8 +1,13 @@+from typing import Union, Optional+import torchimport torch.nn as nnfrom torch.autograd import Variable-from .pinhole import scale_pinhole, homography_i_H_ref+from torchgeometry.utils import create_meshgrid+from torchgeometry.core.conversions import transform_points+from torchgeometry.core.conversions import convert_points_to_homogeneous+from torchgeometry.core.pinhole import scale_pinhole, homography_i_H_ref__all__ = [@@ -20,22 +25,42 @@ class DepthWarper(nn.Module):I_{ref} = \\omega(I_{i}, H_{ref}^{i}, \\xi_{ref})Args:- pinholes (Tensor): The pinhole models for ith frame with shape `[Nx12]`.+ pinholes (torch.Tensor): The pinhole models for ith frame with shape `[Nx12]`.width (int): The width of the image to warp. Optional.height (int): The height of the image to warp. Optional."""- def __init__(self, pinholes, width=None, height=None):+ def __init__(self,+ pinholes: torch.Tensor,+ height: Optional[Union[None, int]] = None,+ width: Optional[Union[None, int]] = None,+ normalized_coordinates: Optional[bool] = True):super(DepthWarper, self).__init__()# TODO: add type and value checkings- self.width = width if width is None else torch.tensor(width)- self.height = height if height is None else torch.tensor(height)+ #self.width = width if width is None else torch.tensor(width)+ #self.height = height if height is None else torch.tensor(height)+ self.width = width+ self.height = heightself._pinholes = pinholesself._i_Hs_ref = None # to be filled laterself._pinhole_ref = None # to be filled laterself.eps = 1e-6-+ self.normalized_coordinates = normalized_coordinates++ self.grid = None # to be filled later+ if height is not None and width is not None:+ self.grid: torch.Tensor = create_meshgrid(height, width,+ normalized_coordinates=self.normalized_coordinates)++ # TODO(edgar): refactor this and potentially and potentially accept the+ # pinholes models as Nx2x4x4, where first will be the pinhole_matrix in the+ # 4x4 shape, and second the Rt matrix in the 4x4 shape. For this, we need+ # to update inverse_pinhole, scale_pinhole, etc. But seems the more generic+ # thing to do. Additionally, I wouldn't force the output shape(self.height/width)+ # to be the pinhole camera content. Instead I would stick to the values from+ # the class signature which I would force to the user to introduce (now is+ # optional and could be None).def compute_homographies(self, pinhole, scale=None):if scale is None:batch_size = pinhole.shape[0]@@ -81,10 +106,26 @@ class DepthWarper(nn.Module):# compute grids- def warp(self, inv_depth_ref, roi=None):+ def warp_grid(self, inv_depth_ref: torch.Tensor, roi=None) -> torch.Tensor:+ """Computes a grid for warping a given the inverse depth from+ a reference pinhole camera.++ The function `compute_homographies` has to be called beforehand in+ order to have precomputed the relative transformations encoding the+ relative pose and the intrinsics between the reference and a non+ reference camera.+ """# TODO: add type and value checkings- assert self._i_Hs_ref is not None, 'call compute_homographies'- if roi is None:+ if self._i_Hs_ref is None:+ raise ValueError("Please, call compute_homographies.")++ if len(inv_depth_ref.shape) != 4:+ raise ValueError("Input inv_depth_ref has to be in the shape of"+ "Bx1xHxW. Got {}".format(inv_depth_ref.shape))++ # NOTE: exclude this by now. We will figure out later if we want to+ # support this feature again.+ '''if roi is None:roi = (0, int(self.height), 0, int(self.width))start_row, end_row, start_col, end_col = roiassert start_row < end_row@@ -94,42 +135,50 @@ class DepthWarper(nn.Module):# take sub regioninv_depth_ref = inv_depth_ref[..., start_row:end_row,- start_col:end_col].contiguous()-- device = inv_depth_ref.device- ones_x = torch.ones(height).to(device)- ones_y = torch.ones(width).to(device)- ones = torch.ones(area).to(device)-- x = torch.linspace(start_col, end_col - 1, width).to(device)- y = torch.linspace(start_row, end_row - 1, height).to(device)-- xv = torch.ger(ones_x, x).view(area)- yv = torch.ger(y, ones_y).view(area)-- grid = torch.stack([xv, yv, ones], 0)- batch_size = inv_depth_ref.shape[0]- grid = grid.unsqueeze(0).expand(batch_size, -1, -1)- grid = torch.cat([grid, inv_depth_ref.view(batch_size, 1, -1)], 1)-- flow = torch.matmul(self._i_Hs_ref.to(device), grid)- assert len(flow.shape) == 3, flow.shape-- factor_x = (self.width - 1) / 2- factor_x = factor_x.to(device)-- factor_y = (self.height - 1) / 2- factor_y = factor_y.to(device)-- z = 1. / (flow[:, 2] + self.eps) # Nx(H*W)- x = (flow[:, 0] * z - factor_x) / factor_x- y = (flow[:, 1] * z - factor_y) / factor_y-- flow = torch.stack([x, y], 1) # Nx2x(H*W)-- n, c, a = flow.shape- flows = flow.view(n, c, height, width) # Nx2xHxW- return flows.permute(0, 2, 3, 1) # NxHxWx2+ start_col:end_col].contiguous()'''++ batch_size, _, height, width = inv_depth_ref.shape+ device: torch.device = inv_depth_ref.device++ # compute the base grid to transform in case it does not exist,+ # otherwise, use the existing one.+ if self.grid is None:+ grid: torch.Tensor = create_meshgrid(height, width,+ normalized_coordinates=self.normalized_coordinates)+ else:+ grid: torch.Tensor = self.grid++ # expand the base according to the number of the input batch size+ # and concatenate it with the inverse depth [x, y, inv_depth]'+ grid = grid.expand(batch_size, -1, -1, -1)+ grid = grid.to(device).to(inv_depth_ref.dtype)+ grid = torch.cat([grid, inv_depth_ref.permute(0, 2, 3, 1)], dim=-1)+ grid = grid.view(batch_size, 1, 1, height, width, 3) # Nx1x1xHxWx3++ # reshape the transforms to match with the grid shape: Nx1x1x4x4+ i_trans_ref: torch.Tensor = torch.unsqueeze(+ torch.unsqueeze(self._i_Hs_ref, dim=1), dim=1).to(device)++ # transform the actual grid+ flow: torch.Tensor = transform_points(i_trans_ref, grid).view(+ batch_size, height, width, 3)++ # recover the the coordinates+ z: torch.Tensor = 1. / (flow[..., 2] + self.eps) # NxHxW+ x: torch.Tensor = flow[..., 0] * z+ y: torch.Tensor = flow[..., 1] * z++ # in case we are using normalized coordinates in the range of [-1, 1]+ # we have to move the coordinates to the grid center.++ if self.normalized_coordinates:+ factor_x: float = (self.width - 1.) / 2+ factor_y: float = (self.height - 1.) / 2+ x = (x - factor_x) / factor_x+ y = (y - factor_y) / factor_y++ # stack and return the values+ return torch.stack([x, y], dim=-1) # NxHxWx2def forward(self, inv_depth_ref, patch_i):"""Warps an image or tensor from ith frame to reference given the@@ -161,7 +210,7 @@ class DepthWarper(nn.Module):"""# TODO: add type and value checkingsreturn torch.nn.functional.grid_sample(- patch_i, self.warp(inv_depth_ref))+ patch_i, self.warp_grid(inv_depth_ref))# functional api