π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Merge remote-tracking branch 'upstream/master' into random_rotation
dvd428f73f817f95f
diff --cc docs/source/augmentation.rstindex 085c55c79,45fdf5f4d..2996004d0--- a/docs/source/augmentation.rst+++ b/docs/source/augmentation.rst@@@ -3,18 -3,13 +3,23 @@@ kornia.augmentatio.. currentmodule:: kornia.augmentation+The functions in this section perform various data augmentation operations++.. autofunction:: random_hflip+.. autofunction:: random_vflip+.. autofunction:: color_jitter+.. autofunction:: random_rectangle_erase+.. autofunction:: random_grayscale+.. autofunction:: random_rotation++ The classes in this section perform various data augmentation operations+.. autoclass:: RandomHorizontalFlip.. autoclass:: RandomVerticalFlip- .. autoclass:: ColorJitter.. autoclass:: RandomRectangleErasing.. autoclass:: RandomGrayscale+.. autoclass:: RandomRotation+ .. autoclass:: ColorJitter++ .. automodule:: kornia.augmentation.functional+ :members:diff --cc kornia/augmentation/augmentation.pyindex 000000000,1683bc3e4..491e62546mode 000000,100644..100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@@ -1,0 -1,345 +1,450 @@@+ from typing import Callable, Tuple, Union, List, Optional, Dict, cast++ import torch+ import torch.nn as nn++ from . import functional as F+ from . 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]]+++ class AugmentationBase(nn.Module):+ def __init__(self, apply_fcn: Callable, return_transform: bool = False) -> None:+ super(AugmentationBase, self).__init__()+ self.return_transform = return_transform+ self._apply_fcn: Callable = apply_fcn++ def infer_batch_size(self, input) -> int:+ 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+ return batch_size++ def infer_image_shape(self, input: UnionType) -> Tuple[int, int]:+ if isinstance(input, tuple):+ data, _ = cast(Tuple, input)+ else:+ data = cast(torch.Tensor, input)+ return data.shape[-2:]++ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore+ if isinstance(input, tuple):++ inp: torch.Tensor = input[0]+ prev_trans: torch.Tensor = input[1]++ if self.return_transform:++ out = self._apply_fcn(inp, params, 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, self._apply_fcn(inp, params, return_transform=False))++ # Transform image but pass along the previous transformation+ return img, prev_trans++ return self._apply_fcn(input, params, return_transform=self.return_transform)+++ class RandomHorizontalFlip(AugmentationBase):++ 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)`.+ 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 Horizontally flip 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:+ p (float): probability of the image being flipped. Default value is 0.5+ 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([[[[0., 0., 0.],+ [0., 0., 0.],+ [0., 1., 1.]]]])+ >>> seq = nn.Sequential(kornia.augmentation.RandomHorizontalFlip(p=1.0, return_transform=True),+ kornia.augmentation.RandomHorizontalFlip(p=1.0, return_transform=True)+ )+ >>> seq(input)+ (tensor([[0., 0., 0.],+ [0., 0., 0.],+ [0., 1., 1.]]),+ tensor([[[1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.]]]))++ """++ def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:+ super(RandomHorizontalFlip, self).__init__(F.apply_hflip, return_transform)+ self.p: float = p++ @staticmethod+ def get_params(batch_size: int, p: float) -> Dict[str, torch.Tensor]:+ return pg._random_prob_gen(batch_size, p)++ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore+ if params is None:+ batch_size = self.infer_batch_size(input)+ params = self.get_params(batch_size, self.p)+ return super().forward(input, params)+++ class RandomVerticalFlip(AugmentationBase):++ r"""Vertically 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)`.+ 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 Vertically flip 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:+ p (float): probability of the image being flipped. Default value is 0.5+ 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([[[[0., 0., 0.],+ [0., 0., 0.],+ [0., 1., 1.]]]])+ >>> seq = nn.Sequential(kornia.augmentation.RandomVerticalFlip(p=1.0, return_transform=True))+ >>> seq(input)+ (tensor([[0., 1., 1.],+ [0., 0., 0.],+ [0., 0., 0.]]),+ tensor([[[1., 0., 0.],+ [0., -1., 3.],+ [0., 0., 1.]]]))++ """++ def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:+ super(RandomVerticalFlip, self).__init__(F.apply_vflip, return_transform)+ self.p: float = p++ @staticmethod+ def get_params(batch_size: int, p: float) -> Dict[str, torch.Tensor]:+ return pg._random_prob_gen(batch_size, p)++ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore+ if params is None:+ batch_size = self.infer_batch_size(input)+ params = self.get_params(batch_size, self.p)+ return super().forward(input, params)+++ class ColorJitter(AugmentationBase):++ r"""Change the brightness, contrast, saturation and hue randomly given tensor image or a batch of tensor images.++ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.++ Args:+ brightness (float or tuple): Default value is 0+ contrast (float or tuple): Default value is 0+ saturation (float or tuple): Default value is 0+ hue (float or tuple): Default value is 0+ 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+ """++ def __init__(self, brightness: FloatUnionType = 0., contrast: FloatUnionType = 0.,+ saturation: FloatUnionType = 0., hue: FloatUnionType = 0., return_transform: bool = False) -> None:+ super(ColorJitter, self).__init__(F.apply_color_jitter, return_transform)+ self.brightness: FloatUnionType = brightness+ self.contrast: FloatUnionType = contrast+ self.saturation: FloatUnionType = saturation+ self.hue: FloatUnionType = hue+ self.return_transform: bool = return_transform++ def __repr__(self) -> str:+ repr = f"(brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation},\+ hue={self.hue}, return_transform={self.return_transform})"+ return self.__class__.__name__ + repr++ @staticmethod+ def get_params(batch_size: int, brightness: FloatUnionType = 0., contrast: FloatUnionType = 0.,+ saturation: FloatUnionType = 0., hue: FloatUnionType = 0.) -> Dict[str, torch.Tensor]:+ return pg._random_color_jitter_gen(batch_size, brightness, contrast, saturation, hue)++ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore+ if params is None:+ batch_size = self.infer_batch_size(input)+ params = ColorJitter.get_params(batch_size, self.brightness, self.contrast, self.saturation, self.hue)+ return super().forward(input, params)+++ class RandomGrayscale(AugmentationBase):+ r"""Random Grayscale transformation according to a probability p value++ Args:+ p (float): probability of the image to be transformed to grayscale. Default value is 0.5+ 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+ """++ def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:+ super(RandomGrayscale, self).__init__(F.apply_grayscale, return_transform)+ self.p = p++ def __repr__(self) -> str:+ repr = f"(p={self.p}, return_transform={self.return_transform})"+ return self.__class__.__name__ + repr++ @staticmethod+ def get_params(batch_size: int, p: float = .5) -> Dict[str, torch.Tensor]:+ return pg._random_prob_gen(batch_size, p)++ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore+ if params is None:+ batch_size = self.infer_batch_size(input)+ params = RandomGrayscale.get_params(batch_size, self.p)+ return super().forward(input, params)+++ class RandomRectangleErasing(nn.Module):+ r"""+ Erases a random selected rectangle for each image in the batch, putting the value to zero.+ The rectangle will have an area equal to the original image area multiplied by a value uniformly+ sampled between the range [erase_scale_range[0], erase_scale_range[1]) and an aspect ratio sampled+ between [aspect_ratio_range[0], aspect_ratio_range[1])++ Args:+ erase_scale_range (Tuple[float, float]): range of proportion of erased area against input image.+ aspect_ratio_range (Tuple[float, float]): range of aspect ratio of erased area.++ Examples:+ >>> inputs = torch.ones(1, 1, 3, 3)+ >>> rec_er = kornia.augmentation.RandomRectangleErasing((.4, .8), (.3, 1/.3))+ >>> rec_er(inputs)+ tensor([[[[1., 0., 0.],+ [1., 0., 0.],+ [1., 0., 0.]]]])+ """++ def __init__(+ self, erase_scale_range: Tuple[float, float], aspect_ratio_range: Tuple[float, float]+ ) -> None:+ super(RandomRectangleErasing, self).__init__()+ self.erase_scale_range: Tuple[float, float] = erase_scale_range+ self.aspect_ratio_range: Tuple[float, float] = aspect_ratio_range++ def forward(self, images: torch.Tensor) -> torch.Tensor: # type: ignore+ return F.random_rectangle_erase(+ images,+ self.erase_scale_range,+ self.aspect_ratio_range+ )+++ class RandomPerspective(AugmentationBase):+ r"""Performs Perspective transformation of the given torch.Tensor randomly with a given probability.++ Args:+ p (float): probability of the image being perspectively transformed. Default value is 0.5+ distortion_scale(float): it controls the degree of distortion and ranges from 0 to 1. Default value is 0.5.+ return_transform (bool): if ``True`` return the matrix describing the transformation+ applied to each. Default: False.+ input tensor.+ """++ def __init__(self, distortion_scale: float = 0.5, p: float = 0.5, return_transform: bool = False) -> None:+ super(RandomPerspective, self).__init__(F.apply_perspective, return_transform)+ self.p: float = p+ self.distortion_scale: float = distortion_scale+ self.return_transform: bool = return_transform++ def __repr__(self) -> str:+ repr = f"(distortion_scale={self.distortion_scale}, p={self.p}, return_transform={self.return_transform})"+ return self.__class__.__name__ + repr++ @staticmethod+ def get_params(batch_size: int, height: int, width: int, p: float,+ distortion_scale: float) -> Dict[str, torch.Tensor]:+ return pg._random_perspective_gen(batch_size, height, width, p, distortion_scale)++ 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.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)++++++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:++ >>> 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)++++ 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 --cc kornia/augmentation/functional.pyindex 000000000,56f3452bc..1946aa3c5mode 000000,100644..100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@@ -1,0 -1,467 +1,545 @@@+ from typing import Tuple, List, Union, Dict, cast, Optional++ import torch+ import torch.nn as nn++ from kornia.geometry.transform.flips import hflip, vflip+ from kornia.geometry.transform import get_perspective_transform, warp_perspective+ from kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHue+ from kornia.color.gray import rgb_to_grayscale++from kornia.geometry.transform import _compute_rotation_matrix, _compute_tensor_center++ from . import param_gen as pg+ from .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]]+++ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False) -> UnionType:+ r"""Generate params and apply operation on input tensor.++ See :func:`~kornia.augmentation.param_gen._random_prob_gen` for details.+ See :func:`~kornia.augmentation.functional.apply_hflip` for details.+ """++ 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+ params = pg._random_prob_gen(batch_size, p=p)+ return apply_hflip(input, params, return_transform)+++ def random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False) -> UnionType:+ r"""Generate params and apply operation on input tensor.++ See :func:`~kornia.augmentation.param_gen._random_prob_gen` for details.+ See :func:`~kornia.augmentation.functional.apply_vflip` for details.+ """++ 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+ params = pg._random_prob_gen(batch_size, p=p)+ return apply_vflip(input, params, return_transform)+++ def color_jitter(input: torch.Tensor, brightness: FloatUnionType = 0.,+ contrast: FloatUnionType = 0., saturation: FloatUnionType = 0.,+ hue: FloatUnionType = 0., return_transform: bool = False) -> UnionType:+ r"""Generate params and apply operation on input tensor.++ See :func:`~kornia.augmentation.param_gen._random_color_jitter_gen` for details.+ See :func:`~kornia.augmentation.functional.apply_color_jitter` for details.+ """++ 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+ params = pg._random_color_jitter_gen(batch_size, brightness, contrast, saturation, hue)+ return apply_color_jitter(input, params, return_transform)+++ def random_grayscale(input: torch.Tensor, p: float = 0.5, return_transform: bool = False):+ r"""Generate params and apply operation on input tensor.++ See :func:`~kornia.augmentation.param_gen._random_prob_gen` for details.+ See :func:`~kornia.augmentation.functional.apply_grayscale` for details.+ """++ 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+ params = pg._random_prob_gen(batch_size, p=p)+ return apply_grayscale(input, params, return_transform)+++ def random_perspective(input: torch.Tensor,+ distortion_scale: float = 0.5,+ p: float = 0.5,+ return_transform: bool = False) -> UnionType:+ r"""Performs Perspective transformation of the given torch.Tensor randomly with a given probability.++ See :func:`~kornia.augmentation.param_gen._random_perspective_gen` for details.+ See :func:`~kornia.augmentation.functional.apply_perspective` for details.+ """++ 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++ See :func:`~kornia.augmentation.param_gen._random_affine_gen` for details.+ See :func:`~kornia.augmentation.functional.apply_affine` for details.+ """++ 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 random_rectangle_erase(++ images: torch.Tensor,++ erase_scale_range: Tuple[float, float],++ aspect_ratio_range: Tuple[float, float]++) -> torch.Tensor:++ r"""++ Function that erases a random selected rectangle for each image in the batch, putting++ the value to zero.++ The rectangle will have an area equal to the original image area multiplied by a value uniformly++ sampled between the range [erase_scale_range[0], erase_scale_range[1]) and an aspect ratio sampled++ between [aspect_ratio_range[0], aspect_ratio_range[1])++++ Args:++ images (torch.Tensor): input images.++ erase_scale_range (Tuple[float, float]): range of proportion of erased area against input image.++ aspect_ratio_range (Tuple[float, float]): range of aspect ratio of erased area.++ """++++ if not (isinstance(erase_scale_range[0], float) and++ isinstance(erase_scale_range[1], float) and++ erase_scale_range[0] > 0. and erase_scale_range[1] > 0.):++ raise TypeError(++ f"'erase_scale_range' must be a Tuple[float, float] with positive values"++ )++ if not (isinstance(aspect_ratio_range[0], float) and++ isinstance(aspect_ratio_range[1], float) and++ aspect_ratio_range[0] > 0. and aspect_ratio_range[1] > 0.):++ raise TypeError(++ f"'aspect_ratio_range' must be a Tuple[float, float] with positive values"++ )++++ images_size = images.size()++ b, _, h, w = images_size++ rect_params = get_random_rectangles_params(++ (b, ), h, w, erase_scale_range, aspect_ratio_range++ )++ images = erase_rectangles(images, rect_params)++ return images++++++def random_rotation(input: torch.Tensor, degrees: FloatUnionType, return_transform: bool = False) -> UnionType:++ r"""Generate params and apply operation on input tensor.++++ See :func:`~kornia.augmentation.param_gen._random_rotation_gen` for details.++ See :func:`~kornia.augmentation.functional.apply_rotation` for details.++ """++ input_tmp: torch.Tensor = input.unsqueeze(0)++ input_tmp = input_tmp.view(-1, *input_tmp.shape[-3:])++ batch_size = input_tmp.shape[0]++++ params = pg._random_rotation_gen(batch_size, degrees=degrees)++++ return apply_rotation(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)`.++ Args:+ params (dict): A dict that must have {'batch_prob': torch.Tensor}. Can be generated from+ kornia.augmentation.param_gen._random_prob_gen.+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor.++ Returns:+ torch.Tensor: The horizontally flipped input+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)` if return_transform flag+ is set to ``True``+ """++ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if len(input.shape) == 2:+ input = input.unsqueeze(0)++ if len(input.shape) == 3:+ input = input.unsqueeze(0)++ if len(input.shape) != 4:+ raise ValueError(f"Input size must have a shape of (*, C, H, W). Got {input.shape}")++ 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++ flipped: torch.Tensor = input.clone()++ to_flip = params['batch_prob'].to(device)+ flipped[to_flip] = hflip(input[to_flip])+ flipped.squeeze_()++ if return_transform:++ trans_mat: torch.Tensor = torch.eye(3, device=device, dtype=dtype).repeat(input.shape[0], 1, 1)++ w: int = input.shape[-1]+ flip_mat: torch.Tensor = torch.tensor([[-1, 0, w],+ [0, 1, 0],+ [0, 0, 1]])++ trans_mat[to_flip] = flip_mat.to(device).to(dtype)++ return flipped, trans_mat++ return flipped+++ def apply_vflip(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False) -> UnionType:+ r"""Apply vertically 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)`.++ Args:+ params (dict): A dict that must have {'batch_prob': torch.Tensor}. Can be generated from+ kornia.augmentation.param_gen._random_prob_gen.+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor.++ Returns:+ torch.Tensor: The vertically flipped input+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)` if return_transform flag+ is set to ``True``+ """+ # TODO: params validation++ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if len(input.shape) == 2:+ input = input.unsqueeze(0)++ if len(input.shape) == 3:+ input = input.unsqueeze(0)++ if len(input.shape) != 4:+ raise ValueError(f"Input size must have a shape of (*, C, H, W). Got {input.shape}")++ 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++ flipped: torch.Tensor = input.clone()+ to_flip = params['batch_prob'].to(device)+ flipped[to_flip] = vflip(input[to_flip])++ if return_transform:++ trans_mat: torch.Tensor = torch.eye(3, device=device, dtype=dtype).repeat(input.shape[0], 1, 1)++ h: int = input.shape[-2]+ flip_mat: torch.Tensor = torch.tensor([[1, 0, 0],+ [0, -1, h],+ [0, 0, 1]])++ trans_mat[to_flip] = flip_mat.to(device).to(dtype)++ return flipped, trans_mat++ return flipped+++ def apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor],+ return_transform: bool = False) -> UnionType:+ r"""Apply Color Jitter 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)`.++ Args:+ params (dict): A dict that must have {+ 'brightness_factor': torch.Tensor,+ 'contrast_factor': torch.Tensor,+ 'hue_factor': torch.Tensor,+ 'saturation_factor': torch.Tensor,+ }. Can be generated from kornia.augmentation.param_gen._random_color_jitter_gen+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor.++ Returns:+ torch.Tensor: The color jitterred input+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)` if return_transform flag+ is set to ``True``+ """+ # TODO: params validation++ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if len(input.shape) == 2:+ input = input.unsqueeze(0)++ if len(input.shape) == 3:+ input = input.unsqueeze(0)++ if len(input.shape) != 4:+ raise ValueError(f"Input size must have a shape of (*, C, H, W). Got {input.shape}")++ 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++ transforms = nn.ModuleList([AdjustBrightness(params['brightness_factor'].to(device)),+ AdjustContrast(params['contrast_factor'].to(device)),+ AdjustSaturation(params['saturation_factor'].to(device)),+ AdjustHue(params['hue_factor'].to(device))])++ jittered = input++ for idx in torch.randperm(4).tolist():+ t = transforms[idx]+ jittered = t(jittered)++ if return_transform:++ identity: torch.Tensor = torch.eye(3, device=device, dtype=dtype).repeat(input.shape[0], 1, 1)++ return jittered, identity++ return jittered+++ def apply_grayscale(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False) -> UnionType:+ r"""Apply Gray Scale on a tensor image or a batch of tensor images with given random parameters.+ Input should be a tensor of shape (3, H, W) or a batch of tensors :math:`(*, 3, H, W)`.++ Args:+ params (dict): A dict that must have {'batch_prob': torch.Tensor}. Can be generated from+ kornia.augmentation.param_gen._random_prob_gen+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor.++ Returns:+ torch.Tensor: The grayscaled input+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)` if return_transform flag+ is set to ``True``+ """+ # TODO: params validation++ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if len(input.shape) == 3 and input.shape[-3] == 3:+ input = input.unsqueeze(0)++ if len(input.shape) != 4 or input.shape[-3] != 3:+ raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {input.shape}")++ 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++ grayscale: torch.Tensor = input.clone()++ to_gray = params['batch_prob'].to(device)++ grayscale[to_gray] = rgb_to_grayscale(input[to_gray])+ if return_transform:++ identity: torch.Tensor = torch.eye(3, device=device, dtype=dtype).repeat(input.shape[0], 1, 1)++ return grayscale, identity++ return grayscale++-def random_rectangle_erase(- images: torch.Tensor,- erase_scale_range: Tuple[float, float],- aspect_ratio_range: Tuple[float, float]-) -> torch.Tensor:- r"""- Function that erases a random selected rectangle for each image in the batch, putting- the value to zero.- The rectangle will have an area equal to the original image area multiplied by a value uniformly- sampled between the range [erase_scale_range[0], erase_scale_range[1]) and an aspect ratio sampled- between [aspect_ratio_range[0], aspect_ratio_range[1])-- Args:- images (torch.Tensor): input images.- erase_scale_range (Tuple[float, float]): range of proportion of erased area against input image.- aspect_ratio_range (Tuple[float, float]): range of aspect ratio of erased area.- """-- if not (isinstance(erase_scale_range[0], float) and- isinstance(erase_scale_range[1], float) and- erase_scale_range[0] > 0. and erase_scale_range[1] > 0.):- raise TypeError(- f"'erase_scale_range' must be a Tuple[float, float] with positive values"- )- if not (isinstance(aspect_ratio_range[0], float) and- isinstance(aspect_ratio_range[1], float) and- aspect_ratio_range[0] > 0. and aspect_ratio_range[1] > 0.):- raise TypeError(- f"'aspect_ratio_range' must be a Tuple[float, float] with positive values"- )-- images_size = images.size()- b, _, h, w = images_size- rect_params = get_random_rectangles_params(- (b, ), h, w, erase_scale_range, aspect_ratio_range- )- images = erase_rectangles(images, rect_params)- return images--+ def apply_perspective(input: torch.Tensor,+ params: Dict[str, torch.Tensor],+ return_transform: bool = False) -> UnionType:+ r"""Perform perspective transform of the given torch.Tensor or batch of tensors.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape BxCxHxW.+ start_points (torch.Tensor): Tensor containing [top-left, top-right, bottom-right,+ bottom-left] of the orignal image with shape Bx4x2.+ end_points (torch.Tensor): Tensor containing [top-left, top-right, bottom-right,+ bottom-left] of the transformed image with shape Bx4x2.+ return_transform (bool): if ``True`` return the matrix describing the transformation+ applied to each. Default: False.++ Returns:+ torch.Tensor: Perspectively transformed tensor.+ """++ 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:])++ batch_size, _, height, width = x_data.shape++ # compute the homography between the input points+ transform: torch.Tensor = get_perspective_transform(+ params['start_points'], params['end_points']).to(device, dtype)++ out_data: torch.Tensor = x_data.clone()++ # process valid samples+ mask = params['batch_prob'].to(device)++ # apply the computed transform+ height, width = x_data.shape[-2:]+ out_data[mask] = warp_perspective(x_data[mask], transform[mask], (height, width))++ if return_transform:+ return out_data.view_as(input), transform++ return 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)}")+ 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 applied. 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'.+ """+++ 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)++++++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:++ 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++ """++ 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.device++ dtype: torch.dtype = input.dtype++++ input = input.unsqueeze(0)++ input = input.view((-1, (*input.shape[-3:])))++ angles: torch.Tensor = 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 transformeddiff --cc kornia/augmentation/param_gen.pyindex 000000000,458f05f1c..5e8c299f1mode 000000,100644..100644--- a/kornia/augmentation/param_gen.py+++ b/kornia/augmentation/param_gen.py@@@ -1,0 -1,278 +1,302 @@@-from typing import Tuple, List, Union, Dict, Optional++from typing import Tuple, List, Union, Dict, Optional, cast++ import torch+ from torch.distributions import Uniform++ from kornia.geometry import pi+ from kornia.geometry.transform import get_rotation_matrix2d+++ UnionType = 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.,+ hue: FloatUnionType = 0.) -> Dict[str, torch.Tensor]:+ r"""Generator random color jiter parameters for a batch of images.++ Args:+ batch_size (int): the number of images.+ brightness (float or tuple): Default value is 0+ contrast (float or tuple): Default value is 0+ saturation (float or tuple): Default value is 0+ hue (float or tuple): Default value is 0++ Returns:+ dict: generated parameter dictionary.++ See :class:`~kornia.augmentation.ColorJitter` for details.+ """++ def _check_and_bound(factor: FloatUnionType, name: str, center: float = 0.,+ bounds: Tuple[float, float] = (0, float('inf'))) -> torch.Tensor:+ r"""Check inputs and compute the corresponding factor bounds+ """++ if isinstance(factor, float):++ if factor < 0:+ raise ValueError(f"If {name} is a single number number, it must be non negative. Got {factor}")++ factor_bound = torch.tensor([center - factor, center + factor], dtype=torch.float32)+ factor_bound = torch.clamp(factor_bound, bounds[0], bounds[1])++ elif (isinstance(factor, torch.Tensor) and factor.dim() == 0):++ if factor < 0:+ raise ValueError(f"If {name} is a single number number, it must be non negative. Got {factor}")++ factor_bound = torch.tensor(+ [torch.tensor(center) - factor, torch.tensor(center) + factor], dtype=torch.float32)+ factor_bound = torch.clamp(factor_bound, bounds[0], bounds[1])++ elif isinstance(factor, (tuple, list)) and len(factor) == 2:++ if not bounds[0] <= factor[0] <= factor[1] <= bounds[1]:+ raise ValueError(f"{name}[0] should be smaller than {name}[1] got {factor}")++ factor_bound = torch.tensor(factor, dtype=torch.float32)++ elif isinstance(factor, torch.Tensor) and factor.shape[0] == 2 and factor.dim() == 1:++ if not bounds[0] <= factor[0] <= factor[1] <= bounds[1]:+ raise ValueError(f"{name}[0] should be smaller than {name}[1] got {factor}")++ factor_bound = factor++ else:++ raise TypeError(+ f"The {name} should be a float number or a tuple with length 2 whose values move between {bounds}.")++ return factor_bound++ brightness_bound: torch.Tensor = _check_and_bound(+ brightness, 'brightness', bounds=(+ float('-inf'), float('inf')))+ contrast_bound: torch.Tensor = _check_and_bound(contrast, 'contrast', center=1.)+ saturation_bound: torch.Tensor = _check_and_bound(saturation, 'saturation', center=1.)+ hue_bound: torch.Tensor = _check_and_bound(hue, 'hue', bounds=(-pi.item(), pi.item()))++ brightness_distribution = Uniform(brightness_bound[0], brightness_bound[1])+ brightness_factor = brightness_distribution.rsample([batch_size])++ contrast_distribution = Uniform(contrast_bound[0], contrast_bound[1])+ contrast_factor = contrast_distribution.rsample([batch_size])++ hue_distribution = Uniform(hue_bound[0], hue_bound[1])+ hue_factor = hue_distribution.rsample([batch_size])++ saturation_distribution = Uniform(saturation_bound[0], saturation_bound[1])+ saturation_factor = saturation_distribution.rsample([batch_size])++ return {+ "brightness_factor": brightness_factor,+ "contrast_factor": contrast_factor,+ "hue_factor": hue_factor,+ "saturation_factor": saturation_factor,+ }+++ def _random_prob_gen(batch_size: int, p: float = 0.5) -> Dict[str, torch.Tensor]:+ r"""Generator random probabilities for a batch of inputs.++ Args:+ batch_size (int): the number of images.+ p (float): probability of the image being flipped or grayscaled. Default value is 0.5++ Returns:+ dict: generated parameter dictionary.++ See :class:`~kornia.augmentation.RandomGrayscale` for details.+ See :class:`~kornia.augmentation.RandomHorizontalFlip` for details.+ See :class:`~kornia.augmentation.RandomVerticalFlip` for details.+ """++ if not isinstance(p, float):+ raise TypeError(f"The probability should be a float number. Got {type(p)}")++ probs: torch.Tensor = Uniform(0, 1).rsample((batch_size,))++ batch_prob: torch.Tensor = probs < p++ return {'batch_prob': batch_prob}+++ def _get_perspective_params(batch_size: int, width: int, height: int, distortion_scale: float+ ) -> Tuple[torch.Tensor, torch.Tensor]:+ r"""Get parameters for ``perspective`` for a random perspective transform.++ Args:+ batch_size (int): the tensor batch size.+ width (int): width of the image.+ height (int) : height of the image.+ distortion_scale (float): it controls the degree of distortion and ranges from 0 to 1. Default value is 0.5.++ Returns:+ List containing [top-left, top-right, bottom-right, bottom-left] of the original image,+ List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image.+ The points are in -x order.+ """+ start_points: torch.Tensor = torch.tensor([[+ [0., 0],+ [0, width - 1],+ [height - 1, 0],+ [height - 1, width - 1],+ ]]).expand(batch_size, -1, -1)++ # generate random offset not larger than half of the image+ fx: float = distortion_scale * width / 2+ fy: float = distortion_scale * height / 2++ factor = torch.tensor([fy, fx]).view(-1, 1, 2)++ rand_val: torch.Tensor = Uniform(0, 1).rsample((batch_size, 4, 2))+ offset = 2 * factor - 1++ end_points = start_points + offset++ return start_points, end_points+++ def _random_perspective_gen(+ batch_size: int, height: int, width: int, p: float, distortion_scale: float+ ) -> Dict[str, torch.Tensor]:+ params: Dict[str, torch.Tensor] = _random_prob_gen(batch_size, p)+ start_points, end_points = (+ _get_perspective_params(batch_size, width, height, distortion_scale)+ )+ params['start_points'] = start_points+ params['end_points'] = end_points+ return 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 _random_rotation_gen(batch_size: int, degrees: FloatUnionType) -> Dict[str, torch.Tensor]:++++ 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)}")++++ # 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")++++ params: Dict[str, torch.Tensor] = {}++ params["degrees"] = Uniform(degrees[0], degrees[1]).rsample([batch_size])++++ return params++ 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 --cc test/augmentation/test_augmentation.pyindex 8541f0bf8,07bf2b75f..85bfa9490--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@@ -743,7 -743,7 +743,7 @@@ class TestColorJitterassert_allclose(f(input)[0], expected, atol=1e-4, rtol=1e-5)assert_allclose(f(input)[1], expected_transform)- def test_color_jitter_batch(self, device):- def test_color_jitter_batch_sequential(self):++ def test_color_jitter_batch_sequential(self, device):f = nn.Sequential(ColorJitter(return_transform=True),ColorJitter(return_transform=True),