Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

random rotation

dvd425400e50c94e4
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rst
index 9031fe3cd..085c55c79 100644
--- a/docs/source/augmentation.rst
+++ b/docs/source/augmentation.rst
@@ -10,9 +10,11 @@ The functions in this section perform various data augmentation operations
.. autofunction:: color_jitter
.. autofunction:: random_rectangle_erase
.. autofunction:: random_grayscale
+.. autofunction:: random_rotation
.. autoclass:: RandomHorizontalFlip
.. autoclass:: RandomVerticalFlip
.. autoclass:: ColorJitter
.. autoclass:: RandomRectangleErasing
.. autoclass:: RandomGrayscale
+.. autoclass:: RandomRotation
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 436c9d2e1..468e40da9 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -87,6 +87,7 @@ from kornia.augmentation import (
random_vflip,
color_jitter,
random_grayscale,
+ random_rotation,
)
from kornia.geometry import *
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 182628485..1de2fd982 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -12,4 +12,6 @@ __all__ = [
"RandomRectangleErasing",
"random_grayscale",
"RandomGrayscale",
+ "random_rotation",
+ "RandomRotation",
]
diff --git a/kornia/augmentation/augmentations.py b/kornia/augmentation/augmentations.py
index 2de6dc43a..14024d5a8 100644
--- a/kornia/augmentation/augmentations.py
+++ b/kornia/augmentation/augmentations.py
@@ -7,7 +7,8 @@ from torch.distributions import Uniform
from kornia.geometry.transform.flips import hflip, vflip
from kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHue
from kornia.color.gray import rgb_to_grayscale
-from kornia.geometry import pi
+from kornia.geometry import pi, rotate
+from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]
@@ -214,6 +215,59 @@ class RandomGrayscale(nn.Module):
return random_grayscale(input, p=self.p, return_transform=self.return_transform)
+class RandomRotation(nn.Module):
+
+ r"""Rotate a tensor image or a batch of tensor images a random amount of degrees.
+ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
+ the corresponding transformation matrix that has been applied to them. In this case the module
+ will rotate the tensors and concatenate the corresponding transformation matrix to the
+ previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
+
+ Args:
+ degrees (sequence or float or tensor): range of degrees to select from. If degrees is a number the
+ range of degrees to select from will be (-degrees, +degrees)
+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ wont be concatenated
+
+ Examples:
+
+ """
+
+ def __init__(self, degrees: FloatUnionType = 45.0, return_transform: bool = False) -> None:
+ super(RandomRotation, self).__init__()
+ self.degrees = degrees
+ self.return_transform = return_transform
+
+ def __repr__(self) -> str:
+ repr = f"(degrees={self.degrees}, return_transform={self.return_transform})"
+ return self.__class__.__name__ + repr
+
+ def forward(self, input: UnionType) -> UnionType: # type: ignore
+
+ if isinstance(input, tuple):
+
+ inp: torch.Tensor = input[0]
+ prev_trans: torch.Tensor = input[1]
+
+ if self.return_transform:
+
+ out = random_rotation(inp, degrees=self.degrees, return_transform=True)
+ img: torch.Tensor = out[0]
+ trans_mat: torch.Tensor = out[1]
+
+ return img, prev_trans @ trans_mat
+
+ # https://mypy.readthedocs.io/en/latest/casts.html cast the return type to please mypy gods
+ img = cast(torch.Tensor, random_rotation(inp, degrees=self.degrees, return_transform=False))
+
+ # Transform image but pass along the previous transformation
+ return img, prev_trans
+
+ return random_rotation(input, self.degrees, self.return_transform)
+
+
def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False) -> UnionType:
r"""Horizontally flip a tensor image or a batch of tensor images randomly with a given probability.
Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
@@ -461,3 +515,58 @@ def random_grayscale(input: torch.Tensor, p: float = .5, return_transform: bool
return grayscale, identity
return grayscale
+
+
+def random_rotation(input: torch.Tensor, degrees: FloatUnionType, return_transform: bool = False) -> UnionType:
+
+ r""" Randomly rotate the input tensor.
+
+ See :class `~kornia.RandomRotation` for details
+
+ """
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+
+ if not torch.is_tensor(degrees):
+ if isinstance(degrees, float):
+ degrees = torch.tensor([-abs(degrees), abs(degrees)]) # allow negative angles as inputs
+
+ elif isinstance(degrees, (tuple, list)):
+ degrees = torch.tensor(degrees)
+
+ else:
+ raise TypeError(f"Degrees should be a float number a sequence or a tensor. Got {type(degrees)}")
+
+ # https://mypy.readthedocs.io/en/latest/casts.html cast to please mypy gods
+ degrees = cast(torch.Tensor, degrees)
+
+ if degrees.numel() != 2:
+ raise ValueError("If degrees is a sequence it must be of length 2")
+
+ if not isinstance(return_transform, bool):
+ raise TypeError(f"The return_transform flag must be a bool. Got {type(return_transform)}")
+
+ device: torch.device = input.device
+ dtype: torch.dtype = input.dtype
+
+ input = input.unsqueeze(0)
+ input = input.view((-1, (*input.shape[-3:])))
+ degrees = degrees.to(device, dtype)
+
+ angles: torch.Tensor = Uniform(degrees[0], degrees[1]).rsample([input.shape[0]])
+
+ transformed: torch.Tensor = rotate(input, angles).squeeze(0)
+
+ if return_transform:
+
+ center: torch.Tensor = _compute_tensor_center(input)
+ rotation_mat: torch.Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
+
+ # rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix
+ trans_mat: torch.Tensor = torch.eye(3, device=device, dtype=dtype).repeat(input.shape[0], 1, 1)
+ trans_mat[:, 0] = rotation_mat[:, 0]
+ trans_mat[:, 1] = rotation_mat[:, 1]
+
+ return transformed, trans_mat
+
+ return transformed
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index fbafc74d3..665a3c3f6 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -8,7 +8,7 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
from kornia.augmentation import RandomHorizontalFlip, RandomVerticalFlip, ColorJitter, \
- RandomRectangleErasing, RandomGrayscale
+ RandomRectangleErasing, RandomGrayscale, RandomRotation
from kornia.augmentation.random_erasing import get_random_rectangles_params, erase_rectangles
from test.common import device
@@ -1054,3 +1054,156 @@ class TestRandomGrayscale:
assert gradcheck(kornia.random_grayscale, (input, 0.), raise_exception=True)
assert gradcheck(kornia.random_grayscale, (input, 1.), raise_exception=True)
+
+
+class TestRandomRotation:
+
+ torch.manual_seed(0) # for random reproductibility
+
+ def smoke_test(self):
+ f = RandomRotation(degrees=45.5)
+ repr = "RandomHorizontalFlip(degrees=45.5, return_transform=False)"
+ assert str(f) == repr
+
+ def test_random_rotation(self):
+
+ torch.manual_seed(0) # for random reproductibility
+
+ f = RandomRotation(degrees=45.0, return_transform=True)
+ f1 = RandomRotation(degrees=45.0)
+
+ input = torch.tensor([[1., 0., 0., 2.],
+ [0., 0., 0., 0.],
+ [0., 1., 2., 0.],
+ [0., 0., 1., 2.]]) # 4 x 4
+
+ expected = torch.tensor([[[0.9824, 0.0088, 0.0000, 1.9649],
+ [0.0000, 0.0029, 0.0000, 0.0176],
+ [0.0029, 1.0000, 1.9883, 0.0000],
+ [0.0000, 0.0088, 1.0117, 1.9649]]]) # 1 x 4 x 4
+
+ expected_transform = torch.tensor([[[1.0000, -0.0059, 0.0088],
+ [0.0059, 1.0000, -0.0088],
+ [0.0000, 0.0000, 1.0000]]]) # 1 x 3 x 3
+
+ expected_2 = torch.tensor([[0.1322, 0.0000, 0.7570, 0.2644],
+ [0.3785, 0.0000, 0.4166, 0.0000],
+ [0.0000, 0.6309, 1.5910, 1.2371],
+ [0.0000, 0.1444, 0.3177, 0.6499]]) # 1 x 4 x 4
+
+ out, mat = f(input)
+ assert_allclose(out, expected, rtol=1e-6, atol=1e-4)
+ assert_allclose(mat, expected_transform, rtol=1e-6, atol=1e-4)
+ assert_allclose(f1(input), expected_2, rtol=1e-6, atol=1e-4)
+
+ def test_batch_random_rotation(self):
+
+ torch.manual_seed(0) # for random reproductibility
+
+ f = RandomRotation(degrees=45.0, return_transform=True)
+
+ input = torch.tensor([[[[1., 0., 0., 2.],
+ [0., 0., 0., 0.],
+ [0., 1., 2., 0.],
+ [0., 0., 1., 2.]]]]) # 1 x 1 x 4 x 4
+
+ expected = torch.tensor([[[[0.9824, 0.0088, 0.0000, 1.9649],
+ [0.0000, 0.0029, 0.0000, 0.0176],
+ [0.0029, 1.0000, 1.9883, 0.0000],
+ [0.0000, 0.0088, 1.0117, 1.9649]]],
+ [[[0.1322, 0.0000, 0.7570, 0.2644],
+ [0.3785, 0.0000, 0.4166, 0.0000],
+ [0.0000, 0.6309, 1.5910, 1.2371],
+ [0.0000, 0.1444, 0.3177, 0.6499]]]]) # 2 x 1 x 4 x 4
+
+ expected_transform = torch.tensor([[[1.0000, -0.0059, 0.0088],
+ [0.0059, 1.0000, -0.0088],
+ [0.0000, 0.0000, 1.0000]],
+
+ [[0.9125, 0.4090, -0.4823],
+ [-0.4090, 0.9125, 0.7446],
+ [0.0000, 0.0000, 1.0000]]]) # 2 x 3 x 3
+
+ input = input.repeat(2, 1, 1, 1) # 5 x 3 x 3 x 3
+
+ out, mat = f(input)
+ assert_allclose(out, expected, rtol=1e-6, atol=1e-4)
+ assert_allclose(mat, expected_transform, rtol=1e-6, atol=1e-4)
+
+ def test_sequential(self):
+
+ torch.manual_seed(0) # for random reproductibility
+
+ f = nn.Sequential(
+ RandomRotation(torch.tensor([-45.0, 90]), return_transform=True),
+ RandomRotation(-10.4, return_transform=True),
+ )
+ f1 = nn.Sequential(
+ RandomRotation(torch.tensor([-45.0, 90]), return_transform=True),
+ RandomRotation(-10.4),
+ )
+
+ input = torch.tensor([[1., 0., 0., 2.],
+ [0., 0., 0., 0.],
+ [0., 1., 2., 0.],
+ [0., 0., 1., 2.]]) # 4 x 4
+
+ expected = torch.tensor([[[0.1314, 0.1050, 0.6649, 0.2628],
+ [0.3234, 0.0202, 0.4256, 0.1671],
+ [0.0525, 0.5976, 1.5199, 1.1306],
+ [0.0000, 0.1453, 0.3224, 0.5796]]]) # 1 x 4 x 4
+
+ expected_transform = torch.tensor([[[0.8864, 0.4629, -0.5240],
+ [-0.4629, 0.8864, 0.8647],
+ [0.0000, 0.0000, 1.0000]]]) # 1 x 3 x 3
+
+ expected_transform_2 = torch.tensor([[[0.8381, -0.5455, 1.0610],
+ [0.5455, 0.8381, -0.5754],
+ [0.0000, 0.0000, 1.0000]]]) # 1 x 3 x 3
+
+ out, mat = f(input)
+ _, mat_2 = f1(input)
+ assert_allclose(out, expected, rtol=1e-6, atol=1e-4)
+ assert_allclose(mat, expected_transform, rtol=1e-6, atol=1e-4)
+ assert_allclose(mat_2, expected_transform_2, rtol=1e-6, atol=1e-4)
+
+ @pytest.mark.skip(reason="turn off all jit for a while")
+ def test_jit(self):
+
+ torch.manual_seed(0) # for random reproductibility
+
+ @torch.jit.script
+ def op_script(data: torch.Tensor) -> torch.Tensor:
+
+ return kornia.random_rotation(data, degrees=45.0)
+
+ input = torch.tensor([[1., 0., 0., 2.],
+ [0., 0., 0., 0.],
+ [0., 1., 2., 0.],
+ [0., 0., 1., 2.]]) # 4 x 4
+
+ # Build jit trace
+ op_trace = torch.jit.trace(op_script, (input, ))
+
+ # Create new inputs
+ input = torch.tensor([[0., 0., 0.],
+ [5., 5., 0.],
+ [0., 0., 0.]]) # 3 x 3
+
+ expected = torch.tensor([[[0.0000, 0.2584, 0.0000],
+ [2.9552, 5.0000, 0.2584],
+ [1.6841, 0.4373, 0.0000]]])
+
+ actual = op_trace(input)
+
+ assert_allclose(actual, expected, rtol=1e-6, atol=1e-4)
+
+ def test_gradcheck(self):
+
+ torch.manual_seed(0) # for random reproductibility
+
+ input = torch.rand((3, 3)).double() # 3 x 3
+
+ input = utils.tensor_to_gradcheck_var(input) # to var
+
+ assert gradcheck(RandomRotation(degrees=(15.0, 15.0)), (input, ), raise_exception=True)