π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix warp_perspective
edgarriba3470180ff61c
diff --git a/test/test_imgwarp.py b/test/test_imgwarp.pyindex 7261313a8..4c7be0617 100644--- a/test/test_imgwarp.py+++ b/test/test_imgwarp.py@@ -12,7 +12,7 @@ class Tester(unittest.TestCase):def test_warp_perspective(self):# generate input databatch_size = 1- height, width = 64, 64+ height, width = 2, 4alpha = tgm.pi / 2 # 90 deg rotation# create data patch@@ -26,6 +26,7 @@ class Tester(unittest.TestCase):]]) # Bx3x3# apply transformation and inverse+ import ipdb;ipdb.set_trace()_, _, h, w = patch.shapepatch_warped = tgm.warp_perspective(patch, M, dsize=(height, width))patch_warped_inv = tgm.warp_perspective(patch_warped, tgm.inverse(M),diff --git a/test/test_utils.py b/test/test_utils.pyindex d293d2663..17799aadf 100644--- a/test/test_utils.py+++ b/test/test_utils.py@@ -21,6 +21,19 @@ class Tester(unittest.TestCase):self.assertTrue(tensor.shape == (3, 4, 4))self.assertIsInstance(tensor, torch.Tensor)+ def test_create_meshgrid(self):+ height, width = 4, 6+ normalized_coordinates = False++ # create the meshgrid and verify shape+ grid = tgm.create_meshgrid(height, width, normalized_coordinates)+ self.assertTrue(grid.shape == (1, height, width, 2))++ # check grid corner values+ self.assertTrue(tuple(grid[0, 0, 0].numpy()) == (0., 0.))+ self.assertTrue(tuple(+ grid[0, height - 1, width - 1].numpy()) == (width - 1, height - 1))+if __name__ == '__main__':unittest.main()diff --git a/torchgeometry/homography_warper.py b/torchgeometry/homography_warper.pyindex abe699bd4..4a6832968 100644--- a/torchgeometry/homography_warper.py+++ b/torchgeometry/homography_warper.py@@ -2,6 +2,7 @@ import torchimport torch.nn as nnimport torch.nn.functional as F+from .utils import create_meshgridfrom .conversions import transform_points@@ -11,22 +12,6 @@ __all__ = []-def create_meshgrid(height, width, normalized_coordinates=True):- '''Generates a coordinate grid for an image of width(cols), height(rows).- This is normalized to be in the range [-1,1] to be consistent with the- pytorch function grid_sample.- http://pytorch.org/docs/master/nn.html#torch.nn.functional.grid_sample- Returns a 3xN matrix.- '''- if normalized_coordinates:- xs = torch.linspace(-1, 1, width)- ys = torch.linspace(-1, 1, height)- else:- xs = torch.linspace(0, width - 1, width)- ys = torch.linspace(0, height - 1, height)- return torch.stack(torch.meshgrid([ys, xs])).view(1, 2, -1)[:, (1, 0), :]--# layer apiclass HomographyWarper(nn.Module):@@ -54,8 +39,8 @@ class HomographyWarper(nn.Module):self.width = widthself.height = height# create base grid to use for computing the flow- grid = create_meshgrid(height, width, normalized_coordinates=True)- self.grid = grid.permute(0, 2, 1) # 1x(H*W)x2+ self.grid = create_meshgrid(height, width,+ normalized_coordinates=True)def warp_grid(self, H):"""@@ -64,11 +49,10 @@ class HomographyWarper(nn.Module)::returns: Tensor[1, Height, Width, 2] containing transformed points innormalized images space."""- grid = self.grid- if len(H.shape) > 3: # local homography case- grid = grid.view(*H.shape[:-2], 2) # 1xHxWx2batch_size = H.shape[0] # expand grid to match the input batch size- grid = grid.expand(batch_size, *grid.shape[1:]) # Nx(...)x2+ grid = self.grid.repeat(batch_size, 1, 1, 1) # NxHxWx2+ if len(H.shape) == 3: # local homography case+ grid = grid.view(batch_size, -1, 2) # Nx(H*W)x2# perform the actual grid transformation,# the grid is copied to input device and casted to the same typeflow = transform_points(H, grid.to(H.device).type_as(H)) # Nx(...)x2@@ -134,8 +118,9 @@ class HomographyWarper(nn.Module):raise TypeError("Patch and homography must be on the same device. \Got patch.device: {} dst_H_src.device: {}.".format(patch.device, dst_homo_src.device))- return F.grid_sample(patch, self.warp_grid(dst_homo_src), 'bilinear',- padding_mode=padding_mode)+ return torch.nn.functional.grid_sample(patch,+ self.warp_grid(dst_homo_src), mode='bilinear',+ padding_mode=padding_mode)# functional apidiff --git a/torchgeometry/imgwarp.py b/torchgeometry/imgwarp.pyindex 84db4ae3c..0a02394ea 100644--- a/torchgeometry/imgwarp.py+++ b/torchgeometry/imgwarp.py@@ -1,5 +1,6 @@import torch+from .utils import inversefrom .homography_warper import homography_warp@@ -8,6 +9,32 @@ __all__ = []+def center_transform(transform, height, width):+ assert len(transform.shape) == 3, transform.shape+ # move points to origin+ center_mat_origin = torch.unsqueeze(torch.eye(3), dim=0)+ center_mat_origin[..., 0, 2] = float(width) / 2+ center_mat_origin[..., 1, 2] = float(height) / 2+ # move points from origin+ origin_mat_center = torch.unsqueeze(torch.eye(3), dim=0)+ origin_mat_center[..., 0, 2] = -float(width) / 2+ origin_mat_center[..., 1, 2] = -float(height) / 2+ return torch.matmul(center_mat_origin,+ torch.matmul(transform, origin_mat_center))+++def normalize_transform_to_pix(transform, height, width):+ assert len(transform.shape) == 3, transform.shape+ normal_trans_pix = torch.tensor([[+ [2. / (width - 1), 0., -1.],+ [ 0., 2. / (height - 1), -1.],+ [ 0., 0., 1.]]],+ device=transform.device, dtype=transform.dtype) # 1x3x3+ pix_trans_normal = inverse(normal_trans_pix) # 1x3x3+ return torch.matmul(normal_trans_pix,+ torch.matmul(transform, pix_trans_normal))++def warp_perspective(src, M, dsize, flags='bilinear', border_mode=None,border_value=0):"""Applies a perspective transformation to an image.@@ -44,5 +71,9 @@ def warp_perspective(src, M, dsize, flags='bilinear', border_mode=None,if not (len(M.shape) == 3 or M.shape[-2:] == (3, 3)):raise ValueError("Input M must be a Bx3x3 tensor. Got {}".format(src.shape))+ # center the transformation and normalize+ _, _, height, width = src.shape+ M_new = center_transform(M, height, width)+ M_new = normalize_transform_to_pix(M_new, height, width)# warp and return- return homography_warp(src, M, dsize)+ return homography_warp(src, M_new, dsize)diff --git a/torchgeometry/utils.py b/torchgeometry/utils.pyindex 60634ad0e..a33bc28ca 100644--- a/torchgeometry/utils.py+++ b/torchgeometry/utils.py@@ -10,11 +10,41 @@ __all__ = ["image_to_tensor","draw_rectangle","create_pinhole",+ "create_meshgrid","inverse","Inverse",]+def create_meshgrid(height, width, normalized_coordinates=True):+ """Generates a coordinate grid for an image.++ This is normalized to be in the range [-1,1] to be consistent with the+ pytorch function grid_sample.+ http://pytorch.org/docs/master/nn.html#torch.nn.functional.grid_sample++ Args:+ height (int): the image height (rows).+ width (int): the image width (cols).+ normalized_coordinates (bool): wether to used normalized coordinates in+ the range [-1, 1] in order to be consistent with the PyTorch function+ grid_sample.++ Return:+ Tensor: returns a 1xHxWx2 grid.+ """+ # generate coordinates+ if normalized_coordinates:+ xs = torch.linspace(-1, 1, width)+ ys = torch.linspace(-1, 1, height)+ else:+ xs = torch.linspace(0, width - 1, width)+ ys = torch.linspace(0, height - 1, height)+ # generate grid by stacking coordinates+ base_grid = torch.stack(torch.meshgrid([xs, ys])).transpose(1, 2) # 2xHxW+ return torch.unsqueeze(base_grid, dim=0).permute(0, 2, 3, 1) # 1xHxwx2++def inverse(transforms):"""Batched version of `torch.inverse`