Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Merge branch 'random_rotation' of git://github.com/dvd42/kornia into dvd42-random_rotation

edgarriba036c7aa9523f
diff --cc docs/source/augmentation.rst
index 9b6ed9caa,91ffaaf5f..6678dba09
--- a/docs/source/augmentation.rst
+++ b/docs/source/augmentation.rst
@@@ -9,10 -9,8 +9,11 @@@ The classes in this section perform var
.. autoclass:: RandomVerticalFlip
.. autoclass:: RandomRectangleErasing
.. autoclass:: RandomGrayscale
+.. autoclass:: RandomAffine
+.. autoclass:: RandomPerspective
+ .. autoclass:: RandomRotation
.. autoclass:: ColorJitter
+.. autoclass:: CenterCrop
.. automodule:: kornia.augmentation.functional
:members:
diff --cc kornia/augmentation/augmentation.py
index 22bb5e42a,d444b2f9a..331a828a5
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@@ -347,31 -345,52 +347,82 @@@ class RandomAffine(AugmentationBase)
return super().forward(input, params)
+class CenterCrop(AugmentationBase):
+ r"""Crops the given torch.Tensor at the center.
+ Args:
+ size (sequence or int): Desired output size of the crop. If size is an
+ int instead of sequence like (h, w), a square crop (size, size) is
+ made.
+ """
+
+ def __init__(self, size: Union[int, Tuple[int, int]], return_transform: bool = False) -> None:
+ super(CenterCrop, self).__init__(F.apply_center_crop, return_transform)
+ self.size = size
+ self.return_transform = return_transform
+
+ @staticmethod
+ def get_params(size: Union[int, Tuple[int, int]]) -> Dict[str, torch.Tensor]:
+ if isinstance(size, tuple):
+ size_param = torch.tensor([size[0], size[1]])
+ elif isinstance(size, int):
+ size_param = torch.tensor([size, size])
+ else:
+ raise Exception(f"Invalid size type. Expected (int, tuple(int, int). "
+ f"Got: {type(size)}.")
+ return dict(size=size_param)
+
+ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore
+ if params is None:
+ params = self.get_params(self.size)
+ return super().forward(input, params)
++
++
+ class RandomRotation(AugmentationBase):
+
+ 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:
+ >>> input = torch.tensor([[[[10., 0., 0.],
+ [0., 4.5, 4.],
+ [0., 1., 1.]]]])
+ >>> seq = nn.Sequential(kornia.augmentation.RandomRotation(degrees=90.0, return_transform=True))
+ >>> seq(input)
+ (tensor([[[0.0000e+00, 8.8409e-02, 9.8243e+00],
+ [9.9131e-01, 4.5000e+00, 1.7524e-04],
+ [9.9121e-01, 3.9735e+00, 3.5140e-02]]]),
+ tensor([[[ 0.0088, -1.0000, 1.9911],
+ [ 1.0000, 0.0088, -0.0088],
+ [ 0.0000, 0.0000, 1.0000]]]))
+ """
+
+ def __init__(self, degrees: FloatUnionType = 45.0, return_transform: bool = False) -> None:
+ super(RandomRotation, self).__init__(F.apply_rotation, return_transform)
+ self.degrees = degrees
+
+ def __repr__(self) -> str:
+ repr = f"(degrees={self.degrees}, return_transform={self.return_transform})"
+ return self.__class__.__name__ + repr
+
+ @staticmethod
+ def get_params(batch_size: int, degrees: FloatUnionType) -> Dict[str, torch.Tensor]:
+ return pg._random_rotation_gen(batch_size, degrees)
+
+ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore
+
+ if params is None:
+ height, width = self.infer_image_shape(input)
+ batch_size: int = self.infer_batch_size(input)
+ params = self.get_params(batch_size, self.degrees)
+ return super().forward(input, params)
diff --cc kornia/augmentation/functional.py
index 42eb63dbe,a14d64e7f..bf1ed045b
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@@ -4,9 -4,10 +4,11 @@@ import torc
import torch.nn as nn
from kornia.geometry.transform.flips import hflip, vflip
- from kornia.geometry.transform import get_perspective_transform, warp_perspective, center_crop
++from kornia.geometry.transform import get_perspective_transform, warp_perspective, center_crop, rotate
+ from kornia.geometry.transform import get_perspective_transform, warp_perspective, rotate
from kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHue
from kornia.color.gray import rgb_to_grayscale
+ from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
from . import param_gen as pg
from .erasing import erase_rectangles, get_random_rectangles_params
@@@ -467,12 -484,40 +485,51 @@@ def apply_affine(input: torch.Tensor
return out_data.view_as(input)
+def apply_center_crop(input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ return_transform: bool = False) -> UnionType:
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+
+ size1: int = int(params['size'][0].item())
+ size2: int = int(params['size'][1].item())
+ return center_crop(input, (size1, size2), return_transform)
++
++
+ def apply_rotation(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False):
+ 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)`.
+
+ Args:
+ params (dict): A dict that must have {'degrees': torch.Tensor}. Can be generated from
+ kornia.augmentation.param_gen._random_rotation_gen
+ 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
+ """
+
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+
+ device: torch.device = input.device
+ dtype: torch.dtype = input.dtype
+
+ input = input.unsqueeze(0)
+ input = input.view((-1, (*input.shape[-3:])))
+ angles: torch.Tensor = params["degrees"].to(device, dtype)
+
+ 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 --cc test/augmentation/test_augmentation.py
index aa48a16b7,72776a458..d8f5e9f9d
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@@ -1056,26 -1056,154 +1056,178 @@@ class TestRandomGrayscale
assert gradcheck(kornia.random_grayscale, (input, 1.), raise_exception=True)
+class TestCenterCrop:
+
+ def test_no_transform(self, device):
+ inp = torch.rand(1, 2, 4, 4).to(device)
+ out = kornia.augmentation.CenterCrop(2)(inp)
+ assert out.shape == (1, 2, 2, 2)
+
+ def test_transform(self, device):
+ inp = torch.rand(1, 2, 5, 4).to(device)
+ out = kornia.augmentation.CenterCrop(2, return_transform=True)(inp)
+ assert len(out) == 2
+ assert out[0].shape == (1, 2, 2, 2)
+ assert out[1].shape == (1, 3, 3)
+
+ def test_no_transform_tuple(self, device):
+ inp = torch.rand(1, 2, 5, 4).to(device)
+ out = kornia.augmentation.CenterCrop((3, 4))(inp)
+ assert out.shape == (1, 2, 3, 4)
+
+ def test_gradcheck(self, device):
+ input = torch.rand(1, 2, 3, 4).to(device)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(kornia.augmentation.CenterCrop(3), (input,), raise_exception=True)
++
+ class TestRandomRotation:
+
+ torch.manual_seed(0) # for random reproductibility
+
+ def smoke_test(self, device):
+ f = RandomRotation(degrees=45.5)
+ repr = "RandomHorizontalFlip(degrees=45.5, return_transform=False)"
+ assert str(f) == repr
+
+ def test_random_rotation(self, device):
+
+ 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, device):
+
+ 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, device):
+
+ 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, device):
+
+ 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, device):
+
+ torch.manual_seed(0) # for random reproductibility
+
+ input = torch.rand((3, 3)) # 3 x 3
+
+ input = utils.tensor_to_gradcheck_var(input) # to var
+
+ assert gradcheck(RandomRotation(degrees=(15.0, 15.0)), (input, ), raise_exception=True)