Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] Add Affine transformation (#630)

Philip Meier9c2aa92e471a
diff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rst
index 9f4ae10bc..0c05265ad 100644
--- a/docs/source/geometry.transform.rst
+++ b/docs/source/geometry.transform.rst
@@ -45,3 +45,4 @@ The functions in this section perform various geometrical transformations of 2D
.. autoclass:: Vflip
.. autoclass:: Rot180
.. autoclass:: Resize
+.. autoclass:: Affine
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index df575e4d3..ac3351591 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -1,10 +1,10 @@
-from typing import Union, Tuple
+from typing import Union, Tuple, Optional
import torch
import torch.nn as nn
from kornia.geometry.transform.imgwarp import (
- warp_affine, get_rotation_matrix2d
+ warp_affine, get_rotation_matrix2d, get_affine_matrix2d
)
from kornia.geometry.transform.projwarp import (
warp_projective, get_projective_transform
@@ -23,6 +23,7 @@ __all__ = [
"Translate",
"Shear",
"Resize",
+ "Affine",
]
# utilities to compute affine matrices
@@ -406,6 +407,87 @@ class Resize(nn.Module):
return resize(input, self.size, self.interpolation, align_corners=self.align_corners, side=self.side)
+class Affine(nn.Module):
+ r"""Apply multiple elementary affine transforms simultaneously.
+
+ Args:
+ angle (torch.Tensor, optional): Angle in degrees for counter-clockwise rotation around the center. The tensor
+ must have a shape of (B), where B is the batch size.
+ translation (torch.Tensor, optional): Amount of pixels for translation in x- and y-direction. The tensor must
+ have a shape of (B, 2), where B is the batch size and the last dimension contains dx and dy.
+ scale_factor (torch.Tensor, optional): Factor for scaling. The tensor must have a shape of (B), where B is the
+ batch size.
+ shear (torch.Tensor, optional): Angles in degrees for shearing in x- and y-direction around the center. The
+ tensor must have a shape of (B, 2), where B is the batch size and the last dimension contains sx and sy.
+ center (torch.Tensor, optional): Transformation center in pixels. The tensor must have a shape of (B, 2), where
+ B is the batch size and the last dimension contains cx and cy. Defaults to the center of image to be
+ transformed.
+ align_corners (bool): interpolation flag. Default: False. See :func:`~torch.nn.functional.interpolate` for
+ details.
+
+ Raises:
+ RuntimeError: If not one of ``angle``, ``translation``, ``scale_factor``, or ``shear`` is set.
+
+ Returns:
+ torch.Tensor: The transformed tensor.
+ """
+
+ def __init__(
+ self,
+ angle: Optional[torch.Tensor] = None,
+ translation: Optional[torch.Tensor] = None,
+ scale_factor: Optional[torch.Tensor] = None,
+ shear: Optional[torch.Tensor] = None,
+ center: Optional[torch.Tensor] = None,
+ align_corners: bool = False,
+ ) -> None:
+ batch_sizes = [arg.size()[0] for arg in (angle, translation, scale_factor, shear) if arg is not None]
+ if not batch_sizes:
+ msg = (
+ "Affine was created without any affine parameter. At least one of angle, translation, scale_factor, or "
+ "shear has to be set."
+ )
+ raise RuntimeError(msg)
+
+ batch_size = batch_sizes[0]
+ if not all(other == batch_size for other in batch_sizes[1:]):
+ raise RuntimeError(f"The batch sizes of the affine parameters mismatch: {batch_sizes}")
+
+ self._batch_size = batch_size
+
+ super().__init__()
+
+ if angle is None:
+ angle = torch.zeros(batch_size)
+ self.angle = angle
+
+ if translation is None:
+ translation = torch.zeros(batch_size, 2)
+ self.translation = translation
+
+ if scale_factor is None:
+ scale_factor = torch.ones(batch_size)
+ self.scale_factor = scale_factor
+
+ self.shear = shear
+ self.center = center
+ self.align_corners = align_corners
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ if self.shear is None:
+ sx = sy = None
+ else:
+ sx, sy = self.shear[..., 0], self.shear[..., 1]
+
+ if self.center is None:
+ center = _compute_tensor_center(input).expand(input.size()[0], -1)
+ else:
+ center = self.center
+
+ matrix = get_affine_matrix2d(self.translation, center, self.scale_factor, -self.angle, sx=sx, sy=sy)
+ return affine(input, matrix[..., :2, :3], align_corners=self.align_corners)
+
+
class Rotate(nn.Module):
r"""Rotate the tensor anti-clockwise about the centre.
diff --git a/test/geometry/transform/test_affine.py b/test/geometry/transform/test_affine.py
index 16b0747c5..a1b43b1e8 100644
--- a/test/geometry/transform/test_affine.py
+++ b/test/geometry/transform/test_affine.py
@@ -432,6 +432,77 @@ class TestShear:
class TestAffine2d:
+ def test_affine_no_args(self):
+ with pytest.raises(RuntimeError):
+ kornia.Affine()
+
+ def test_affine_batch_size_mismatch(self, device):
+ with pytest.raises(RuntimeError):
+ angle = torch.rand(1, device=device)
+ translation = torch.rand(2, 2, device=device)
+ kornia.Affine(angle, translation)
+
+ def test_affine_rotate(self, device):
+ torch.manual_seed(0)
+ angle = torch.rand(1, device=device) * 90.0
+ input = torch.rand(1, 2, 3, 4, device=device)
+
+ transform = kornia.Affine(angle=angle).to(device)
+ actual = transform(input)
+ expected = kornia.rotate(input, angle)
+ assert_allclose(actual, expected)
+
+ def test_affine_translate(self, device):
+ torch.manual_seed(0)
+ translation = torch.rand(1, 2, device=device) * 2.0
+ input = torch.rand(1, 2, 3, 4, device=device)
+
+ transform = kornia.Affine(translation=translation).to(device)
+ actual = transform(input)
+ expected = kornia.translate(input, translation)
+ assert_allclose(actual, expected)
+
+ def test_affine_scale(self, device):
+ torch.manual_seed(0)
+ scale_factor = torch.rand(1, device=device) * 2.0
+ input = torch.rand(1, 2, 3, 4, device=device)
+
+ transform = kornia.Affine(scale_factor=scale_factor).to(device)
+ actual = transform(input)
+ expected = kornia.scale(input, scale_factor)
+ assert_allclose(actual, expected)
+
+ @pytest.mark.skip(
+ "_compute_shear_matrix and get_affine_matrix2d yield different results. "
+ "See https://github.com/kornia/kornia/issues/629 for details."
+ )
+ def test_affine_shear(self, device):
+ torch.manual_seed(0)
+ shear = torch.rand(1, 2, device=device)
+ input = torch.rand(1, 2, 3, 4, device=device)
+
+ transform = kornia.Affine(shear=shear).to(device)
+ actual = transform(input)
+ expected = kornia.shear(input, shear)
+ assert_allclose(actual, expected)
+
+ def test_affine_rotate_translate(self, device):
+ batch_size = 2
+
+ input = torch.tensor(
+ [[[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]], device=device
+ ).repeat(batch_size, 1, 1, 1)
+
+ angle = torch.tensor(180.0, device=device).repeat(batch_size)
+ translation = torch.tensor([1.0, 0.0]).repeat(batch_size, 1)
+
+ expected = torch.tensor(
+ [[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 0.0]]], device=device,
+ ).repeat(batch_size, 1, 1, 1)
+
+ transform = kornia.Affine(angle=angle, translation=translation, align_corners=True).to(device)
+ actual = transform(input)
+ assert_allclose(actual, expected)
def test_compose_affine_matrix_3x3(self, device):
""" To get parameters: