π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
implement random affine
edgarriba3050d1737eff
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex 82ad01882..dad820d0f 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -7,6 +7,8 @@ from . import functional as Ffrom . import param_gen as pg+TupleFloat = Tuple[float, float]+UnionFloat = Union[float, TupleFloat]UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]@@ -283,3 +285,60 @@ class RandomPerspective(AugmentationBase):batch_size: int = self.infer_batch_size(input)params = self.get_params(batch_size, height, width, self.p, self.distortion_scale)return super().forward(input, params)+++class RandomAffine(AugmentationBase):+ r"""Random affine transformation of the image keeping center invariant.+ Args:+ degrees (float or tuple): Range of degrees to select from.+ If degrees is a number instead of sequence like (min, max), the range of degrees+ will be (-degrees, +degrees). Set to 0 to deactivate rotations.+ translate (tuple, optional): tuple of maximum absolute fraction for horizontal+ and vertical translations. For example translate=(a, b), then horizontal shift+ is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is+ randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.+ scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is+ randomly sampled from the range a <= scale <= b. Will keep original scale by default.+ shear (sequence or float, optional): Range of degrees to select from.+ If shear is a number, a shear parallel to the x axis in the range (-shear, +shear)+ will be apllied. Else if shear is a tuple or list of 2 values a shear parallel to the x axis in the+ range (shear[0], shear[1]) will be applied. Else if shear is a tuple or list of 4 values,+ a x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.+ Will not apply shear by default+ return_transform (bool): if ``True`` return the matrix describing the transformation+ applied to each. Default: False.+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ """++ def __init__(self,+ degrees: UnionFloat,+ translate: Optional[TupleFloat] = None,+ scale: Optional[TupleFloat] = None,+ shear: Optional[UnionFloat] = None,+ return_transform: bool = False) -> None:+ super(RandomAffine, self).__init__(F.apply_affine, return_transform)+ self.degrees = degrees+ self.translate = translate+ self.scale = scale+ self.shear = shear+ self.return_transform = return_transform++ @staticmethod+ def get_params(batch_size: int,+ height: int,+ width: int,+ degrees: UnionFloat,+ translate: Optional[TupleFloat] = None,+ scale: Optional[TupleFloat] = None,+ shear: Optional[UnionFloat] = None) -> Dict[str, torch.Tensor]:+ return pg._random_affine_gen(batch_size, height, width, degrees, translate, scale, shear)++ 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, height, width, self.degrees, self.translate, self.scale, self.shear)+ return super().forward(input, params)diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.pyindex 058d64b8e..4af5861f6 100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@ -1,4 +1,4 @@-from typing import Tuple, List, Union, Dict, cast+from typing import Tuple, List, Union, Dict, cast, Optionalimport torchimport torch.nn as nn@@ -12,6 +12,8 @@ from . import param_gen as pgfrom .erasing import erase_rectangles, get_random_rectangles_params+TupleFloat = Tuple[float, float]+UnionFloat = Union[float, TupleFloat]UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]@@ -88,15 +90,49 @@ def random_perspective(input: torch.Tensor,applied to each. Default: False.input tensor."""- if isinstance(input, tuple):- batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1- else:- batch_size = input.shape[0] if len(input.shape) == 4 else 1- height, width = input.shape[-2:]- params = pg._random_perspective_gen(batch_size, height, width, p, distortion_scale)+ batch_size, _, height, width = input.shape+ params: Dict[str, torch.Tensor] = pg._random_perspective_gen(+ batch_size, height, width, p, distortion_scale)return apply_perspective(input, params, return_transform)+def random_affine(input: torch.Tensor,+ degrees: UnionFloat,+ translate: Optional[TupleFloat] = None,+ scale: Optional[TupleFloat] = None,+ shear: Optional[UnionFloat] = None,+ return_transform: bool = False) -> UnionType:+ r"""Random affine transformation of the image keeping center invariant+ Args:+ input (torch.Tensor): Tensor to be transformed with shape (*, C, H, W).+ degrees (float or tuple): Range of degrees to select from.+ If degrees is a number instead of sequence like (min, max), the range of degrees+ will be (-degrees, +degrees). Set to 0 to deactivate rotations.+ translate (tuple, optional): tuple of maximum absolute fraction for horizontal+ and vertical translations. For example translate=(a, b), then horizontal shift+ is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is+ randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.+ scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is+ randomly sampled from the range a <= scale <= b. Will keep original scale by default.+ shear (sequence or float, optional): Range of degrees to select from.+ If shear is a number, a shear parallel to the x axis in the range (-shear, +shear)+ will be apllied. Else if shear is a tuple or list of 2 values a shear parallel to the x axis in the+ range (shear[0], shear[1]) will be applied. Else if shear is a tuple or list of 4 values,+ a x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.+ Will not apply shear by default+ return_transform (bool): if ``True`` return the matrix describing the transformation+ applied to each. Default: False.+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ """+ batch_size, _, height, width = input.shape+ params: Dict[str, torch.Tensor] = pg._random_affine_gen(+ batch_size, height, width, degrees, translate, scale, shear)+ return apply_affine(input, params, return_transform)++def apply_hflip(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False) -> UnionType:r"""Apply Horizontally flip on a tensor image or a batch of tensor images with given random parameters.Input should be a tensor of shape (H, W), (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.@@ -398,3 +434,26 @@ def apply_perspective(input: torch.Tensor,return out_data.view_as(input), transformreturn out_data.view_as(input)+++def apply_affine(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)}")++ device: torch.device = input.device+ dtype: torch.dtype = input.dtype++ # arrange input data+ x_data: torch.Tensor = input.view(-1, *input.shape[-3:])++ height, width = x_data.shape[-2:]+ transform: torch.Tensor = params['transform'].to(device, dtype)++ out_data: torch.Tensor = warp_perspective(x_data, transform, (height, width))++ if return_transform:+ return out_data.view_as(input), transform++ return out_data.view_as(input)diff --git a/kornia/augmentation/param_gen.py b/kornia/augmentation/param_gen.pyindex c37f4239a..458f05f1c 100644--- a/kornia/augmentation/param_gen.py+++ b/kornia/augmentation/param_gen.py@@ -1,14 +1,19 @@-from typing import Tuple, List, Union, Dict+from typing import Tuple, List, Union, Dict, Optionalimport torchfrom torch.distributions import Uniformfrom kornia.geometry import pi+from kornia.geometry.transform import get_rotation_matrix2dUnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]+TupleInt = Tuple[int, int]+TupleFloat = Tuple[float, float]+UnionFloat = Union[float, TupleFloat]+def _random_color_jitter_gen(batch_size: int, brightness: FloatUnionType = 0.,contrast: FloatUnionType = 0., saturation: FloatUnionType = 0.,@@ -169,3 +174,105 @@ def _random_perspective_gen(params['start_points'] = start_pointsparams['end_points'] = end_pointsreturn params+++def _random_affine_gen(+ batch_size: int,+ height: int,+ width: int,+ degrees: UnionFloat,+ translate: Optional[TupleFloat] = None,+ scale: Optional[TupleFloat] = None,+ shear: Optional[UnionFloat] = None) -> Dict[str, torch.Tensor]:+ # check angle ranges+ degrees_tmp: TupleFloat+ if isinstance(degrees, float):+ if degrees < 0.:+ raise ValueError("If degrees is a single number, it must be positive.")+ degrees_tmp = (-degrees, degrees)+ else:+ assert isinstance(degrees, (tuple, list)) and len(degrees) == 2, \+ "degrees should be a list or tuple and it must be of length 2."+ degrees_tmp = degrees++ # check translation range+ if translate is not None:+ assert isinstance(translate, (tuple, list)) and len(translate) == 2, \+ "translate should be a list or tuple and it must be of length 2."+ for t in translate:+ if not (0.0 <= t <= 1.0):+ raise ValueError("translation values should be between 0 and 1")++ # check scale range+ if scale is not None:+ assert isinstance(scale, (tuple, list)) and len(scale) == 2, \+ "scale should be a list or tuple and it must be of length 2."+ for s in scale:+ if s <= 0:+ raise ValueError("scale values should be positive")++ # check shear range+ shear_tmp: Optional[TupleFloat]+ if shear is not None:+ if isinstance(shear, float):+ if shear < 0:+ raise ValueError("If shear is a single number, it must be positive.")+ shear_tmp = (-shear, shear)+ else:+ assert isinstance(shear, (tuple, list)) and len(shear) == 2, \+ "shear should be a list or tuple and it must be of length 2."+ shear_tmp = shear+ else:+ shear_tmp = shear++ transform: torch.Tensor = _get_random_affine_params(+ batch_size, height, width, degrees_tmp, translate, scale, shear_tmp)+ return dict(transform=transform)+++def _get_random_affine_params(+ batch_size: int, height: int, width: int,+ degrees: TupleFloat, translate: Optional[TupleFloat],+ scales: Optional[TupleFloat], shears: Optional[TupleFloat],+) -> torch.Tensor:+ r"""Get parameters for affine transformation. The returned matrix is Bx3x3.++ Returns:+ torch.Tensor: params to be passed to the affine transformation.+ """+ angle = torch.empty(batch_size).uniform_(degrees[0], degrees[1])++ # compute tensor ranges+ if scales is not None:+ scale = torch.empty(batch_size).uniform_(scales[0], scales[1])+ else:+ scale = torch.ones(batch_size)++ if shears is not None:+ shear = torch.empty(batch_size).uniform_(shears[0], shears[1])+ else:+ shear = torch.zeros(batch_size)++ if translate is not None:+ max_dx: float = translate[0] * width+ max_dy: float = translate[1] * height+ translations = torch.cat([+ torch.empty(batch_size).uniform_(-max_dx, max_dx),+ torch.empty(batch_size).uniform_(-max_dy, max_dy),+ ], dim=-1)+ else:+ translations = torch.zeros(batch_size, 2)++ center: torch.Tensor = torch.tensor(+ [width, height], dtype=torch.float32).view(1, 2) / 2++ # concatenate transforms+ transform: torch.Tensor = get_rotation_matrix2d(center, angle, scale)+ transform[..., 2] += translations # tx/ty+ transform[..., 0, 1] += shear+ transform[..., 1, 0] += shear++ # pad transform to get Bx3x3+ transform_h = torch.nn.functional.pad(transform, [0, 0, 0, 1], value=0.)+ transform_h[..., -1, -1] += 1.0+ return transform_hdiff --git a/test/augmentation/test_perspective.py b/test/augmentation/test_perspective.pyindex 4f3c731f7..72cb85454 100644--- a/test/augmentation/test_perspective.py+++ b/test/augmentation/test_perspective.py@@ -96,3 +96,30 @@ class TestRandomPerspective:input = torch.rand(1, 2, 5, 7).to(device)input = utils.tensor_to_gradcheck_var(input) # to varassert gradcheck(F.random_perspective, (input, 0., 1.), raise_exception=True)+++class TestRandomAffine:++ torch.manual_seed(0) # for random reproductibility++ def test_smoke_no_transform(self, device):+ x_data = torch.rand(1, 2, 8, 9).to(device)++ out = F.random_affine(x_data, 0.)++ assert out.shape == x_data.shape++ def test_smoke_transform(self, device):+ x_data = torch.rand(1, 2, 4, 5).to(device)++ out = F.random_affine(x_data, 0., return_transform=True)++ assert isinstance(out, tuple)+ assert len(out) == 2+ assert out[0].shape == x_data.shape+ assert out[1].shape == (1, 3, 3)++ def test_gradcheck(self, device):+ input = torch.rand(1, 2, 5, 7).to(device)+ input = utils.tensor_to_gradcheck_var(input) # to var+ assert gradcheck(kornia.augmentation.RandomAffine(0.), (input, ), raise_exception=True)