π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix minimal issues
edgarriba94819f8d231c
diff --git a/test/test_depth_warper.py b/test/test_depth_warper.pyindex e87c1952a..c4ae95bde 100644--- a/test/test_depth_warper.py+++ b/test/test_depth_warper.py@@ -5,146 +5,149 @@ import torchgeometry as tgmfrom torch.autograd import gradcheckimport utils # test utils+from torchgeometry.core.depth_warper import PinholeCamera+from torchgeometry.core.depth_warper import normalize_pixel_coordinatesclass TestDepthWarper:eps = 1e-6+ def _test_compute_projection_matrix(self):+ # prepare data+ batch_size, height, width = 1, 3, 5+ fx, fy = 1., 1.+ cx, cy = width / 2, height / 2+ tx, ty, tz = 0, 0, 0++ # create pinhole cameras+ pinhole_src = PinholeCamera.from_parameters(+ fx, fy, cx, cy, height, width, tx, ty, tz)+ pinhole_dst = PinholeCamera.from_parameters(+ fx, fy, cx, cy, height, width, tx + 1., ty, tz)++ # create warper+ warper = tgm.DepthWarper(None, height, width, pinhole_dst)+ 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] # Bx4x4+ dst_proj_src_expected[..., 0, -2] += cx+ dst_proj_src_expected[..., 1, -2] += cy+ dst_proj_src_expected[..., 0, -1] += 1. # offset to x-axis+ assert utils.check_equal_torch(dst_proj_src, dst_proj_src_expected)+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)+ # prepare data+ batch_size, height, width = 1, 3, 5+ fx, fy = 1., 1.+ cx, cy = width / 2, height / 2+ tx, ty, tz = 0, 0, 0++ # create pinhole cameras+ pinhole_src = PinholeCamera.from_parameters(+ fx, fy, cx, cy, height, width, tx, ty, tz)+ pinhole_dst = PinholeCamera.from_parameters(+ fx, fy, cx, cy, height, width, tx + 1., ty, tz)- i_trans_ref = torch.eye(4)[None] + self.eps # 1x4x4- i_trans_ref[..., 0, -1] += 1.+ # initialize depth to one+ depth_src = torch.ones(batch_size, 1, height, width)- warper = tgm.DepthWarper(None, height, width,- normalized_coordinates=False)- warper._i_Hs_ref = i_trans_ref+ # create warper, initialize projection matrices and warp grid+ warper = tgm.DepthWarper(None, height, width, pinhole_dst)+ warper.compute_projection_matrix(pinhole_src)+ grid_warped = warper.warp_grid(depth_src)- grid = warper.grid- grid_warped = warper.warp_grid(inv_depth)+ # normalize base meshgrid+ grid = warper.grid[..., :2]+ grid_norm = normalize_pixel_coordinates(grid, height, width)- assert utils.check_equal_torch(grid[..., 1], grid_warped[..., 1])+ # check offset in x-axisassert utils.check_equal_torch(- grid[..., 1:4, 0], grid_warped[..., 0:3, 0])+ grid_norm[..., -1, 0], grid_warped[..., -2, 0])+ # check that y-axis remain the same+ assert utils.check_equal_torch(+ grid_norm[..., -1, 1], grid_warped[..., -1, 1])++ def _test_warp_grid_offset_x1y1_depth1(self):+ # prepare data+ batch_size, height, width = 1, 3, 5+ fx, fy = 1., 1.+ cx, cy = width / 2, height / 2+ tx, ty, tz = 0, 0, 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)+ # create pinhole cameras+ pinhole_src = PinholeCamera.from_parameters(+ fx, fy, cx, cy, height, width, tx, ty, tz)+ pinhole_dst = PinholeCamera.from_parameters(+ fx, fy, cx, cy, height, width, tx + 1., ty + 1., tz)- i_trans_ref = torch.eye(4)[None] + self.eps # 1x4x4- i_trans_ref[..., 0, -1] += 1.+ # initialize depth to one+ depth_src = torch.ones(batch_size, 1, height, width)- warper = tgm.DepthWarper(None, height, width,- normalized_coordinates=False)- warper._i_Hs_ref = i_trans_ref+ # create warper, initialize projection matrices and warp grid+ warper = tgm.DepthWarper(None, height, width, pinhole_dst)+ warper.compute_projection_matrix(pinhole_src)+ grid_warped = warper.warp_grid(depth_src)- grid = warper.grid- grid_warped = warper.warp_grid(inv_depth)+ # normalize base meshgrid+ grid = warper.grid[..., :2]+ grid_norm = normalize_pixel_coordinates(grid, height, width)+ # check offset in x-axisassert utils.check_equal_torch(- grid[..., 1], grid_warped[..., 1] / depth_val)+ grid_norm[..., -1, 0], grid_warped[..., -2, 0])+ # check that y-axis remain the sameassert utils.check_equal_torch(- grid[..., 1:4, 0], grid_warped[..., 0:3, 0] / depth_val)+ grid_norm[..., -1, :, 1], grid_warped[..., -2, :, 1])- 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)+ def _test_depth_warper_offset_tensor(self):+ # prepare data+ batch_size, channels, height, width = 1, 3, 3, 5+ fx, fy = 1., 1.+ cx, cy = width / 2, height / 2+ tx, ty, tz = 0, 0, 0- i_trans_ref = torch.eye(4)[None] + self.eps # 1x4x4- i_trans_ref[..., 0, -1] += 1.- i_trans_ref[..., 1, -1] += 1.+ # create pinhole cameras+ pinhole_src = PinholeCamera.from_parameters(+ fx, fy, cx, cy, height, width, tx, ty, tz)+ pinhole_dst = PinholeCamera.from_parameters(+ fx, fy, cx, cy, height, width, tx + 1., ty + 1., tz)- warper = tgm.DepthWarper(None, height, width,- normalized_coordinates=False)- warper._i_Hs_ref = i_trans_ref+ # initialize depth to one+ depth_src = torch.ones(batch_size, 1, height, width)- grid = warper.grid- grid_warped = warper.warp_grid(inv_depth)+ # create warper, initialize projection matrices and warp grid+ warper = tgm.DepthWarper(None, height, width, pinhole_dst)+ warper.compute_projection_matrix(pinhole_src)- 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)+ # create patch to warp+ patch_dst = torch.arange(float(height * width)).view(+ batch_size, 1, height, width).expand(batch_size, channels, -1, -1)- 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+ patch_src = warper(depth_src, patch_dst)++ # compare patchesassert 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)-+ patch_dst[..., 1:, 1:], patch_src[..., :2, :4])+# test compute_projection# TODO: this might need a better testxy_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 testsubpixel_step = warper.compute_subpixel_step()assert pytest.approx(subpixel_step.item(), 0.3536)def test_run_all(self):+ self._test_compute_projection_matrix()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()-+ self._test_depth_warper_offset_tensor()diff --git a/torchgeometry/core/depth_warper.py b/torchgeometry/core/depth_warper.pyindex d04058362..32c1d2294 100644--- a/torchgeometry/core/depth_warper.py+++ b/torchgeometry/core/depth_warper.py@@ -1,12 +1,14 @@-from typing import Union, Optional+from typing import Optionalimport torchimport torch.nn as nn-from torch.autograd import Variable+import torch.nn.functional as Ffrom torchgeometry.utils import create_meshgridfrom torchgeometry.core.conversions import transform_pointsfrom torchgeometry.core.conversions import convert_points_to_homogeneous+from torchgeometry.core.transformations import relative_pose+# NOTE: remove laterfrom torchgeometry.core.pinhole import scale_pinhole, homography_i_H_ref@@ -16,6 +18,140 @@ __all__ = []+def normalize_pixel_coordinates(+ pixel_coordinates: torch.Tensor,+ height: float,+ width: float) -> torch.Tensor:+ r"""Normalize pixel coordinates between -1 and 1.++ Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).++ Args:+ pixel_coordinate (torch.Tensor): the grid with pixel coordinates.+ Shape must be BxHxWx2.+ width (int): the maximum width in the x-axis.+ height (int): the maximum height in the y-axis.++ Return:+ torch.Tensor: the nornmalized pixel coordinates.+ """+ if len(pixel_coordinates.shape) != 4 and pixel_coordinates.shape[-1] != 2:+ raise ValueError("Input pixel_coordinates must be of shape BxHxWx2. "+ "Got {}".format(pixel_coordinates.shape))++ # unpack pixel coordinates+ u_coord, v_coord = torch.chunk(pixel_coordinates, dim=-1, chunks=2)++ # apply actual normalization+ factor_u: float = 2. / (width - 1)+ factor_v: float = 2. / (height - 1)+ u_coord_norm: torch.Tensor = factor_u * u_coord - 1.+ v_coord_norm: torch.Tensor = factor_v * v_coord - 1.++ # stack normalized coordinates and return+ pixel_coordinates_norm: torch.Tensor = torch.cat(+ [u_coord_norm, v_coord_norm], dim=-1)+ return pixel_coordinates_norm+++# based on:+# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L26++def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor,+ pixel_coords: torch.Tensor) -> torch.Tensor:+ r"""Transform coordinates in the pixel frame to the camera frame.++ Args:+ depth (torch.Tensor): the source depth maps. Shape must be Bx1xHxW.+ intrinsics_inv (torch.Tensor): the inverse intrinsics camera matrix.+ Shape must be Bx4x4.+ pixel_coords (torch.Tensor): the grid with the homogeneous camera+ coordinates. Shape must be BxHxWx3.++ Returns:+ torch.Tensor: array of (u, v, 1) cam coordinates with shape BxHxWx3.+ """+ if not len(depth.shape) == 4 and depth.shape[1] == 1:+ raise ValueError("Input depth has to be in the shape of "+ "Bx1xHxW. Got {}".format(depth.shape))+ if not len(intrinsics_inv.shape) == 3:+ raise ValueError("Input intrinsics_inv has to be in the shape of "+ "Bx4x4. Got {}".format(intrincsics_inv.shape))+ if not len(pixel_coords.shape) == 4 and pixel_coords.shape[3] == 3:+ raise ValueError("Input pixel_coords has to be in the shape of "+ "BxHxWx3. Got {}".format(intrincsics_inv.shape))+ cam_coords: torch.Tensor = transform_points(intrinsics_inv, pixel_coords)+ return cam_coords * depth.permute(0, 2, 3, 1)+++# based on+# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L43++def cam2pixel(+ cam_coords_src: torch.Tensor,+ dst_proj_src: torch.Tensor,+ eps: Optional[float] = 1e-6) -> torch.Tensor:+ r"""Transform coordinates in the camera frame to the pixel frame.++ Args:+ cam_coords (torch.Tensor): pixel coordinates defined in the first+ camera coordinates system. Shape must be BxHxWx3.+ dst_proj_src (torch.Tensor): the projection matrix between the+ reference and the non reference camera frame. Shape must be Bx4x4.++ Returns:+ torch.Tensor: array of [-1, 1] coordinates of shape BxHxWx2.+ """+ if not len(cam_coords_src.shape) == 4 and cam_coords_src.shape[3] == 3:+ raise ValueError("Input cam_coords_src has to be in the shape of "+ "BxHxWx3. Got {}".format(depth.shape))+ if not len(dst_proj_src.shape) == 3 and dst_proj_src.shape[-2:] == (4, 4):+ raise ValueError("Input dst_proj_src has to be in the shape of "+ "Bx4x4. Got {}".format(dst_proj_src.shape))+ b, h, w, _ = cam_coords_src.shape+ # apply projection matrix to points+ point_coords: torch.Tensor = transform_points(dst_proj_src, cam_coords_src)+ x_coord: torch.Tensor = point_coords[..., 0]+ y_coord: torch.Tensor = point_coords[..., 1]+ z_coord: torch.Tensor = point_coords[..., 2]++ # compute pixel coordinates+ u_coord: torch.Tensor = x_coord / (z_coord + eps)+ v_coord: torch.Tensor = y_coord / (z_coord + eps)++ # stack and return the coordinates, that's the actual flow+ pixel_coords_dst: torch.Tensor = torch.stack([u_coord, v_coord], dim=-1)+ return pixel_coords_dst # BxHxWx2+++class PinholeCamera:+ # TODO: add more documentation+ def __init__(self, intrinsics, extrinsics):+ self.intrinsics = intrinsics+ self.extrinsics = extrinsics++ def intrinsics_inverse(self):+ return self.intrinsics.inverse()++ # NOTE: just for test. Decide if we keep it.+ @classmethod+ def from_parameters(self, fx, fy, cx, cy, height, width, tx, ty, tz):+ # create the camera matrix+ intrinsics = torch.zeros(1, 4, 4)+ intrinsics[..., 0, 0] += fx+ intrinsics[..., 1, 1] += fy+ intrinsics[..., 0, 2] += cx+ intrinsics[..., 1, 2] += cy+ intrinsics[..., 2, 2] += 1.0+ intrinsics[..., 3, 3] += 1.0+ # create the pose matrix+ extrinsics = torch.eye(4)[None]+ extrinsics[..., 0, -1] += tx+ extrinsics[..., 1, -1] += ty+ extrinsics[..., 2, -1] += tz+ return self(intrinsics, extrinsics)++class DepthWarper(nn.Module):"""Warps a patch by inverse depth.@@ -33,26 +169,35 @@ class DepthWarper(nn.Module):def __init__(self,pinholes: torch.Tensor,- height: Optional[Union[None, int]] = None,- width: Optional[Union[None, int]] = None,- normalized_coordinates: Optional[bool] = True):+ height: int,+ width: int,+ pinhole_dst):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- self.height = height+ self.width: int = width+ self.height: int = height+ self.eps = 1e-6++ # old parametersself._pinholes = pinholesself._i_Hs_ref = None # to be filled laterself._pinhole_ref = None # to be filled later- self.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)-+ # new refactor parameters+ self.grid: torch.Tensor = self._create_meshgrid(height, width)+ self._pinhole_src = None # to be filled later+ self._dst_proj_src = None # to be filled later++ if not isinstance(pinhole_dst, PinholeCamera):+ raise TypeError("Argument pinhole_dst expected to be of class "+ "PinholeCamera. Got {}".format(type(pinhole_dst)))+ self._pinhole_dst = pinhole_dst++ @staticmethod+ def _create_meshgrid(height: int, width: int) -> torch.Tensor:+ grid: torch.Tensor = create_meshgrid(+ height, width, normalized_coordinates=False) # 1xHxWx2+ return convert_points_to_homogeneous(grid) # append ones to last dim+# 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@@ -78,9 +223,30 @@ class DepthWarper(nn.Module):pinhole_i = scale_pinhole(self._pinholes, scale)self._i_Hs_ref = homography_i_H_ref(pinhole_i, pinhole_ref)+ def compute_projection_matrix(self, pinhole_src):+ # TODO: add documentation+ if not isinstance(pinhole_src, PinholeCamera):+ raise TypeError("Argument pinhole_src expected to be of class "+ "PinholeCamera. Got {}".format(type(pinhole_dst)))+ # compute the relative pose between the non reference and the reference+ # camera frames.+ dst_trans_src = relative_pose(+ pinhole_src.extrinsics, self._pinhole_dst.extrinsics)++ # compute the projection matrix between the non reference cameras and+ # the reference.+ self._dst_proj_src = torch.matmul(+ self._pinhole_dst.intrinsics, dst_trans_src)++ # update class member+ self._pinhole_src = pinhole_src+ return self+def _compute_projection(self, x, y, invd):point = torch.FloatTensor([[[x], [y], [1.0], [invd]]])- flow = torch.matmul(self._i_Hs_ref, point.to(self._i_Hs_ref.device))+ #flow = torch.matmul(self._i_Hs_ref, point.to(self._i_Hs_ref.device))+ flow = torch.matmul(+ self._dst_proj_src, point.to(self._dst_proj_src.device))z = 1. / flow[:, 2]x = (flow[:, 0] * z)y = (flow[:, 1] * z)@@ -105,11 +271,54 @@ class DepthWarper(nn.Module):return torch.min(0.5 / dxdd)# compute grids+ def warp_grid(self, depth_src: torch.Tensor) -> torch.Tensor:+ """Computes a grid for warping a given the depth from the reference+ pinhole camera.- def warp_grid(self, inv_depth_ref: torch.Tensor, roi=None) -> torch.Tensor:+ The function `compute_projection_matrix` has to be called beforehand in+ order to have precomputed the relative projection matrices encoding the+ relative pose and the intrinsics between the reference and a non+ reference camera.+ """+ # TODO: add type and value checkings+ if self._dst_proj_src is None or self._pinhole_src is None:+ raise ValueError("Please, call compute_projection_matrix.")++ if len(depth_src.shape) != 4:+ raise ValueError("Input depth_src has to be in the shape of"+ "Bx1xHxW. Got {}".format(inv_depth_ref.shape))++ # unpack depth attributes+ batch_size, _, height, width = depth_src.shape+ device: torch.device = depth_src.device+ dtype: torch.dtype = depth_src.dtype++ # expand the base coordinate grid according to the input batch size+ pixel_coords: torch.Tensor = self.grid.to(device).to(dtype).expand(+ batch_size, -1, -1, -1)++ # reproject the pixel coordinates to the camera frame+ cam_coords_src: torch.Tensor = pixel2cam(+ depth_src,+ self._pinhole_src.intrinsics_inverse(),+ pixel_coords) # BxHxWx3++ # reproject the camera coordinates to the pixel+ pixel_coords_src: torch.Tensor = cam2pixel(+ cam_coords_src, self._dst_proj_src) # BxHxWx2++ # normalize between -1 and 1 the coordinates+ pixel_coords_src_norm: torch.Tensor = normalize_pixel_coordinates(+ pixel_coords_src, self.height, self.width)+ return pixel_coords_src_norm++ def warp_grid_old(+ self,+ inv_depth_ref: torch.Tensor,+ roi=None) -> torch.Tensor:"""Computes a grid for warping a given the inverse depth froma reference pinhole camera.-+The function `compute_homographies` has to be called beforehand inorder to have precomputed the relative transformations encoding therelative pose and the intrinsics between the reference and a non@@ -139,19 +348,14 @@ class DepthWarper(nn.Module):batch_size, _, height, width = inv_depth_ref.shapedevice: 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+ dtype: torch.dtype = inv_depth_ref.dtype# 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)+ import pdb+ pdb.set_trace()+ grid: torch.Tensor = self.grid.to(device).to(dtype).expand(+ batch_size, -1, -1, -1)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@@ -170,15 +374,17 @@ class DepthWarper(nn.Module):# in case we are using normalized coordinates in the range of [-1, 1]# we have to move the coordinates to the grid center.+ x_norm: torch.Tensor = x+ y_norm: torch.Tensor = yif 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+ factor_x: float = 2. / (self.width - 1.)+ factor_y: float = 2. / (self.height - 1.)+ x_norm = factor_x * x - 1.+ y_norm = factor_y * y - 1.# stack and return the values- return torch.stack([x, y], dim=-1) # NxHxWx2+ return torch.stack([x_norm, y_norm], dim=-1) # NxHxWx2def forward(self, inv_depth_ref, patch_i):"""Warps an image or tensor from ith frame to reference given the