π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
random rotation
dvd42b20ba27d067f
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex 491e62546..d444b2f9a 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -345,7 +345,7 @@ class RandomAffine(AugmentationBase):return super().forward(input, params)-class RandomRotation(nn.Module):+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)`.@@ -394,57 +394,3 @@ class RandomRotation(nn.Module):batch_size: int = self.infer_batch_size(input)params = self.get_params(batch_size, self.degrees)return super().forward(input, params)-- 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 transformeddiff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.pyindex 1946aa3c5..a14d64e7f 100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@ -4,10 +4,10 @@ import torchimport torch.nn as nnfrom kornia.geometry.transform.flips import hflip, vflip-from kornia.geometry.transform import get_perspective_transform, warp_perspective+from kornia.geometry.transform import get_perspective_transform, warp_perspective, rotatefrom kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHuefrom kornia.color.gray import rgb_to_grayscale-from kornia.geometry.transform import _compute_rotation_matrix, _compute_tensor_center+from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_centerfrom . import param_gen as pgfrom .erasing import erase_rectangles, get_random_rectangles_params@@ -467,7 +467,6 @@ def apply_affine(input: torch.Tensor,if not torch.is_tensor(input):raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")-device: torch.device = input.devicedtype: torch.dtype = input.dtype@@ -490,43 +489,22 @@ def apply_rotation(input: torch.Tensor, params: Dict[str, torch.Tensor], return_Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.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)+ params (dict): A dict that must have {'degrees': torch.Tensor}. Can be generated from+ kornia.augmentation.param_gen._random_rotation_genreturn_transform (bool): if ``True`` return the matrix describing the transformation applied to eachinput tensor. If ``False`` and the input is a tuple the applied transformationwont be concatenated"""- degrees = params["degrees"]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):- if degrees < 0:- raise ValueError(f"If Degrees is only one number it must be a positive number. Got{degrees}")- degrees = torch.tensor([-degrees, degrees])-- 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)}")-- 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.devicedtype: torch.dtype = input.dtypeinput = input.unsqueeze(0)input = input.view((-1, (*input.shape[-3:])))- angles: torch.Tensor = degrees.to(device, dtype)+ angles: torch.Tensor = params["degrees"].to(device, dtype)transformed: torch.Tensor = rotate(input, angles).squeeze(0)diff --git a/kornia/augmentation/param_gen.py b/kornia/augmentation/param_gen.pyindex 5e8c299f1..236c350e9 100644--- a/kornia/augmentation/param_gen.py+++ b/kornia/augmentation/param_gen.py@@ -229,6 +229,7 @@ def _random_affine_gen(batch_size, height, width, degrees_tmp, translate, scale, shear_tmp)return dict(transform=transform)+def _random_rotation_gen(batch_size: int, degrees: FloatUnionType) -> Dict[str, torch.Tensor]:if not torch.is_tensor(degrees):@@ -254,6 +255,7 @@ def _random_rotation_gen(batch_size: int, degrees: FloatUnionType) -> Dict[str,return params+def _get_random_affine_params(batch_size: int, height: int, width: int,degrees: TupleFloat, translate: Optional[TupleFloat],diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex 85bfa9490..72776a458 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -8,7 +8,7 @@ from torch.autograd import gradcheckimport korniaimport kornia.testing as utils # test utilsfrom kornia.augmentation import RandomHorizontalFlip, RandomVerticalFlip, ColorJitter, \- RandomRectangleErasing, RandomGrayscale+ RandomRectangleErasing, RandomGrayscale, RandomRotationfrom kornia.augmentation.erasing import get_random_rectangles_params, erase_rectanglesfrom test.common import device@@ -1136,11 +1136,11 @@ class TestRandomRotation:f = nn.Sequential(RandomRotation(torch.tensor([-45.0, 90]), return_transform=True),- RandomRotation(-10.4, return_transform=True),+ RandomRotation(10.4, return_transform=True),)f1 = nn.Sequential(RandomRotation(torch.tensor([-45.0, 90]), return_transform=True),- RandomRotation(-10.4),+ RandomRotation(10.4),)input = torch.tensor([[1., 0., 0., 2.],