Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Merge branch 'master' into feat/get_perspective_transform

Edgar Riba006d96766fd3
diff --cc docs/source/index.rst
index da2d442e5,bea9b5b0f..38567faa9
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@@ -26,7 -26,7 +26,8 @@@ Geometric Image Transformation
The functions in this section perform various geometrical transformations of 2D images.
.. autofunction:: warp_perspective
+.. autofunction:: get_perspective_transform
+ .. autofunction:: get_rotation_matrix2d
Pinhole
diff --cc test/test_imgwarp.py
index 39d22bd82,90f01ef18..c11bb9502
--- a/test/test_imgwarp.py
+++ b/test/test_imgwarp.py
@@@ -64,36 -64,62 +64,94 @@@ class Tester(unittest.TestCase)
raise_exception=True)
self.assertTrue(res)
+ def test_rotation_matrix2d(self):
+ # generate input data
+ batch_size = 1
+ center_base = torch.zeros(batch_size, 2)
+ angle_base = torch.ones(batch_size, 1)
+ scale_base = torch.ones(batch_size, 1)
+
+ # 90 deg rotation
+ center = center_base
+ angle = 90. * angle_base
+ scale = scale_base
+ M = tgm.get_rotation_matrix2d(center, angle, scale)
+
+ self.assertAlmostEqual(M[0, 0, 0].item(), 0.0)
+ self.assertAlmostEqual(M[0, 0, 1].item(), 1.0)
+ self.assertAlmostEqual(M[0, 1, 0].item(), -1.0)
+ self.assertAlmostEqual(M[0, 1, 1].item(), 0.0)
+
+ # 90 deg rotation + 2x scale
+ center = center_base
+ angle = 90. * angle_base
+ scale = 2. * scale_base
+ M = tgm.get_rotation_matrix2d(center, angle, scale)
+
+ self.assertAlmostEqual(M[0, 0, 0].item(), 0.0, 4)
+ self.assertAlmostEqual(M[0, 0, 1].item(), 2.0, 4)
+ self.assertAlmostEqual(M[0, 1, 0].item(), -2.0, 4)
+ self.assertAlmostEqual(M[0, 1, 1].item(), 0.0, 4)
+
+ # 45 deg rotation
+ center = center_base
+ angle = 45. * angle_base
+ scale = scale_base
+ M = tgm.get_rotation_matrix2d(center, angle, scale)
+
+ self.assertAlmostEqual(M[0, 0, 0].item(), 0.7071, 4)
+ self.assertAlmostEqual(M[0, 0, 1].item(), 0.7071, 4)
+ self.assertAlmostEqual(M[0, 1, 0].item(), -0.7071, 4)
+ self.assertAlmostEqual(M[0, 1, 1].item(), 0.7071, 4)
+
+ def test_get_rotation_matrix2d_gradcheck(self):
+ # generate input data
+ batch_size = 1
+ center = torch.zeros(batch_size, 2)
+ angle = torch.ones(batch_size, 1)
+ scale = torch.ones(batch_size, 1)
+
+ center = utils.tensor_to_gradcheck_var(center) # to var
+ angle = utils.tensor_to_gradcheck_var(angle) # to var
+ scale = utils.tensor_to_gradcheck_var(scale) # to var
+
+ # evaluate function gradient
+ res = gradcheck(tgm.get_rotation_matrix2d, (center, angle, scale),
+ raise_exception=True)
+ self.assertTrue(res)
+
+ def test_get_perspective_transform(self):
+ # generate input data
+ h, w = 64, 32 # height, width
+ norm = torch.randn(1, 4, 2)
+ points_src = torch.FloatTensor([[
+ [0, 0], [h, 0], [0, w], [h, w],
+ ]])
+ points_dst = points_src + norm
+
+ # compute transform from source to target
+ dst_homo_src = tgm.get_perspective_transform(points_src, points_dst)
+
+ res = utils.check_equal_torch(
+ tgm.transform_points(dst_homo_src, points_src), points_dst)
+ self.assertTrue(res)
+
+ def test_get_perspective_transform_gradcheck(self):
+ # generate input data
+ h, w = 64, 32 # height, width
+ norm = torch.randn(1, 4, 2)
+ points_src = torch.FloatTensor([[
+ [0, 0], [h, 0], [0, w], [h, w],
+ ]])
+ points_dst = points_src + norm
+ points_src = utils.tensor_to_gradcheck_var(points_src) # to var
+ points_dst = utils.tensor_to_gradcheck_var(points_dst) # to var
+
+ # compute transform from source to target
+ res = gradcheck(tgm.get_perspective_transform,
+ (points_src, points_dst,), raise_exception=True)
+ self.assertTrue(res)
++
+
if __name__ == '__main__':
unittest.main()
diff --cc torchgeometry/imgwarp.py
index 8af4feec2,abba50ee8..a4188558d
--- a/torchgeometry/imgwarp.py
+++ b/torchgeometry/imgwarp.py
@@@ -6,7 -7,7 +7,8 @@@ from .conversions import deg2ra
__all__ = [
"warp_perspective",
+ "get_perspective_transform",
+ "get_rotation_matrix2d",
]
@@@ -95,86 -96,86 +97,170 @@@ def warp_perspective(src, M, dsize, fla
return homography_warp(src, M_new, dsize)
+def get_perspective_transform(src, dst):
+ """Calculates a perspective transform from four pairs of the corresponding
+ points.
+
+ The function calculates the matrix of a perspective transform so that:
+
+ .. math ::
+
+ todo
+
+ Args:
+ src (Tensor): coordinates of quadrangle vertices in the source image.
+ dst (Tensor): coordinates of the corresponding quadrangle vertices in
+ the destination image.
+
+ Returns:
+ Tensor: the perspective transformation.
+
+ Shape:
+ - Input: :math:`(B, 4, 2)` and :math:`(B, 4, 2)`
+ - Output: :math:`(B, 3, 3)`
+ """
+ if not torch.is_tensor(src):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(src)))
+ if not torch.is_tensor(dst):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(dst)))
+ if not src.shape[-2:] == (4, 2):
+ raise ValueError("Inputs must be a Bx4x2 tensor. Got {}"
+ .format(src.shape))
+ if not src.shape == dst.shape:
+ raise ValueError("Inputs must have the same shape. Got {}"
+ .format(dst.shape))
+ def ax(p, q):
+ ones = torch.ones_like(p)[..., 0:1]
+ zeros = torch.zeros_like(p)[..., 0:1]
+ return torch.cat(
+ [ p[:, 0:1], p[:, 1:2], ones, zeros, zeros, zeros,
+ -p[:, 0:1] * q[:, 0:1], -p[:, 1:2] * q[:, 0:1] ], dim=1)
+
+ def ay(p, q):
+ ones = torch.ones_like(p)[..., 0:1]
+ zeros = torch.zeros_like(p)[..., 0:1]
+ return torch.cat(
+ [ zeros, zeros, zeros, p[:, 0:1], p[:, 1:2], ones,
+ -p[:, 0:1] * q[:, 1:2], -p[:, 1:2] * q[:, 1:2] ], dim=1)
+ # we build matrix A by using only 4 point correspondence. The linear
+ # system is solved with the least square method, so here
+ # we could even pass more correspondence
+ p = []
+ p.append(ax(src[:, 0], dst[:, 0]))
+ p.append(ay(src[:, 0], dst[:, 0]))
+
+ p.append(ax(src[:, 1], dst[:, 1]))
+ p.append(ay(src[:, 1], dst[:, 1]))
+
+ p.append(ax(src[:, 2], dst[:, 2]))
+ p.append(ay(src[:, 2], dst[:, 2]))
+
+ p.append(ax(src[:, 3], dst[:, 3]))
+ p.append(ay(src[:, 3], dst[:, 3]))
+
+ # A is Bx8x8
+ A = torch.stack(p, dim=1)
+
+ # b is a Bx8x1
+ b = torch.stack([
+ dst[:, 0:1, 0], dst[:, 0:1, 1],
+ dst[:, 1:2, 0], dst[:, 1:2, 1],
+ dst[:, 2:3, 0], dst[:, 2:3, 1],
+ dst[:, 3:4, 0], dst[:, 3:4, 1],
+ ], dim=1)
+
+ # solve the system Ax = b
+ X, LU = torch.gesv(b, A)
+
+ # create variable to return
+ batch_size = src.shape[0]
+ M = torch.ones(batch_size, 9, device=src.device, dtype=src.dtype)
+ M[..., :8] = torch.squeeze(X, dim=-1)
+ return M.view(-1, 3, 3) # Bx3x3
+
++
+ def get_rotation_matrix2d(center, angle, scale):
+ r"""Calculates an affine matrix of 2D rotation.
+
+ The function calculates the following matrix:
+
+ .. math::
+ \begin{bmatrix}
+ \alpha & \beta & (1 - \alpha) \cdot \text{x}
+ - \beta \cdot \text{y} \\
+ -\beta & \alpha & \beta \cdot \text{x}
+ + (1 - \alpha) \cdot \text{y}
+ \end{bmatrix}
+
+ where
+
+ .. math::
+ \alpha = \text{scale} \cdot cos(\text{angle}) \\
+ \beta = \text{scale} \cdot sin(\text{angle})
+
+ The transformation maps the rotation center to itself
+ If this is not the target, adjust the shift.
+
+ Args:
+ center (Tensor): center of the rotation in the source image.
+ angle (Tensor): rotation angle in degrees. Positive values mean
+ counter-clockwise rotation (the coordinate origin is assumed to
+ be the top-left corner).
+ scale (Tensor): isotropic scale factor.
+
+ Returns:
+ Tensor: the affine matrix of 2D rotation.
+
+ Shape:
+ - Input: :math:`(B, 2)`, :math:`(B, 1)` and :math:`(B, 1)`
+ - Output: :math:`(B, 2, 3)`
+
+ Example:
+ >>> center = torch.zeros(1, 2)
+ >>> scale = torch.ones(1, 1)
+ >>> angle = 45. * torch.ones(1, 1)
+ >>> M = tgm.get_rotation_matrix2d(center, angle, scale)
+ tensor([[[ 0.7071, 0.7071, 0.0000],
+ [-0.7071, 0.7071, 0.0000]]])
+ """
+ if not torch.is_tensor(center):
+ raise TypeError("Input center type is not a torch.Tensor. Got {}"
+ .format(type(center)))
+ if not torch.is_tensor(angle):
+ raise TypeError("Input angle type is not a torch.Tensor. Got {}"
+ .format(type(angle)))
+ if not torch.is_tensor(scale):
+ raise TypeError("Input scale type is not a torch.Tensor. Got {}"
+ .format(type(scale)))
+ if not (len(center.shape) == 2 and center.shape[1] == 2):
+ raise ValueError("Input center must be a Bx2 tensor. Got {}"
+ .format(center.shape))
+ if not (len(angle.shape) == 2 and angle.shape[1] == 1):
+ raise ValueError("Input angle must be a Bx1 tensor. Got {}"
+ .format(angle.shape))
+ if not (len(scale.shape) == 2 and scale.shape[1] == 1):
+ raise ValueError("Input scale must be a Bx1 tensor. Got {}"
+ .format(scale.shape))
+ if not (center.shape[0] == angle.shape[0] == scale.shape[0]):
+ raise ValueError("Inputs must have same batch size dimension. Got {}"
+ .format(center.shape, angle.shape, scale.shape))
+ # convert angle and apply scale
+ angle_rad = deg2rad(angle)
+ alpha = torch.cos(angle_rad) * scale
+ beta = torch.sin(angle_rad) * scale
+
+ # unpack the center to x, y coordinates
+ x, y = torch.chunk(center, chunks=2, dim=1)
+
+ # create output tensor
+ batch_size, _ = center.shape
+ M = torch.zeros(batch_size, 2, 3, device=center.device, dtype=center.dtype)
+ M[..., 0, 0] = alpha
+ M[..., 0, 1] = beta
+ M[..., 0, 2] = (1. - alpha) * x - beta * y
+ M[..., 1, 0] = -beta
+ M[..., 1, 1] = alpha
+ M[..., 1, 2] = beta * x + (1. - alpha) * y
+ return M