π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
import homography_warper
edgarriba79816b239938
diff --git a/test/test_homography_warper.py b/test/test_homography_warper.pynew file mode 100644index 000000000..a8b070082--- /dev/null+++ b/test/test_homography_warper.py@@ -0,0 +1,76 @@+import unittest++import torch+import torchgeometry as dgm+from torch.autograd import gradcheck++import utils # test utils+++class Tester(unittest.TestCase):++ num_tests = 10++ def test_homography_warper(self):+ # generate input data+ batch_size = 1+ height, width = 128, 128+ eye_size = 3 # identity 3x3++ # create checkerboard+ board = utils.create_checkerboard(height, width, 4)+ patch_src = torch.from_numpy(board).view( \+ 1, 1, height, width).expand(batch_size, 1, height, width)++ # create base homography+ dst_homo_src = utils.create_eye_batch(batch_size, eye_size)++ # instantiate warper+ warper = dgm.HomographyWarper(width, height)++ for i in range(self.num_tests):+ # generate homography noise+ homo_delta = torch.zeros_like(dst_homo_src)+ homo_delta[:, -1, -1] = 0.0++ dst_homo_src_i = dst_homo_src + homo_delta++ # transform the points from dst to ref+ patch_dst = warper(patch_src, dst_homo_src_i)+ patch_dst_to_src = warper(patch_dst, dgm.inverse(dst_homo_src_i))++ # projected should be equal as initial+ error = utils.compute_patch_error(+ patch_dst, patch_dst_to_src, height, width)++ threshold = 0.05+ self.assertTrue(error.item() < threshold)++ # TODO: fixme+ @unittest.skip("Test freezes")+ def test_homography_warper_gradcheck(self):+ # generate input data+ batch_size = 1+ height, width = 128, 128+ eye_size = 3 # identity 3x3++ # create checkerboard+ board = utils.create_checkerboard(height, width, 4)+ patch_src = torch.from_numpy(board).view( \+ 1, 1, height, width).expand(batch_size, 1, height, width)+ patch_src = utils.tensor_to_gradcheck_var(patch_src) # to var++ # create base homography+ dst_homo_src = utils.create_eye_batch(batch_size, eye_size)+ dst_homo_src = utils.tensor_to_gradcheck_var(dst_homo_src) # to var++ # instantiate warper+ warper = dgm.HomographyWarper(width, height)++ # evaluate function gradient+ res = gradcheck(warper, (patch_src, dst_homo_src,),+ raise_exception=True)+++if __name__ == '__main__':+ unittest.main()diff --git a/test/utils.py b/test/utils.pyindex 96704ba77..eb9db9e8e 100644--- a/test/utils.py+++ b/test/utils.py@@ -1,9 +1,17 @@import torch+import numpy as np# test utilites+def create_checkerboard(w, h, nw):+ """Creates a synthetic checkerd board of shape HxW and window size `nw`.+ """+ return np.kron([[1, 0] * nw, [0, 1] * nw] * nw,+ np.ones((h // (2 * nw), w // (2 * nw)))).astype(np.float32)++def create_eye_batch(batch_size, eye_size):"""Creates a batch of identity matrices of shape Bx3x3"""@@ -23,8 +31,8 @@ def tensor_to_gradcheck_var(tensor):"""Converts the input tensor to a valid variable to check the gradient.`gradcheck` needs 64-bit floating point and requires gradient."""- tensor = tensor.type(torch.DoubleTensor)- return tensor.requires_grad_(True)+ assert torch.is_tensor(tensor), type(tensor)+ return tensor.requires_grad_(True).type(torch.DoubleTensor)def compute_mse(x, y):diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.pyindex bc1ae19ea..c6c3a6bc7 100644--- a/torchgeometry/__init__.py+++ b/torchgeometry/__init__.py@@ -2,3 +2,4 @@__version__ = '0.0.1' # the current version of the libfrom .functional import *+from .homography_warper import HomographyWarperdiff --git a/torchgeometry/homography_warper.py b/torchgeometry/homography_warper.pynew file mode 100644index 000000000..a8202dff2--- /dev/null+++ b/torchgeometry/homography_warper.py@@ -0,0 +1,105 @@+import torch+import torch.nn as nn+import torch.nn.functional as F+++def generate_grid(width, height):+ '''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.+ '''+ xs = torch.linspace(-1, 1, width)+ ys = torch.linspace(-1, 1, height)+ return torch.stack([+ xs.repeat(height),+ ys.repeat(width, 1).t().contiguous().view(-1),+ torch.ones(width * height)+ ], 1).t()+++class HomographyWarper(nn.Module):+ '''+ Warps patches by homographies.+height, width '''++ def __init__(self, width, height, points=None):+ '''+ :param width: The width of the image to warp.+ :param height: The height of the image to warp.+ :param points: Tensor[3, N] of homogeneous points in normalized image+ space [-1, 1] to sample. Optional parameter.+ '''+ nn.Module.__init__(self)+ if points is not None:+ assert points.size(0) == 3, "Points must be 3xN"+ self.width = points.size(1)+ self.height = 1+ self.grid = points+ else:+ self.width = width+ self.height = height+ # This is a parmeter to support moving to GPU with call to self.cuda()+ self.grid = generate_grid(width, height)++ def warp_grid(self, H):+ """+ :param H: Homography or homographies (stacked) to transform all points in the grid.+ :returns: Tensor[1, Height, Width, 2] containing transformed points in+ normalized images space.+ """+ # TODO(edgarriba): use dgm.transform_points+ grid = self.grid.expand(H.shape[0], *self.grid.shape)+ flow_h = torch.matmul(H, grid.to(H.device).type_as(H))+ flow = flow_h[:, :2] / flow_h[:, -1:] # projective+ flow = flow.view(-1, 2, self.height, self.width) # Nx2xHxW+ return flow.permute(0, 2, 3, 1) # NxHxWx2++ def random_warp(self, patch, dist):+ return self(patch, random_homography(dist))++ def crop_and_warp(self, H, image, roi, padding_mode='zeros'):+ grid = self.warp_grid(H)+ assert len(image.shape) == 4, image.shape++ width, height = image.shape[3], image.shape[2]++ start_x, end_x = roi[2], roi[3] - 1 # inclusive [x_0, x_1]+ start_y, end_y = roi[0], roi[1] - 1++ start_x = (2 * start_x) / width - 1+ end_x = (2 * end_x) / width - 1++ start_y = (2 * start_y) / height - 1+ end_y = (2 * end_y) / height - 1++ b_x = (start_x + end_x) / 2+ a_x = b_x - start_x++ b_y = (start_y + end_y) / 2+ a_y = b_y - start_y+ a = Variable(torch.FloatTensor((a_x, a_y)))+ b = Variable(torch.FloatTensor((b_x, b_y)))+ if grid.is_cuda:+ a = a.cuda()+ b = b.cuda()+ grid = grid * a + b+ return F.grid_sample(+ image, grid, mode='bilinear', padding_mode=padding_mode)++ def forward(self, patch, dst_H_src, padding_mode='zeros'):+ """+ Warps an image from dst into src's reference frame.+ :param patch: Tensor[X,Y,Height,Width] The image to warp. Should be from dst.+ :param dst_H_src: Tensor[3,3] The homography from src to dst.+ :param padding_mode: Either 'zeros' to replace out of bounds with zeros+ or 'border' to choose the closest border data.+ :returns: Tensor[X,Y,Height,Width] patch sampled at locations from src warped to dst.+ """+ assert dst_H_src.device == patch.device, \+ "Patch and homography must be on the same device." \+ " patch.device: {} dst_H_src.device: {}" \+ .format(patch.device, dst_H_src.device)+ return F.grid_sample(patch, self.warp_grid(dst_H_src),+ 'bilinear', padding_mode=padding_mode)