Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement shear

edgarriba0a3a0d1a7a7f
diff --git a/test/test_affine.py b/test/test_affine.py
index 72d6fa8c7..7518252a6 100644
--- a/test/test_affine.py
+++ b/test/test_affine.py
@@ -284,3 +284,111 @@ class TestScale:
trans_traced = torch.jit.trace(tgm.Scale(scale_factor), img)
assert_allclose(trans(img), trans_traced(img))
+
+class TestShear:
+ def test_shear_x(self):
+ # prepare input data
+ inp = torch.tensor([[
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.]
+ ]])
+ expected = torch.tensor([[
+ [1., 1., 1., 1.],
+ [.5, 1., 1., 1.],
+ [0., 1., 1., 1.],
+ [0., .5, 1., 1.]
+ ]])
+
+ # prepare transformation
+ shear = torch.tensor([[0.5, 0.0]])
+ transform = tgm.Shear(shear)
+ assert_allclose(transform(inp), expected)
+
+ def test_shear_y(self):
+ # prepare input data
+ inp = torch.tensor([[
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.]
+ ]])
+ expected = torch.tensor([[
+ [1., .5, 0., 0.],
+ [1., 1., 1., .5],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.]
+ ]])
+
+ # prepare transformation
+ shear = torch.tensor([[0.0, 0.5]])
+ transform = tgm.Shear(shear)
+ assert_allclose(transform(inp), expected)
+
+ def test_shear_batch2(self):
+ # prepare input data
+ inp = torch.tensor([[
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.]
+ ]]).repeat(2, 1, 1, 1)
+
+ expected = torch.tensor([[[
+ [1., 1., 1., 1.],
+ [.5, 1., 1., 1.],
+ [0., 1., 1., 1.],
+ [0., .5, 1., 1.]
+ ]],[[
+ [1., .5, 0., 0.],
+ [1., 1., 1., .5],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.]
+ ]]])
+
+ # prepare transformation
+ shear = torch.tensor([[0.5, 0.0], [0.0, 0.5]])
+ transform = tgm.Shear(shear)
+ assert_allclose(transform(inp), expected)
+
+ def test_shear_batch2_broadcast(self):
+ # prepare input data
+ inp = torch.tensor([[
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.]
+ ]]).repeat(2, 1, 1, 1)
+
+ expected = torch.tensor([[[
+ [1., 1., 1., 1.],
+ [.5, 1., 1., 1.],
+ [0., 1., 1., 1.],
+ [0., .5, 1., 1.]
+ ]]])
+
+ # prepare transformation
+ shear = torch.tensor([[0.5, 0.0]])
+ transform = tgm.Shear(shear)
+ assert_allclose(transform(inp), expected)
+
+ def test_gradcheck(self):
+ # test parameters
+ shear = torch.tensor([[0.5, 0.0]])
+ shear = utils.tensor_to_gradcheck_var(
+ shear, requires_grad=False) # to var
+
+ # evaluate function gradient
+ input = torch.rand(1, 2, 3, 4)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(tgm.shear, (input, shear,), raise_exception=True)
+
+ @pytest.mark.skip('Need deep look into it since crashes everywhere.')
+ def test_jit(self):
+ shear = torch.tensor([[0.5, 0.0]])
+ batch_size, channels, height, width = 2, 3, 64, 64
+ img = torch.ones(batch_size, channels, height, width)
+ trans = tgm.Shear(shear)
+ trans_traced = torch.jit.trace(tgm.Shear(shear), img)
+ assert_allclose(trans(img), trans_traced(img))
diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.py
index 173fe0b28..fffb9f83c 100644
--- a/torchgeometry/__init__.py
+++ b/torchgeometry/__init__.py
@@ -20,4 +20,6 @@ from .core.pinhole import *
from .core.conversions import *
from .core.imgwarp import *
from .core.transformations import *
-from .core.affine import affine, rotate, translate, scale, Rotate, Translate, Scale
+from .core.affine import (
+ affine, rotate, translate, scale, shear, Rotate, Translate, Scale, Shear
+)
diff --git a/torchgeometry/core/__init__.py b/torchgeometry/core/__init__.py
index 1b87826ce..910b95f62 100644
--- a/torchgeometry/core/__init__.py
+++ b/torchgeometry/core/__init__.py
@@ -4,4 +4,6 @@ from .pinhole import *
from .conversions import *
from .imgwarp import *
from .transformations import *
-from .affine import rotate, translate, scale, Rotate, Translate, Scale
+from .affine import (
+ affine, rotate, translate, scale, shear, Rotate, Translate, Scale, Shear
+)
diff --git a/torchgeometry/core/affine.py b/torchgeometry/core/affine.py
index 971171af0..e8d62ccaf 100644
--- a/torchgeometry/core/affine.py
+++ b/torchgeometry/core/affine.py
@@ -45,6 +45,17 @@ def _compute_scaling_matrix(scale: torch.Tensor, center: torch.Tensor) -> torch.
return matrix
+def _compute_shear_matrix(shear: torch.Tensor) -> torch.Tensor:
+ """Computes affine matrix for shearing."""
+ matrix: torch.Tensor = torch.eye(3, device=shear.device, dtype=shear.dtype)
+ matrix = matrix.repeat(shear.shape[0], 1, 1)
+
+ shx, shy = torch.chunk(shear, chunks=2, dim=-1)
+ matrix[..., 0, 1:2] += shx
+ matrix[..., 1, 0:1] += shy
+ return matrix
+
+
# based on:
# https://github.com/anibali/tvl/blob/master/src/tvl/transforms.py#L166
@@ -181,6 +192,34 @@ def scale(tensor: torch.Tensor, scale_factor: torch.Tensor,
return affine(tensor, scaling_matrix[..., :2, :3])
+def shear(tensor: torch.Tensor, shear: torch.Tensor) -> torch.Tensor:
+ r"""Shear the tensor.
+
+ Args:
+ tensor (torch.Tensor): The image tensor to be translated.
+ shear (torch.Tensor): tensor containing the angle to shear
+ in the x and y direction. The tensor must have a shape of
+ :math:(B, 2), where B is batch size, last dimension contains shx shy.
+ Returns:
+ torch.Tensor: The skewed tensor.
+ """
+ if not torch.is_tensor(tensor):
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
+ .format(type(tensor)))
+ if not torch.is_tensor(shear):
+ raise TypeError("Input shear type is not a torch.Tensor. Got {}"
+ .format(type(shear)))
+ if len(tensor.shape) not in (3, 4,):
+ raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. "
+ "Got: {}".format(tensor.shape))
+
+ # compute the translation matrix
+ shear_matrix: torch.Tensor = _compute_shear_matrix(shear)
+
+ # warp using the affine transform
+ return affine(tensor, shear_matrix[..., :2, :3])
+
+
class Rotate(nn.Module):
r"""Rotate the tensor anti-clockwise about the centre.
@@ -252,3 +291,26 @@ class Scale(nn.Module):
return self.__class__.__name__ + '(' \
'scale_factor={0}, center={1})' \
.format(self.scale_factor, self.center)
+
+
+class Shear(nn.Module):
+ r"""Shear the tensor.
+
+ Args:
+ tensor (torch.Tensor): The image tensor to be translated.
+ shear (torch.Tensor): tensor containing the angle to shear
+ in the x and y direction. The tensor must have a shape of
+ :math:(B, 2), where B is batch size, last dimension contains shx shy.
+ Returns:
+ torch.Tensor: The skewed tensor.
+ """
+ def __init__(self, shear: torch.Tensor) -> None:
+ super(Shear, self).__init__()
+ self.shear: torch.Tensor = shear
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ return shear(input, self.shear)
+
+ def __repr__(self):
+ return self.__class__.__name__ + '(' \
+ 'shear={0})'.format(self.shear)