Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[DOC] Updated docstring for augmentation module (#554)

shijianjianbc407ce2a656
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rst
index 85d9d3999..87afa533e 100644
--- a/docs/source/augmentation.rst
+++ b/docs/source/augmentation.rst
@@ -25,8 +25,10 @@ This is the base class for creating a new transform. The user only needs to over
Create your own transformation:
.. code-block:: python
+ from kornia.augmentation import AugmentationBase
- class MyRandomTransform(nn.Module):
+
+ class MyRandomTransform(AugmentationBase):
def __init__(self, return_transform: bool = False) -> None:
super(MyRandomTransform, self).__init__(return_transform)
@@ -55,6 +57,58 @@ Create your own transformation:
Module
------
+Kornia augmentation implementations can be easily used in a TorchVision style using `nn.Sequential`.
+
+.. code-block:: python
+ import kornia.augmentation as K
+ import torch.nn as nn
+
+ transform = nn.Sequential(
+ K.RandomAffine(360),
+ K.ColorJitter(0.2, 0.3, 0.2, 0.3)
+ )
+
+Kornia augmentation implementations have two additional parameters compare to TorchVision, `return_transform` and `same_on_batch`. The former provides the ability of undoing one geometry transformation while the latter can be used to control the randomness for a batched transformation. To enable those behaviour, you may simply set the flags to True.
+
+.. code-block:: python
+ import kornia.augmentation as K
+
+
+ class MyAugmentationPipeline(nn.Module):
+ def __init__(self) -> None:
+ super(MyAugmentationPipeline, self).__init__()
+ self.aff = K.RandomAffine(360, return_transform=True, same_on_batch=True)
+ self.jit = K.ColorJitter(0.2, 0.3, 0.2, 0.3, same_on_batch=True)
+
+ def forward(self, input):
+ input, transform = self.aff(input)
+ input, transform = self.jit((input, transform))
+ return input, transform
+
+Example for semantic segmentation using low-level randomness control:
+
+.. code-block:: python
+ import kornia.augmentation as K
+
+
+ class MyAugmentationPipeline(nn.Module):
+ def __init__(self) -> None:
+ super(MyAugmentationPipeline, self).__init__()
+ self.aff = K.RandomAffine(360)
+ self.jit = K.ColorJitter(0.2, 0.3, 0.2, 0.3)
+
+ def forward(self, input, mask):
+ assert input.shape == mask.shape,
+ f"Input shape should be consistent with mask shape, while got {input.shape}, {mask.shape}"
+ aff_params = self.aff.generate_parameters(input.shape)
+ input = self.aff(input, aff_params)
+ mask = self.aff(mask, aff_params)
+
+ jit_params = self.jit.generate_parameters(input.shape)
+ input = self.jit(input, jit_params)
+ mask = self.jit(mask, jit_params)
+ return input, mask
+
.. autoclass:: RandomHorizontalFlip
.. autoclass:: RandomVerticalFlip
.. autoclass:: RandomErasing
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index c99f79c32..3e6107353 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -80,16 +80,14 @@ class RandomHorizontalFlip(AugmentationBase):
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)
- )
+ ... [0., 0., 0.],
+ ... [0., 1., 1.]]]])
+ >>> seq = nn.Sequential(RandomHorizontalFlip(p=1.0, return_transform=True),
+ ... RandomHorizontalFlip(p=1.0, return_transform=True))
>>> seq(input)
- (tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]),
- tensor([[[1., 0., 0.],
+ (tensor([[[[0., 0., 0.],
+ [0., 0., 0.],
+ [0., 1., 1.]]]]), tensor([[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]]]))
@@ -134,16 +132,15 @@ class RandomVerticalFlip(AugmentationBase):
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))
+ ... [0., 0., 0.],
+ ... [0., 1., 1.]]]])
+ >>> seq = 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.]]]))
+ (tensor([[[[0., 1., 1.],
+ [0., 0., 0.],
+ [0., 0., 0.]]]]), tensor([[[ 1., 0., 0.],
+ [ 0., -1., 3.],
+ [ 0., 0., 1.]]]))
"""
@@ -169,7 +166,6 @@ class RandomVerticalFlip(AugmentationBase):
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:
@@ -181,6 +177,23 @@ class ColorJitter(AugmentationBase):
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated
same_on_batch (bool): apply the same transformation across the batch. Default: False
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.ones(1, 3, 3, 3)
+ >>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1)
+ >>> aug(inputs)
+ tensor([[[[0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993]],
+ <BLANKLINE>
+ [[0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993]],
+ <BLANKLINE>
+ [[0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993]]]])
"""
def __init__(
@@ -219,6 +232,23 @@ class RandomGrayscale(AugmentationBase):
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated
same_on_batch (bool): apply the same transformation across the batch. Default: False
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.randn((1, 3, 3, 3))
+ >>> rec_er = RandomGrayscale(p=1.0)
+ >>> rec_er(inputs)
+ tensor([[[[-1.1344, -0.1330, 0.1517],
+ [-0.0791, 0.6711, -0.1413],
+ [-0.1717, -0.9023, 0.0819]],
+ <BLANKLINE>
+ [[-1.1344, -0.1330, 0.1517],
+ [-0.0791, 0.6711, -0.1413],
+ [-0.1717, -0.9023, 0.0819]],
+ <BLANKLINE>
+ [[-1.1344, -0.1330, 0.1517],
+ [-0.0791, 0.6711, -0.1413],
+ [-0.1717, -0.9023, 0.0819]]]])
"""
def __init__(self, p: float = 0.1, return_transform: bool = False, same_on_batch: bool = False) -> None:
@@ -254,8 +284,9 @@ class RandomErasing(AugmentationBase):
same_on_batch (bool): apply the same transformation across the batch. Default: False
Examples:
+ >>> rng = torch.manual_seed(0)
>>> inputs = torch.ones(1, 1, 3, 3)
- >>> rec_er = kornia.augmentation.RandomErasing((.4, .8), (.3, 1/.3))
+ >>> rec_er = RandomErasing(1.0, (.4, .8), (.3, 1/.3))
>>> rec_er(inputs)
tensor([[[[1., 0., 0.],
[1., 0., 0.],
@@ -301,6 +332,17 @@ class RandomPerspective(AugmentationBase):
return_transform (bool): if ``True`` return the matrix describing the transformation
applied to each. Default: False.
same_on_batch (bool): apply the same transformation across the batch. Default: False
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs= torch.tensor([[[[1., 0., 0.],
+ ... [0., 1., 0.],
+ ... [0., 0., 1.]]]])
+ >>> aug = RandomPerspective(0.5, 1.0)
+ >>> aug(inputs)
+ tensor([[[[0.0000, 0.2289, 0.0000],
+ [0.0000, 0.4800, 0.0000],
+ [0.0000, 0.0000, 0.0000]]]])
"""
def __init__(
@@ -336,31 +378,37 @@ class RandomPerspective(AugmentationBase):
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
- resample (int, str or kornia.Resample): Default: Resample.BILINEAR
- return_transform (bool): if ``True`` return the matrix describing the transformation
- applied to each. Default: False.
- same_on_batch (bool): apply the same transformation across the batch. Default: False
+ 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
+ resample (int, str or kornia.Resample): Default: Resample.BILINEAR
+ return_transform (bool): if ``True`` return the matrix describing the transformation
+ applied to each. Default: False.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False
Examples:
- >>> input = torch.rand(2, 3, 224, 224)
- >>> my_fcn = kornia.augmentation.RandomAffine((-15., 20.), return_transform=True)
- >>> out, transform = my_fcn(input) # 2x3x224x224 / 2x3x3
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 3)
+ >>> aug = RandomAffine((-15., 20.), return_transform=True)
+ >>> aug(input)
+ (tensor([[[[0.3961, 0.7310, 0.1574],
+ [0.1781, 0.3074, 0.5648],
+ [0.4804, 0.8379, 0.4234]]]]), tensor([[[ 0.9923, -0.1241, 0.1319],
+ [ 0.1241, 0.9923, -0.1164],
+ [ 0.0000, 0.0000, 1.0000]]]))
"""
def __init__(
@@ -397,12 +445,21 @@ class RandomAffine(AugmentationBase):
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.
return_transform (bool): if ``True`` return the matrix describing the transformation
applied to each. Default: False.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.randn(1, 1, 3, 3)
+ >>> aug = CenterCrop(2)
+ >>> aug(inputs)
+ tensor([[[[-0.1425, -1.1266],
+ [-0.0373, -0.6562]]]])
"""
def __init__(self, size: Union[int, Tuple[int, int]], return_transform: bool = False) -> None:
@@ -450,17 +507,19 @@ class RandomRotation(AugmentationBase):
same_on_batch (bool): apply the same transformation across the batch. Default: False
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]]]))
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.tensor([[1., 0., 0., 2.],
+ ... [0., 0., 0., 0.],
+ ... [0., 1., 2., 0.],
+ ... [0., 0., 1., 2.]])
+ >>> seq = RandomRotation(degrees=45.0, return_transform=True)
+ >>> seq(input)
+ (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]]]]), tensor([[[ 1.0000, -0.0059, 0.0088],
+ [ 0.0059, 1.0000, -0.0088],
+ [ 0.0000, 0.0000, 1.0000]]]))
"""
# Note: Extra params, center=None, fill=0 in TorchVision
@@ -492,6 +551,7 @@ class RandomRotation(AugmentationBase):
class RandomCrop(AugmentationBase):
r"""Random Crop on given size.
+
Args:
size (tuple): Desired output size of the crop, like (h, w).
padding (int or sequence, optional): Optional padding on each border
@@ -510,6 +570,14 @@ class RandomCrop(AugmentationBase):
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated
same_on_batch (bool): apply the same transformation across the batch. Default: False
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.randn(1, 1, 3, 3)
+ >>> aug = RandomCrop((2, 2))
+ >>> aug(inputs)
+ tensor([[[[-0.6562, -1.0009],
+ [ 0.2223, -0.5507]]]])
"""
def __init__(
@@ -573,6 +641,7 @@ class RandomCrop(AugmentationBase):
class RandomResizedCrop(AugmentationBase):
r"""Random Crop on given size and resizing the cropped patch to another.
+
Args:
size (Tuple[int, int]): expected output size of each edge
scale: range of size of the origin size cropped
@@ -582,6 +651,17 @@ class RandomResizedCrop(AugmentationBase):
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated
same_on_batch (bool): apply the same transformation across the batch. Default: False
+
+ Example:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.tensor([[[0., 1., 2.],
+ ... [3., 4., 5.],
+ ... [6., 7., 8.]]])
+ >>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
+ >>> aug(inputs)
+ tensor([[[[3.7500, 4.7500, 5.7500],
+ [5.2500, 6.2500, 7.2500],
+ [4.5000, 5.2500, 6.0000]]]])
"""
def __init__(
diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.py
index f789b69de..fe7a2d19c 100644
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@ -42,11 +42,8 @@ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = F
See :func:`~kornia.augmentation.random_generator.random_prob_generator` 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
+ input = _transform_input(input)
+ batch_size, _, h, w = input.size()
params = rg.random_prob_generator(batch_size, p=p)
output = apply_hflip(input, params)
if return_transform:
@@ -60,11 +57,8 @@ def random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = F
See :func:`~kornia.augmentation.random_generator.random_prob_generator` 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
+ input = _transform_input(input)
+ batch_size, _, h, w = input.size()
params = rg.random_prob_generator(batch_size, p=p)
output = apply_vflip(input, params)
if return_transform:
@@ -80,11 +74,8 @@ def color_jitter(input: torch.Tensor, brightness: FloatUnionType = 0.,
See :func:`~kornia.augmentation.random_generator.random_color_jitter_generator` 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
+ input = _transform_input(input)
+ batch_size, _, h, w = input.size()
params = rg.random_color_jitter_generator(batch_size, brightness, contrast, saturation, hue)
output = apply_color_jitter(input, params)
if return_transform:
@@ -98,11 +89,8 @@ def random_grayscale(input: torch.Tensor, p: float = 0.5, return_transform: bool
See :func:`~kornia.augmentation.random_generator.random_prob_generator` 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
+ input = _transform_input(input)
+ batch_size, _, h, w = input.size()
params = rg.random_prob_generator(batch_size, p=p)
output = apply_grayscale(input, params)
@@ -115,13 +103,14 @@ 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.
+ r"""Generate params and apply operation on input tensor.
See :func:`~kornia.augmentation.random_generator.random_perspective_generator` for details.
See :func:`~kornia.augmentation.functional.apply_perspective` for details.
"""
- batch_size, _, height, width = input.shape
+ input = _transform_input(input)
+ batch_size, _, height, width = input.size()
params: Dict[str, torch.Tensor] = rg.random_perspective_generator(
batch_size, height, width, p, distortion_scale)
output = apply_perspective(input, params)
@@ -138,13 +127,14 @@ def random_affine(input: torch.Tensor,
shear: Optional[UnionFloat] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
return_transform: bool = False) -> UnionType:
- r"""Random affine transformation of the image keeping center invariant
+ r"""Generate params and apply operation on input tensor.
See :func:`~kornia.augmentation.random_generator.random_affine_generator` for details.
See :func:`~kornia.augmentation.functional.apply_affine` for details.
"""
- batch_size, _, height, width = input.shape
+ input = _transform_input(input)
+ batch_size, _, height, width = input.size()
params: Dict[str, torch.Tensor] = rg.random_affine_generator(
batch_size, height, width, degrees, translate, scale, shear, resample)
output = apply_affine(input, params)
@@ -172,19 +162,12 @@ def random_rectangle_erase(
input (torch.Tensor): input images.
scale (Tuple[float, float]): range of proportion of erased area against input image.
ratio (Tuple[float, float]): range of aspect ratio of erased area.
- """
-
- if not (isinstance(scale[0], float) and isinstance(scale[1], float) and scale[0] > 0. and scale[1] > 0.):
- raise TypeError(
- f"'erase_scale_range' must be a Tuple[float, float] with positive values"
- )
- if not (isinstance(ratio[0], float) and isinstance(ratio[1], float) and ratio[0] > 0. and ratio[1] > 0.):
- raise TypeError(
- f"'ratio' must be a Tuple[float, float] with positive values"
- )
- images_size = input.size()
- b, _, h, w = images_size
+ See :func:`~kornia.augmentation.random_generator.random_rectangles_params_generator` for details.
+ See :func:`~kornia.augmentation.functional.apply_erase_rectangles` for details.
+ """
+ input = _transform_input(input)
+ b, _, h, w = input.size()
params = rg.random_rectangles_params_generator(
b, h, w, p, scale, ratio
)
@@ -200,12 +183,9 @@ def random_rotation(input: torch.Tensor, degrees: FloatUnionType, return_transfo
See :func:`~kornia.augmentation.random_generator.random_rotation_generator` 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]
-
+ input = _transform_input(input)
+ batch_size, _, _, _ = input.size()
params = rg.random_rotation_generator(batch_size, degrees=degrees)
-
output = apply_rotation(input, params)
if return_transform:
return output, compute_rotate_tranformation(input, params)
@@ -217,15 +197,12 @@ def apply_hflip(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.T
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.random_generator.random_prob_generator.
- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
- input tensor.
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.
Returns:
torch.Tensor: The horizontally flipped input
- torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)` if return_transform flag
- is set to ``True``
"""
input = _transform_input(input)
@@ -240,6 +217,16 @@ def apply_hflip(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.T
def compute_hflip_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.
+
+ Returns:
+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)`
+ """
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
to_flip = params['batch_prob'].to(input.device)
@@ -258,15 +245,12 @@ def apply_vflip(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.T
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.random_generator.random_prob_generator.
- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
- input tensor.
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.
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
@@ -281,6 +265,16 @@ def apply_vflip(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.T
def compute_vflip_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.
+
+ Returns:
+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)`
+ """
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
to_flip = params['batch_prob'].to(input.device)
@@ -301,20 +295,17 @@ def apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor]) ->
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,
- 'order': torch.Tensor (can be generated by torch.perm(4) by default)
- }. Can be generated from kornia.augmentation.random_generator.random_color_jitter_generator
- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
- input tensor.
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['brightness_factor']: The brightness factor.
+ - params['contrast_factor']: The contrast factor.
+ - params['hue_factor']: The hue factor.
+ - params['saturation_factor']: The saturation factor.
+ - params['order']: The order of applying color transforms.
+ 0 is brightness, 1 is contrast, 2 is saturation, 4 is hue.
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
@@ -337,6 +328,16 @@ def apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor]) ->
def compute_intensity_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor]):
+ r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['batch_prob']: A boolean tensor that indicating whether if to transform an image in a batch.
+
+ Returns:
+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)`. Returns identity transformations.
+ """
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
identity: torch.Tensor = torch.eye(3, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)
@@ -348,10 +349,9 @@ def apply_grayscale(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> tor
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.random_generator.random_prob_generator
- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
- input tensor.
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['batch_prob']: A boolean tensor that indicating whether if to transform an image in a batch.
Returns:
torch.Tensor: The grayscaled input
@@ -378,12 +378,14 @@ def apply_perspective(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> t
Args:
input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
- 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.
+ params (Dict[str, torch.Tensor]):
+ - params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.
+ - params['start_points']: Tensor containing [top-left, top-right, bottom-right,
+ bottom-left] of the orignal image with shape Bx4x2.
+ - params['end_points']: Tensor containing [top-left, top-right, bottom-right,
+ bottom-left] of the transformed image with shape Bx4x2.
+ - params['interpolation']: Integer tensor. NEAREST = 0, BILINEAR = 1.
+ - params['align_corners']: Boolean tensor.
Returns:
torch.Tensor: Perspectively transformed tensor.
@@ -423,6 +425,20 @@ def apply_perspective(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> t
def compute_perspective_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.
+ - params['start_points']: Tensor containing [top-left, top-right, bottom-right,
+ bottom-left] of the orignal image with shape Bx4x2.
+ - params['end_points']: Tensor containing [top-left, top-right, bottom-right,
+ bottom-left] of the transformed image with shape Bx4x2.
+
+ Returns:
+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)`
+ """
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
transform: torch.Tensor = get_perspective_transform(
@@ -431,34 +447,26 @@ def compute_perspective_transformation(input: torch.Tensor, params: Dict[str, to
def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Random affine transformation of the image keeping center invariant.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['angle']: Degrees of rotation.
+ - params['translations']: Horizontal and vertical translations.
+ - params['center']: Rotation center.
+ - params['scale']: Scaling params.
+ - params['sx']: Shear param toward x-axis.
+ - params['sy']: Shear param toward y-axis.
+ - params['resample']: Integer tensor. NEAREST = 0, BILINEAR = 1.
+ - params['align_corners']: Boolean tensor.
+
+ Returns:
+ torch.Tensor: The transfromed input
+ """
+
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 (H, W), (C, H, W), (*, 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
- resample (int): Can be retrieved from Resample. 0 is NEAREST, 1 is BILINEAR.
- 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'.
- """
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
@@ -481,6 +489,23 @@ def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.
def compute_affine_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['angle']: Degrees of rotation.
+ - params['translations']: Horizontal and vertical translations.
+ - params['center']: Rotation center.
+ - params['scale']: Scaling params.
+ - params['sx']: Shear param toward x-axis.
+ - params['sy']: Shear param toward y-axis.
+ - params['resample']: Integer tensor. NEAREST = 0, BILINEAR = 1.
+ - params['align_corners']: Boolean tensor.
+
+ Returns:
+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)`
+ """
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
transform = get_affine_matrix2d(
@@ -495,11 +520,12 @@ def apply_rotation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torc
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.random_generator.random_rotation_generator
- 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
+ input (torch.Tensor): input image.
+ params (Dict[str, torch.Tensor]):
+ - params['degrees']: degree to be applied.
+
+ Returns:
+ torch.Tensor: The cropped input
"""
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
@@ -514,6 +540,16 @@ def apply_rotation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torc
def compute_rotate_tranformation(input: torch.Tensor, params: Dict[str, torch.Tensor]):
+ r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
+
+ Args:
+ input (torch.Tensor): input image.
+ params (Dict[str, torch.Tensor]):
+ - params['degrees']: degree to be applied.
+
+ Returns:
+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)`
+ """
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
angles: torch.Tensor = params["degrees"].type_as(input)
@@ -531,16 +567,19 @@ def compute_rotate_tranformation(input: torch.Tensor, params: Dict[str, torch.Te
def apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- """
+ r"""Apply cropping by src bounding box and dst bounding box.
+ Order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in the x, y order.
+
Args:
- params (dict): A dict that must have {'src': torch.Tensor, 'dst': torch.Tensor}. Can be generated from
- kornia.augmentation.random_generator.random_crop_generator
- return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
- input tensor.
+ input (torch.Tensor): input image.
+ params (Dict[str, torch.Tensor]):
+ - params['src']: The applied cropping src matrix :math: `(*, 4, 2)`.
+ - params['dst']: The applied cropping dst matrix :math: `(*, 4, 2)`.
+ - params['interpolation']: Integer tensor. NEAREST = 0, BILINEAR = 1.
+ - params['align_corners']: Boolean tensor.
+
Returns:
- torch.Tensor: The grayscaled input
- torch.Tensor: The applied cropping matrix :math: `(*, 4, 2)` if return_transform flag
- is set to ``True``
+ torch.Tensor: The cropped input.
"""
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
@@ -553,6 +592,17 @@ def apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Te
def compute_crop_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor]):
+ r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
+
+ Args:
+ input (torch.Tensor): input image.
+ params (Dict[str, torch.Tensor]):
+ - params['src']: The applied cropping src matrix :math: `(*, 4, 2)`.
+ - params['dst']: The applied cropping dst matrix :math: `(*, 4, 2)`.
+
+ Returns:
+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)`
+ """
input = _transform_input(input)
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
transform: torch.Tensor = get_perspective_transform(params['src'].to(input.dtype), params['dst'].to(input.dtype))
@@ -567,12 +617,15 @@ def apply_erase_rectangles(input: torch.Tensor, params: Dict[str, torch.Tensor])
Args:
input (torch.Tensor): input image.
- params Dict[str, torch.Tensor]:
- params['widths'] must be widths tensor
- params['heights'] must be heights tensor
- params['xs'] must be x positions tensor
- params['ys'] must be y positions tensor
- params['values'] is the value to fill in
+ params (Dict[str, torch.Tensor]):
+ - params['widths']: widths tensor
+ - params['heights']: heights tensor
+ - params['xs']: x positions tensor
+ - params['ys']: y positions tensor
+ - params['values']: the value to fill in
+
+ Returns:
+ torch.Tensor: Erased image.
"""
if not (params['widths'].size() == params['heights'].size() == params['xs'].size() == params['ys'].size()):
raise TypeError(
@@ -607,9 +660,10 @@ def apply_adjust_brightness(input: torch.Tensor, params: Dict[str, torch.Tensor]
Args:
input (torch.Tensor): Image/Input to be adjusted in the shape of (*, N).
- brightness_factor (Union[float, torch.Tensor]): Brightness adjust factor per element
- in the batch. 0 gives a black image, 1 does not modify the input image and 2 gives a
- white image, while any other number modify the brightness.
+ params (Dict[str, torch.Tensor]):
+ - params['brightness_factor']: Brightness adjust factor per element
+ in the batch. 0 gives a black image, 1 does not modify the input image and 2 gives a
+ white image, while any other number modify the brightness.
Returns:
torch.Tensor: Adjusted image.
@@ -624,13 +678,13 @@ def apply_adjust_brightness(input: torch.Tensor, params: Dict[str, torch.Tensor]
def apply_adjust_contrast(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
"""Wrapper for adjust_contrast for Torchvision-like param settings.
+
Args:
input (torch.Tensor): Image to be adjusted in the shape of (*, N).
- params['contrast_factor'] (Union[float, torch.Tensor]):
- Contrast adjust factor per element in the batch.
- 0 generates a compleatly black image, 1 does not modify
- the input image while any other non-negative number modify the
- brightness by this factor.
+ params (Dict[str, torch.Tensor]):
+ - params['contrast_factor']: Contrast adjust factor per element in the batch.
+ 0 generates a compleatly black image, 1 does not modify the input image while any other
+ non-negative number modify the brightness by this factor.
Returns:
torch.Tensor: Adjusted image.
@@ -648,9 +702,10 @@ def apply_adjust_saturation(input: torch.Tensor, params: Dict[str, torch.Tensor]
Args:
input (torch.Tensor): Image/Tensor to be adjusted in the shape of (*, N).
- saturation_factor (float): How much to adjust the saturation. 0 will give a black
- and white image, 1 will give the original image while 2 will enhance the saturation
- by a factor of 2.
+ params (Dict[str, torch.Tensor]):
+ - params['saturation_factor']: How much to adjust the saturation. 0 will give a black
+ and white image, 1 will give the original image while 2 will enhance the saturation
+ by a factor of 2.
Returns:
torch.Tensor: Adjusted image.
@@ -668,10 +723,11 @@ def apply_adjust_hue(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> to
Args:
input (torch.Tensor): Image/Tensor to be adjusted in the shape of (*, N).
- hue_factor (float): How much to shift the hue channel. Should be in [-0.5, 0.5]. 0.5
- and -0.5 give complete reversal of hue channel in HSV space in positive and negative
- direction respectively. 0 means no shift. Therefore, both -PI and PI will give an
- image with complementary colors while 0 gives the original image.
+ params (Dict[str, torch.Tensor]):
+ - params['hue_factor']: How much to shift the hue channel. Should be in [-0.5, 0.5].
+ 0.5 and -0.5 give complete reversal of hue channel in HSV space in positive and negative
+ direction respectively. 0 means no shift. Therefore, both -0.5 and 0.5 will give an
+ image with complementary colors while 0 gives the original image.
Returns:
torch.Tensor: Adjusted image.
@@ -687,14 +743,12 @@ def apply_adjust_hue(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> to
def apply_adjust_gamma(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Perform gamma correction on an image.
- The input image is expected to be in the range of [0, 1].
-
Args:
input (torch.Tensor): Image/Tensor to be adjusted in the shape of (\*, N).
- gamma (float): Non negative real number, same as γ\gammaγ in the equation.
- gamma larger than 1 make the shadows darker, while gamma smaller than 1 make
- dark regions lighter.
- gain (float, optional): The constant multiplier. Default 1.
+ params (Dict[str, torch.Tensor]):
+ - params['gamma_factor']: Non negative real number, same as γ\gammaγ in the equation.
+ gamma larger than 1 make the shadows darker, while gamma smaller than 1 make
+ dark regions lighter.
Returns:
torch.Tensor: Adjusted image.
diff --git a/kornia/augmentation/random_generator.py b/kornia/augmentation/random_generator.py
index 4907c8be9..009843809 100644
--- a/kornia/augmentation/random_generator.py
+++ b/kornia/augmentation/random_generator.py
@@ -10,7 +10,6 @@ from kornia.augmentation.utils import (
_check_and_bound
)
-# TODO: remove this since it does not help readability
from .types import (
TupleFloat,
UnionFloat,
@@ -38,9 +37,7 @@ def random_color_jitter_generator(
same_on_batch (bool): apply the same transformation across the batch. Default: False
Returns:
- dict: generated parameter dictionary.
-
- See :class:`~kornia.augmentation.ColorJitter` for details.
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
brightness_bound: torch.Tensor = _check_and_bound(
@@ -79,15 +76,11 @@ def random_prob_generator(
Args:
batch_size (int): the number of images.
- p (float): probability of the image being flipped or grayscaled. Default value is 0.5.
- same_on_batch (bool): apply the same transformation across the batch. Default: False.
+ p (float): probability of the image being flipped or grayscaled. Default value is 0.5
+ same_on_batch (bool): apply the same transformation across the batch. Default: False
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.
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
if not isinstance(p, float):
@@ -157,9 +150,7 @@ def random_perspective_generator(
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.
+ params (Dict[str, torch.Tensor])
"""
params: Dict[str, torch.Tensor] = random_prob_generator(batch_size, p)
start_points, end_points = (
@@ -186,30 +177,32 @@ def random_affine_generator(
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``affine`` for a random affine transform.
- Args:
- batch_size (int): the tensor batch size.
- height (int) : height of the image.
- width (int): width of the image.
- 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
- resample (int, str or kornia.Resample): Default: Resample.BILINEAR
- same_on_batch (bool): apply the same transformation across the batch. Default: False
- align_corners(bool): interpolation flag. Default: False. See
+ Args:
+ batch_size (int): the tensor batch size.
+ height (int) : height of the image.
+ width (int): width of the image.
+ 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
+ resample (int, str or kornia.Resample): Default: Resample.BILINEAR
+ same_on_batch (bool): apply the same transformation across the batch. Default: False
+ align_corners(bool): interpolation flag. Default: False.See
https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
# check angle ranges
degrees_tmp: TupleFloat
@@ -272,6 +265,9 @@ def random_rotation_generator(
interpolation (int, str or kornia.Resample): Default: Resample.BILINEAR
same_on_batch (bool): apply the same transformation across the batch. Default: False
align_corners (bool): interpolation flag. Default: False.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
if not torch.is_tensor(degrees):
if isinstance(degrees, (float, int)):
@@ -314,7 +310,7 @@ def _get_random_affine_params(
The returned matrix is Bx3x3.
Returns:
- torch.Tensor: params to be passed to the affine transformation.
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
angle = _adapted_uniform((batch_size,), degrees[0], degrees[1], same_on_batch)
@@ -364,6 +360,7 @@ def random_crop_generator(
align_corners: bool = False
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```crop``` transformation for crop transform.
+
Args:
batch_size (int): the tensor batch size.
input_size (tuple): Input image shape, like (h, w).
@@ -372,6 +369,9 @@ def random_crop_generator(
interpolation (int, str or kornia.Resample): Default: Resample.BILINEAR
same_on_batch (bool): apply the same transformation across the batch. Default: False
align_corners (bool): interpolation flag. Default: False.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
x_diff = input_size[1] - size[1]
y_diff = input_size[0] - size[0]
@@ -419,10 +419,13 @@ def random_crop_size_generator(
r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
Args:
- size (Tuple[int, int]): expected output size of each edge.
- scale: range of size of the origin size cropped.
- ratio: range of aspect ratio of the origin aspect ratio cropped.
- same_on_batch (bool): apply the same transformation across the batch. Default: False.
+ size (Tuple[int, int]): expected output size of each edge
+ scale: range of size of the origin size cropped
+ ratio: range of aspect ratio of the origin aspect ratio cropped
+ same_on_batch (bool): apply the same transformation across the batch. Default: False
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
area = _adapted_uniform(
(10,), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)
@@ -464,16 +467,28 @@ def random_rectangles_params_generator(
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```erasing``` transformation for erasing transform
- Args:
- batch_size (int): the tensor batch size.
- height (int) : height of the image.
- width (int): width of the image.
- p (float): probability of applying random earaing.
- scale ([int, int]): range of size of the origin size cropped.
- ratio ([int, int]): range of aspect ratio of the origin aspect ratio cropped.
- value (float): value to be filled in the erased area.
- same_on_batch (bool): apply the same transformation across the batch. Default: False.
+ Args:
+ batch_size (int): the tensor batch size.
+ height (int) : height of the image.
+ width (int): width of the image.
+ p (float): probability of applying random earaing.
+ scale ([int, int]): range of size of the origin size cropped
+ ratio ([int, int]): range of aspect ratio of the origin aspect ratio cropped
+ value (float): value to be filled in the erased area.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
+ if not (isinstance(scale[0], float) and isinstance(scale[1], float) and scale[0] > 0. and scale[1] > 0.):
+ raise TypeError(
+ f"'erase_scale_range' must be a Tuple[float, float] with positive values"
+ )
+ if not (isinstance(ratio[0], float) and isinstance(ratio[1], float) and ratio[0] > 0. and ratio[1] > 0.):
+ raise TypeError(
+ f"'ratio' must be a Tuple[float, float] with positive values"
+ )
+
batch_prob = random_prob_generator(batch_size, p, same_on_batch)['batch_prob']
zeros = torch.zeros((batch_size,))
images_area = height * width
@@ -520,12 +535,15 @@ def center_crop_params_generator(
align_corners: bool = False
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop``` transformation for center crop transform.
- Args:
- batch_size (int): the tensor batch size.
- height (int) : height of the image.
- width (int): width of the image.
- size (tuple): Desired output size of the crop, like (h, w).
- align_corners (bool): interpolation flag. Default: False.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ height (int) : height of the image.
+ width (int): width of the image.
+ size (tuple): Desired output size of the crop, like (h, w).
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
if not isinstance(size, (tuple, list,)) and len(size) == 2:
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 633a0830c..d845e0723 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -1092,7 +1092,7 @@ class TestRandomRotation:
assert str(f) == repr
def test_random_rotation(self, device):
-
+ # This is included in doctest
torch.manual_seed(0) # for random reproductibility
f = RandomRotation(degrees=45.0, return_transform=True)
@@ -1412,6 +1412,7 @@ class TestRandomResizedCrop:
assert (res[0] == res[1]).all()
def test_crop_scale_ratio(self, device):
+ # This is included in doctest
torch.manual_seed(0)
inp = torch.tensor([[
[0., 1., 2.],