Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] Added keepdim flag to augmentation functions. (#731)

Duc Nguyen665c19f373b0
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 097896b4e..bf7afe7f3 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -17,8 +17,10 @@ from .utils import (
class AugmentationBase(AugmentationBase2D):
__doc__ = AugmentationBase2D.__doc__
- def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5) -> None:
- super(AugmentationBase2D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5,
+ keepdim: bool = False) -> None:
+ super(AugmentationBase2D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
raise DeprecationWarning(
"`AugmentationBase` is deprecated. Please use `kornia.augmentation.AugmentationBase2D instead.`")
@@ -39,6 +41,8 @@ class RandomHorizontalFlip(AugmentationBase2D):
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -86,6 +90,8 @@ class RandomVerticalFlip(AugmentationBase2D):
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -137,6 +143,8 @@ class ColorJitter(AugmentationBase2D):
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -170,9 +178,11 @@ class ColorJitter(AugmentationBase2D):
contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
- return_transform: bool = False, same_on_batch: bool = False, p: float = 1.
+ return_transform: bool = False, same_on_batch: bool = False, p: float = 1.,
+ keepdim: bool = False
) -> None:
- super(ColorJitter, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(ColorJitter, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
self.brightness: torch.Tensor = _range_bound(brightness, 'brightness', center=1., bounds=(0, 2))
self.contrast: torch.Tensor = _range_bound(contrast, 'contrast', center=1.)
self.saturation: torch.Tensor = _range_bound(saturation, 'saturation', center=1.)
@@ -202,6 +212,8 @@ class RandomGrayscale(AugmentationBase2D):
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -230,8 +242,10 @@ class RandomGrayscale(AugmentationBase2D):
[-0.1717, -0.9023, 0.0819]]]])
"""
- def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.1) -> None:
- super(RandomGrayscale, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.1,
+ keepdim: bool = False) -> None:
+ super(RandomGrayscale, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
@@ -261,6 +275,8 @@ class RandomErasing(AugmentationBase2D):
scale (Tuple[float, float]): range of proportion of erased area against input image.
ratio (Tuple[float, float]): range of aspect ratio of erased area.
same_on_batch (bool): apply the same transformation across the batch. Default: False
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -285,9 +301,11 @@ class RandomErasing(AugmentationBase2D):
def __init__(
self, scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
- value: float = 0., return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5
+ value: float = 0., return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomErasing, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomErasing, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
self.scale = cast(torch.Tensor, scale) if isinstance(scale, torch.Tensor) else torch.tensor(scale)
self.ratio = cast(torch.Tensor, ratio) if isinstance(ratio, torch.Tensor) else torch.tensor(ratio)
self.value: float = value
@@ -319,6 +337,8 @@ class RandomPerspective(AugmentationBase2D):
applied to each. Default: False.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
align_corners(bool): interpolation flag. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -346,9 +366,10 @@ class RandomPerspective(AugmentationBase2D):
interpolation: Optional[Union[str, int, Resample]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
return_transform: bool = False, same_on_batch: bool = False,
- align_corners: bool = False, p: float = 0.5
+ align_corners: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
- super(RandomPerspective, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomPerspective, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
self.distortion_scale = cast(torch.Tensor, distortion_scale) \
if isinstance(distortion_scale, torch.Tensor) else torch.tensor(distortion_scale)
self.resample: Resample
@@ -410,6 +431,8 @@ class RandomAffine(AugmentationBase2D):
applied to each. Default: False.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
align_corners(bool): interpolation flag. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -439,9 +462,10 @@ class RandomAffine(AugmentationBase2D):
shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False,
- padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name, p: float = 0.5
+ padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name, p: float = 0.5, keepdim: bool = False
) -> None:
- super(RandomAffine, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomAffine, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
degrees = cast(torch.Tensor, degrees) if isinstance(degrees, torch.Tensor) else torch.tensor(degrees)
self.degrees = _range_bound(degrees, 'degrees', 0, (-360, 360))
self.translate: Optional[torch.Tensor] = None
@@ -503,6 +527,8 @@ class CenterCrop(AugmentationBase2D):
If Tuple[int, int], out_h = size[0], out_w = size[1].
return_transform (bool): if ``True`` return the matrix describing the transformation
applied to each. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -524,11 +550,11 @@ class CenterCrop(AugmentationBase2D):
def __init__(self, size: Union[int, Tuple[int, int]], align_corners: bool = True,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, p: float = 1.) -> None:
+ return_transform: bool = False, p: float = 1., keepdim: bool = False) -> None:
# same_on_batch is always True for CenterCrop
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
- super(CenterCrop, self).__init__(
- p=1., return_transform=return_transform, same_on_batch=True, p_batch=p)
+ super(CenterCrop, self).__init__(p=1., return_transform=return_transform, same_on_batch=True, p_batch=p,
+ keepdim=keepdim)
self.size = size
self.resample = Resample.get(resample)
self.align_corners = align_corners
@@ -572,6 +598,8 @@ class RandomRotation(AugmentationBase2D):
wont be concatenated.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
align_corners(bool): interpolation flag. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -603,9 +631,11 @@ class RandomRotation(AugmentationBase2D):
self, degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],
interpolation: Optional[Union[str, int, Resample]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = True, p: float = 0.5
+ return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = True, p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomRotation, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomRotation, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
degrees = cast(torch.Tensor, degrees) if isinstance(degrees, torch.Tensor) else torch.tensor(degrees)
self.degrees = _range_bound(degrees, 'degrees', 0, (-360, 360))
self.resample: Resample
@@ -659,6 +689,8 @@ class RandomCrop(AugmentationBase2D):
wont be concatenated
same_on_batch (bool): apply the same transformation across the batch. Default: False
align_corners(bool): interpolation flag. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -682,11 +714,12 @@ class RandomCrop(AugmentationBase2D):
self, size: Tuple[int, int], padding: Optional[Union[int, Tuple[int, int], Tuple[int, int, int, int]]] = None,
pad_if_needed: Optional[bool] = False, fill: int = 0, padding_mode: str = 'constant',
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False, p: float = 1.0
+ return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False, p: float = 1.0,
+ keepdim: bool = False
) -> None:
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
super(RandomCrop, self).__init__(
- p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p)
+ p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self.size = size
self.padding = padding
self.pad_if_needed = pad_if_needed
@@ -763,6 +796,8 @@ class RandomResizedCrop(AugmentationBase2D):
wont be concatenated.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
align_corners(bool): interpolation flag. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -791,11 +826,11 @@ class RandomResizedCrop(AugmentationBase2D):
interpolation: Optional[Union[str, int, Resample]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
return_transform: bool = False, same_on_batch: bool = False,
- align_corners: bool = False, p: float = 1.
+ align_corners: bool = False, p: float = 1., keepdim: bool = False
) -> None:
# Since PyTorch does not support ragged tensor. So cropping function happens all the time.
super(RandomResizedCrop, self).__init__(
- p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p)
+ p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self.size = size
self.scale = cast(torch.Tensor, scale) if isinstance(scale, torch.Tensor) else torch.tensor(scale)
self.ratio = cast(torch.Tensor, ratio) if isinstance(ratio, torch.Tensor) else torch.tensor(ratio)
@@ -846,6 +881,8 @@ class RandomMotionBlur(AugmentationBase2D):
If Tuple[int, int], it will randomly generate the value from the range.
border_type (int, str or kornia.BorderType): the padding mode to be applied before convolving.
CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -873,9 +910,10 @@ class RandomMotionBlur(AugmentationBase2D):
angle: Union[torch.Tensor, float, Tuple[float, float]],
direction: Union[torch.Tensor, float, Tuple[float, float]],
border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
- return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5
+ return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
- super(RandomMotionBlur, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomMotionBlur, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
self.kernel_size: Union[int, Tuple[int, int]] = kernel_size
angle = cast(torch.Tensor, angle) if isinstance(angle, torch.Tensor) else torch.tensor(angle)
@@ -919,6 +957,8 @@ class RandomSolarize(AugmentationBase2D):
same_on_batch (bool): apply the same transformation across the batch. Default: False.
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -944,7 +984,7 @@ class RandomSolarize(AugmentationBase2D):
def __init__(
self, thresholds: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
additions: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
- same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5
+ same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
super(RandomSolarize, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
@@ -982,6 +1022,8 @@ class RandomPosterize(AugmentationBase2D):
same_on_batch (bool): apply the same transformation across the batch. Default: False.
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -1006,9 +1048,10 @@ class RandomPosterize(AugmentationBase2D):
def __init__(
self, bits: Union[int, Tuple[int, int], torch.Tensor] = 3,
- same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5
+ same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
- super(RandomPosterize, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomPosterize, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
bits = cast(torch.Tensor, bits) if isinstance(bits, torch.Tensor) else torch.tensor(bits)
if len(bits.size()) == 0:
self.bits = torch.tensor([bits, torch.tensor(8)], dtype=torch.float32)
@@ -1040,6 +1083,8 @@ class RandomSharpness(AugmentationBase2D):
same_on_batch (bool): apply the same transformation across the batch. Default: False.
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -1076,9 +1121,10 @@ class RandomSharpness(AugmentationBase2D):
def __init__(
self, sharpness: Union[torch.Tensor, float, Tuple[float, float], torch.Tensor] = 0.5,
- same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5
+ same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
- super(RandomSharpness, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomSharpness, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
sharpness = cast(torch.Tensor, sharpness) if isinstance(sharpness, torch.Tensor) else torch.tensor(sharpness)
if sharpness.dim() == 0:
self.sharpness = torch.tensor([0, sharpness], dtype=torch.float32)
@@ -1105,11 +1151,13 @@ class RandomEqualize(AugmentationBase2D):
r"""Equalize given tensor image or a batch of tensor images randomly.
Args:
- p (float): Probability to equalize an image. Default value is 0.5
- same_on_batch (bool): apply the same transformation across the batch. Default: False
+ p (float): Probability to equalize an image. Default value is 0.5.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False.
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
+ wont be concatenated.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -1133,9 +1181,10 @@ class RandomEqualize(AugmentationBase2D):
"""
def __init__(
- self, same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5
+ self, same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
- super(RandomEqualize, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomEqualize, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index d49f8e39e..0673b14a0 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -23,6 +23,8 @@ class RandomHorizontalFlip3D(AugmentationBase3D):
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
@@ -53,9 +55,10 @@ class RandomHorizontalFlip3D(AugmentationBase3D):
[ 0., 0., 0., 1.]]]))
"""
- def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5) -> None:
+ def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5,
+ keepdim: bool = False) -> None:
super(RandomHorizontalFlip3D, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
@@ -85,6 +88,8 @@ class RandomVerticalFlip3D(AugmentationBase3D):
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
@@ -115,9 +120,10 @@ class RandomVerticalFlip3D(AugmentationBase3D):
[ 0., 0., 0., 1.]]]))
"""
- def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5) -> None:
+ def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5,
+ keepdim: bool = False) -> None:
super(RandomVerticalFlip3D, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
@@ -147,6 +153,8 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
@@ -178,9 +186,10 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
"""
- def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5) -> None:
+ def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5,
+ keepdim: bool = False) -> None:
super(RandomDepthicalFlip3D, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
@@ -231,6 +240,8 @@ class RandomAffine3D(AugmentationBase3D):
applied to each. Default: False.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
align_corners(bool): interpolation flag. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
@@ -272,9 +283,11 @@ class RandomAffine3D(AugmentationBase3D):
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float],
Tuple[float, float], Tuple[float, float]]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False, p: float = 0.5
+ return_transform: bool = False, same_on_batch: bool = False,
+ align_corners: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
- super(RandomAffine3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomAffine3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
self.degrees = _tuple_range_reader(degrees, 3)
self.shear: Optional[torch.Tensor] = None
if shears is not None:
@@ -347,6 +360,8 @@ class RandomRotation3D(AugmentationBase3D):
wont be concatenated.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
align_corners(bool): interpolation flag. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
@@ -383,9 +398,11 @@ class RandomRotation3D(AugmentationBase3D):
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],
interpolation: Optional[Union[str, int, Resample]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False, p: float = 0.5
+ return_transform: bool = False, same_on_batch: bool = False,
+ align_corners: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
- super(RandomRotation3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomRotation3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
self.degrees = _tuple_range_reader(degrees, 3)
if interpolation is not None:
import warnings
@@ -437,6 +454,8 @@ class RandomMotionBlur3D(AugmentationBase3D):
If Tuple[int, int], it will randomly generate the value from the range.
border_type (int, str or kornia.BorderType): the padding mode to be applied before convolving.
CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
@@ -477,10 +496,10 @@ class RandomMotionBlur3D(AugmentationBase3D):
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],
direction: Union[torch.Tensor, float, Tuple[float, float]],
border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
- return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5
+ return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
super(RandomMotionBlur3D, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1., keepdim=keepdim)
self.kernel_size: Union[int, Tuple[int, int]] = kernel_size
self.angle: torch.Tensor = _tuple_range_reader(angle, 3)
@@ -522,6 +541,8 @@ class CenterCrop3D(AugmentationBase3D):
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated.
align_corners(bool): interpolation flag. Default: True.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
@@ -546,11 +567,11 @@ class CenterCrop3D(AugmentationBase3D):
def __init__(self, size: Union[int, Tuple[int, int, int]], align_corners: bool = True,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, p: float = 1.) -> None:
+ return_transform: bool = False, p: float = 1., keepdim: bool = False) -> None:
# same_on_batch is always True for CenterCrop
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
super(CenterCrop3D, self).__init__(
- p=1., return_transform=return_transform, same_on_batch=True, p_batch=p)
+ p=1., return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
self.size = size
self.resample = Resample.get(resample)
self.align_corners = align_corners
@@ -607,6 +628,8 @@ class RandomCrop3D(AugmentationBase3D):
wont be concatenated
same_on_batch (bool): apply the same transformation across the batch. Default: False.
align_corners(bool): interpolation flag. Default: True.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
@@ -634,11 +657,12 @@ class RandomCrop3D(AugmentationBase3D):
padding: Optional[Union[int, Tuple[int, int, int], Tuple[int, int, int, int, int, int]]] = None,
pad_if_needed: Optional[bool] = False, fill: int = 0, padding_mode: str = 'constant',
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = True, p: float = 1.0
+ return_transform: bool = False, same_on_batch: bool = False,
+ align_corners: bool = True, p: float = 1.0, keepdim: bool = False
) -> None:
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
super(RandomCrop3D, self).__init__(
- p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p)
+ p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self.size = size
self.padding = padding
self.pad_if_needed = pad_if_needed
@@ -722,6 +746,8 @@ class RandomPerspective3D(AugmentationBase3D):
applied to each. Default: False.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
align_corners(bool): interpolation flag. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
@@ -764,9 +790,10 @@ class RandomPerspective3D(AugmentationBase3D):
self, distortion_scale: Union[torch.Tensor, float] = 0.5,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
return_transform: bool = False, same_on_batch: bool = False,
- align_corners: bool = False, p: float = 0.5
+ align_corners: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
- super(RandomPerspective3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ super(RandomPerspective3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
self.distortion_scale = cast(torch.Tensor, distortion_scale) \
if isinstance(distortion_scale, torch.Tensor) else torch.tensor(distortion_scale)
self.resample = Resample.get(resample)
@@ -803,6 +830,8 @@ class RandomEqualize3D(AugmentationBase3D):
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
Shape:
- Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
@@ -831,8 +860,10 @@ class RandomEqualize3D(AugmentationBase3D):
[0.4194, 0.5529, 0.9527]]]]])
"""
- def __init__(self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False) -> None:
- super(RandomEqualize3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ def __init__(self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False,
+ keepdim: bool = False) -> None:
+ super(RandomEqualize3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
+ keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index a81daa288..787238b73 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -7,12 +7,10 @@ import torch.nn as nn
from torch.distributions import Bernoulli
from . import functional as F
-from . import random_generator as rg
from .utils import (
- _infer_batch_shape,
- _infer_batch_shape3d,
_transform_input,
_transform_input3d,
+ _transform_output_shape,
_validate_input_dtype,
_adapted_sampling
)
@@ -29,13 +27,18 @@ class _BasicAugmentationBase(nn.Module):
p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
"""
- def __init__(self, p: float = 0.5, p_batch: float = 1., same_on_batch: bool = False) -> None:
+ def __init__(self, p: float = 0.5, p_batch: float = 1., same_on_batch: bool = False,
+ keepdim: bool = False) -> None:
super(_BasicAugmentationBase, self).__init__()
self.p = p
self.p_batch = p_batch
self.same_on_batch = same_on_batch
+ self.keepdim = keepdim
+ self._params = None # type: Union[None,Dict[str, torch.Tensor]]
if p != 0. or p != 1.:
self._p_gen = Bernoulli(self.p)
if p_batch != 0. or p_batch != 1.:
@@ -44,11 +47,15 @@ class _BasicAugmentationBase(nn.Module):
def __repr__(self) -> str:
return f"p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}"
- def __infer_input__(
+ def __unpack_input__(
self, input: torch.Tensor
) -> torch.Tensor:
- in_tensor = self.transform_tensor(input)
- return in_tensor
+ return input
+
+ def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):
+ """Check if a transformation matrix is returned,
+ it has to be in the same batching mode as output."""
+ raise NotImplementedError
def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
"""Standardize input tensors."""
@@ -100,13 +107,17 @@ class _BasicAugmentationBase(nn.Module):
def forward(self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None, # type: ignore
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignore
- in_tensor = self.__infer_input__(input)
+ in_tensor = self.__unpack_input__(input)
+ self.__check_batching__(input)
+ ori_shape = in_tensor.shape
+ in_tensor = self.transform_tensor(in_tensor)
batch_shape = in_tensor.shape
if params is None:
params = self.__forward_parameters__(batch_shape, self.p, self.p_batch, self.same_on_batch)
self._params = params
- return self.apply_func(input, self._params)
+ output = self.apply_func(input, self._params)
+ return _transform_output_shape(output, ori_shape) if self.keepdim else output
class _AugmentationBase(_BasicAugmentationBase):
@@ -123,11 +134,13 @@ class _AugmentationBase(_BasicAugmentationBase):
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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
"""
def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5,
- p_batch: float = 1.) -> None:
- super(_AugmentationBase, self).__init__(p, p_batch=p_batch, same_on_batch=same_on_batch)
+ p_batch: float = 1., keepdim: bool = False) -> None:
+ super(_AugmentationBase, self).__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
self.p = p
self.p_batch = p_batch
self.return_transform = return_transform
@@ -141,15 +154,15 @@ class _AugmentationBase(_BasicAugmentationBase):
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
raise NotImplementedError
- def __infer_input__( # type: ignore
+ def __unpack_input__( # type: ignore
self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
if isinstance(input, tuple):
- in_tensor = self.transform_tensor(input[0])
+ in_tensor = input[0]
in_transformation = input[1]
- return (in_tensor, in_transformation)
+ return in_tensor, in_transformation
else:
- in_tensor = self.transform_tensor(input)
+ in_tensor = input
return in_tensor, None
def apply_func(self, in_tensor: torch.Tensor, in_transform: Optional[torch.Tensor], # type: ignore
@@ -188,10 +201,14 @@ class _AugmentationBase(_BasicAugmentationBase):
def forward(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
params: Optional[Dict[str, torch.Tensor]] = None, # type: ignore
- return_transform: Optional[bool] = None
+ return_transform: Optional[bool] = None,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignore
- in_tensor, in_transform = self.__infer_input__(input)
+ in_tensor, in_transform = self.__unpack_input__(input)
+ self.__check_batching__(input)
+ ori_shape = in_tensor.shape
+ in_tensor = self.transform_tensor(in_tensor)
batch_shape = in_tensor.shape
+
if return_transform is None:
return_transform = self.return_transform
if params is None:
@@ -201,7 +218,8 @@ class _AugmentationBase(_BasicAugmentationBase):
warnings.warn("`batch_prob` is not found in params. Will assume applying on all data.")
self._params = params
- return self.apply_func(in_tensor, in_transform, self._params, return_transform)
+ output = self.apply_func(in_tensor, in_transform, self._params, return_transform)
+ return _transform_output_shape(output, ori_shape) if self.keepdim else output
class AugmentationBase2D(_AugmentationBase):
@@ -219,8 +237,25 @@ class AugmentationBase2D(_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.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
"""
+ def __check_batching__(self, input: Union[torch.Tensor,
+ Tuple[torch.Tensor, torch.Tensor]]):
+ if isinstance(input, tuple):
+ inp, mat = input
+ if len(inp.shape) == 4:
+ assert len(mat.shape) == 3, 'Input tensor is in batch mode ' \
+ 'but transformation matrix is not'
+ assert mat.shape[0] == inp.shape[0], f'In batch dimension, input has {inp.shape[0]}' \
+ f'but transformation matrix has {mat.shape[0]}'
+ elif len(inp.shape) == 3 or len(inp.shape) == 2:
+ assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' \
+ 'but transformation matrix is not'
+ else:
+ raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
+
def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
@@ -245,9 +280,24 @@ class AugmentationBase3D(_AugmentationBase):
return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each
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
+ same_on_batch (bool): apply the same transformation across the batch. Default: False.
"""
+ def __check_batching__(self, input: Union[torch.Tensor,
+ Tuple[torch.Tensor, torch.Tensor]]):
+ if isinstance(input, tuple):
+ inp, mat = input
+ if len(inp.shape) == 5:
+ assert len(mat.shape) == 3, 'Input tensor is in batch mode ' \
+ 'but transformation matrix is not'
+ assert mat.shape[0] == inp.shape[0], f'In batch dimension, input has {inp.shape[0]}' \
+ f'but transformation matrix has {mat.shape[0]}'
+ elif len(inp.shape) == 3 or len(inp.shape) == 4:
+ assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' \
+ 'but transformation matrix is not'
+ else:
+ raise ValueError(f'Unrecognized output shape. Expected 3, 4 or 5, got {len(inp.shape)}')
+
def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
"""Convert any incoming (D, H, W), (C, D, H, W) and (B, C, D, H, W) into (B, C, D, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
@@ -270,10 +320,27 @@ class MixAugmentationBase(_BasicAugmentationBase):
p_batch (float): probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
"""
- def __init__(self, p: float, p_batch: float, same_on_batch: bool = False) -> None:
- super(MixAugmentationBase, self).__init__(p, p_batch=p_batch, same_on_batch=same_on_batch)
+ def __init__(self, p: float, p_batch: float, same_on_batch: bool = False, keepdim: bool = False) -> None:
+ super(MixAugmentationBase, self).__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
+
+ def __check_batching__(self, input: Union[torch.Tensor,
+ Tuple[torch.Tensor, torch.Tensor]]):
+ if isinstance(input, tuple):
+ inp, mat = input
+ if len(inp.shape) == 4:
+ assert len(mat.shape) == 3, 'Input tensor is in batch mode ' \
+ 'but transformation matrix is not'
+ assert mat.shape[0] == inp.shape[0], f'In batch dimension, input has {inp.shape[0]}' \
+ f'but transformation matrix has {mat.shape[0]}'
+ elif len(inp.shape) == 3 or len(inp.shape) == 2:
+ assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' \
+ 'but transformation matrix is not'
+ else:
+ raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
@@ -303,10 +370,13 @@ class MixAugmentationBase(_BasicAugmentationBase):
def forward(self, input: torch.Tensor, label: torch.Tensor, # type: ignore
params: Optional[Dict[str, torch.Tensor]] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
- in_tensor = self.__infer_input__(input)
+ in_tensor = self.__unpack_input__(input)
+ ori_shape = in_tensor.shape
+ in_tensor = self.transform_tensor(in_tensor)
if params is None:
batch_shape = in_tensor.shape
params = self.__forward_parameters__(batch_shape, self.p, self.p_batch, self.same_on_batch)
self._params = params
- return self.apply_func(in_tensor, label, self._params)
+ output = self.apply_func(in_tensor, label, self._params)
+ return _transform_output_shape(output, ori_shape) if self.keepdim else output # type: ignore
diff --git a/kornia/augmentation/functional/functional.py b/kornia/augmentation/functional/functional.py
index acc9e3b40..ccaced34f 100644
--- a/kornia/augmentation/functional/functional.py
+++ b/kornia/augmentation/functional/functional.py
@@ -2,12 +2,10 @@ from typing import Tuple, List, Union, Dict, cast, Optional
import kornia as K
import torch
-import torch.nn as nn
from kornia.constants import Resample, BorderType, SamplePadding, pi
from kornia.geometry import (
get_perspective_transform,
- get_rotation_matrix2d,
get_affine_matrix2d,
warp_perspective,
rotate,
@@ -36,16 +34,17 @@ from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute
from .. import random_generator as rg
from ..utils import (
- _transform_input,
_validate_input_shape,
_validate_input_dtype,
_range_bound,
- _shape_validation
+ _shape_validation,
+ _validate_input
)
from .__temp__ import __deprecation_warning
+@_validate_input
def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
r"""Generate params and apply operation on input tensor.
@@ -53,7 +52,6 @@ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = F
See :func:`~kornia.augmentation.functional.apply_hflip` for details.
"""
__deprecation_warning("random_hflip", "kornia.augmentation.RandomHorizontalFlip")
- input = _transform_input(input)
batch_size, _, h, w = input.size()
output = input.clone()
to_apply = rg.random_prob_generator(batch_size, p=p)
@@ -65,6 +63,7 @@ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = F
return output
+@_validate_input
def random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
r"""Generate params and apply operation on input tensor.
@@ -72,7 +71,6 @@ def random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = F
See :func:`~kornia.augmentation.functional.apply_vflip` for details.
"""
__deprecation_warning("random_vflip", "kornia.augmentation.RandomVerticalFlip")
- input = _transform_input(input)
batch_size, _, h, w = input.size()
output = input.clone()
to_apply = rg.random_prob_generator(batch_size, p=p)
@@ -84,6 +82,7 @@ def random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = F
return output
+@_validate_input
def color_jitter(input: torch.Tensor, brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
@@ -95,7 +94,6 @@ def color_jitter(input: torch.Tensor, brightness: Union[torch.Tensor, float, Tup
See :func:`~kornia.augmentation.functional.apply_color_jitter` for details.
"""
__deprecation_warning("color_jitter", "kornia.augmentation.ColorJitter")
- input = _transform_input(input)
batch_size, _, h, w = input.size()
_brightness: torch.Tensor = _range_bound(brightness, 'brightness', center=1., bounds=(0, 2))
_contrast: torch.Tensor = _range_bound(contrast, 'contrast', center=1.)
@@ -108,13 +106,13 @@ def color_jitter(input: torch.Tensor, brightness: Union[torch.Tensor, float, Tup
return output
+@_validate_input
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.random_generator.random_prob_generator` for details.
See :func:`~kornia.augmentation.functional.apply_grayscale` for details.
"""
__deprecation_warning("random_grayscale", "kornia.augmentation.RandomGrayscale")
- input = _transform_input(input)
batch_size, _, h, w = input.size()
output = input.clone()
to_apply = rg.random_prob_generator(batch_size, p=p)
@@ -125,6 +123,7 @@ def random_grayscale(input: torch.Tensor, p: float = 0.5, return_transform: bool
return output
+@_validate_input
def random_perspective(input: torch.Tensor,
distortion_scale: Union[torch.Tensor, float] = 0.5,
p: float = 0.5,
@@ -134,7 +133,6 @@ def random_perspective(input: torch.Tensor,
See :func:`~kornia.augmentation.functional.apply_perspective` for details.
"""
__deprecation_warning("random_perspective", "kornia.augmentation.RandomPerspective")
- input = _transform_input(input)
batch_size, _, height, width = input.size()
output = input.clone()
distortion_scale = \
@@ -152,6 +150,7 @@ def random_perspective(input: torch.Tensor,
return output
+@_validate_input
def random_affine(input: torch.Tensor,
degrees: Union[float, Tuple[float, float]],
translate: Optional[Tuple[float, float]] = None,
@@ -164,7 +163,6 @@ def random_affine(input: torch.Tensor,
See :func:`~kornia.augmentation.functional.apply_affine` for details.
"""
__deprecation_warning("random_affine", "kornia.augmentation.RandomAffine")
- input = _transform_input(input)
batch_size, _, height, width = input.size()
_degrees: torch.Tensor = _range_bound(degrees, 'degrees', 0, (-360, 360))
@@ -194,6 +192,7 @@ def random_affine(input: torch.Tensor,
return output
+@_validate_input
def random_rectangle_erase(
input: torch.Tensor,
p: float = 0.5,
@@ -215,7 +214,6 @@ def random_rectangle_erase(
See :func:`~kornia.augmentation.functional.apply_erase_rectangles` for details.
"""
__deprecation_warning("random_rectangle_erase", "kornia.augmentation.RandomRectangleErase")
- input = _transform_input(input)
batch_size, _, h, w = input.size()
_scale: torch.Tensor = scale if isinstance(scale, torch.Tensor) else torch.tensor(scale)
_ratio: torch.Tensor = ratio if isinstance(ratio, torch.Tensor) else torch.tensor(ratio)
@@ -231,6 +229,7 @@ def random_rectangle_erase(
return output
+@_validate_input
def random_rotation(input: torch.Tensor, degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],
return_transform: bool = False) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
r"""Generate params and apply operation on input tensor.
@@ -238,7 +237,6 @@ def random_rotation(input: torch.Tensor, degrees: Union[torch.Tensor, float, Tup
See :func:`~kornia.augmentation.functional.apply_rotation` for details.
"""
__deprecation_warning("random_rotation", "kornia.augmentation.RandomRotation")
- input = _transform_input(input)
batch_size, _, _, _ = input.size()
_degrees = _range_bound(degrees, 'degrees', 0, (-360, 360))
params = rg.random_rotation_generator(batch_size, degrees=_degrees)
@@ -249,6 +247,7 @@ def random_rotation(input: torch.Tensor, degrees: Union[torch.Tensor, float, Tup
return output
+@_validate_input
def apply_hflip(input: torch.Tensor) -> torch.Tensor:
r"""Apply Horizontally flip on a tensor image or a batch of tensor images with given random parameters.
@@ -260,12 +259,11 @@ def apply_hflip(input: torch.Tensor) -> torch.Tensor:
Returns:
torch.Tensor: The horizontally flipped input
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
return hflip(input)
+@_validate_input
def compute_hflip_transformation(input: torch.Tensor) -> torch.Tensor:
r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
@@ -275,8 +273,6 @@ def compute_hflip_transformation(input: torch.Tensor) -> torch.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])
w: int = input.shape[-1]
flip_mat: torch.Tensor = torch.tensor([[-1, 0, w - 1],
[0, 1, 0],
@@ -285,6 +281,7 @@ def compute_hflip_transformation(input: torch.Tensor) -> torch.Tensor:
return flip_mat.repeat(input.size(0), 1, 1).type_as(input)
+@_validate_input
def apply_vflip(input: torch.Tensor) -> torch.Tensor:
r"""Apply vertically flip on a tensor image or a batch of tensor images with given random parameters.
@@ -296,12 +293,11 @@ def apply_vflip(input: torch.Tensor) -> torch.Tensor:
Returns:
torch.Tensor: The vertically flipped input
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
return vflip(input)
+@_validate_input
def compute_vflip_transformation(input: torch.Tensor) -> torch.Tensor:
r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
@@ -311,7 +307,6 @@ def compute_vflip_transformation(input: torch.Tensor) -> torch.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])
h: int = input.shape[-2]
@@ -322,6 +317,7 @@ def compute_vflip_transformation(input: torch.Tensor) -> torch.Tensor:
return flip_mat.repeat(input.size(0), 1, 1).type_as(input)
+@_validate_input
def apply_color_jitter(
input: torch.Tensor, params: Dict[str, torch.Tensor]
) -> torch.Tensor:
@@ -344,9 +340,6 @@ def apply_color_jitter(
"""
# TODO: params validation
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
transforms = [
lambda img: apply_adjust_brightness(img, params),
lambda img: apply_adjust_contrast(img, params),
@@ -362,6 +355,7 @@ def apply_color_jitter(
return jittered
+@_validate_input
def compute_intensity_transformation(input: torch.Tensor):
r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
@@ -371,12 +365,11 @@ def compute_intensity_transformation(input: torch.Tensor):
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)
return identity
+@_validate_input
def apply_grayscale(input: torch.Tensor) -> torch.Tensor:
r"""Apply Gray Scale on a tensor image or a batch of tensor images with given random parameters.
@@ -388,9 +381,6 @@ def apply_grayscale(input: torch.Tensor) -> torch.Tensor:
Returns:
torch.Tensor: The grayscaled input
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
if not _validate_input_shape(input, 1, 3):
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {input.shape}")
@@ -402,6 +392,7 @@ def apply_grayscale(input: torch.Tensor) -> torch.Tensor:
return grayscale
+@_validate_input
def apply_perspective(
input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]
) -> torch.Tensor:
@@ -421,9 +412,6 @@ def apply_perspective(
Returns:
torch.Tensor: Perspectively transformed tensor.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
_, _, height, width = input.shape
# compute the homography between the input points
@@ -443,6 +431,7 @@ def apply_perspective(
return out_data.view_as(input)
+@_validate_input
def compute_perspective_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
@@ -457,8 +446,6 @@ def compute_perspective_transformation(input: torch.Tensor, params: Dict[str, to
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])
perspective_transform: torch.Tensor = get_perspective_transform(
params['start_points'], params['end_points']).type_as(input)
@@ -469,6 +456,7 @@ def compute_perspective_transformation(input: torch.Tensor, params: Dict[str, to
return transform
+@_validate_input
def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Random affine transformation of the image keeping center invariant.
@@ -489,12 +477,6 @@ def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Di
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)}")
-
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
# arrange input data
x_data: torch.Tensor = input.view(-1, *input.shape[-3:])
@@ -514,6 +496,7 @@ def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Di
return out_data.view_as(input)
+@_validate_input
def compute_affine_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
@@ -530,8 +513,6 @@ def compute_affine_transformation(input: torch.Tensor, params: Dict[str, torch.T
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(
params['translations'], params['center'], params['scale'], params['angle'],
deg2rad(params['sx']), deg2rad(params['sy'])
@@ -539,6 +520,7 @@ def compute_affine_transformation(input: torch.Tensor, params: Dict[str, torch.T
return transform
+@_validate_input
def apply_rotation(
input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]
) -> torch.Tensor:
@@ -557,8 +539,6 @@ def apply_rotation(
Returns:
torch.Tensor: The cropped input
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
angles: torch.Tensor = params["degrees"].type_as(input)
resample_mode: str = Resample(flags['interpolation'].item()).name.lower()
@@ -569,6 +549,7 @@ def apply_rotation(
return transformed
+@_validate_input
def compute_rotate_tranformation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
@@ -580,8 +561,6 @@ def compute_rotate_tranformation(input: torch.Tensor, params: Dict[str, torch.Te
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)
# TODO: This part should be inferred from rotate directly
@@ -596,6 +575,7 @@ def compute_rotate_tranformation(input: torch.Tensor, params: Dict[str, torch.Te
return trans_mat
+@_validate_input
def apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Apply cropping by src bounding box and dst bounding box.
@@ -613,9 +593,6 @@ def apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict
Returns:
torch.Tensor: The cropped input.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
resample_mode: str = Resample.get(flags['interpolation'].item()).name.lower() # type: ignore
align_corners: bool = cast(bool, flags['align_corners'].item())
@@ -623,6 +600,7 @@ def apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict
input, params['src'], params['dst'], resample_mode, align_corners=align_corners)
+@_validate_input
def compute_crop_transformation(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]):
r"""Compute the applied transformation matrix :math: `(*, 3, 3)`.
@@ -635,13 +613,12 @@ def compute_crop_transformation(input: torch.Tensor, params: Dict[str, torch.Ten
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))
transform = transform.expand(input.shape[0], -1, -1).type_as(input)
return transform
+@_validate_input
def apply_erase_rectangles(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Apply rectangle erase by params.
@@ -666,9 +643,6 @@ def apply_erase_rectangles(input: torch.Tensor, params: Dict[str, torch.Tensor])
f"and ({params['xs'].size()}, {params['ys'].size()})"
)
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
mask = torch.zeros(input.size()).type_as(input)
values = torch.zeros(input.size()).type_as(input)
@@ -689,6 +663,7 @@ def apply_erase_rectangles(input: torch.Tensor, params: Dict[str, torch.Tensor])
return transformed
+@_validate_input
def apply_adjust_brightness(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
"""Apply brightness adjustment.
@@ -704,14 +679,12 @@ def apply_adjust_brightness(input: torch.Tensor, params: Dict[str, torch.Tensor]
Returns:
torch.Tensor: Adjusted image.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
transformed = adjust_brightness(input, params['brightness_factor'].to(input.dtype) - 1)
return transformed
+@_validate_input
def apply_adjust_contrast(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
"""Apply contrast adjustment.
@@ -727,14 +700,12 @@ def apply_adjust_contrast(input: torch.Tensor, params: Dict[str, torch.Tensor])
Returns:
torch.Tensor: Adjusted image.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
transformed = adjust_contrast(input, params['contrast_factor'].to(input.dtype))
return transformed
+@_validate_input
def apply_adjust_saturation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
"""Apply saturation adjustment.
@@ -750,14 +721,12 @@ def apply_adjust_saturation(input: torch.Tensor, params: Dict[str, torch.Tensor]
Returns:
torch.Tensor: Adjusted image.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
transformed = adjust_saturation(input, params['saturation_factor'].to(input.dtype))
return transformed
+@_validate_input
def apply_adjust_hue(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
"""Apply hue adjustment.
@@ -774,14 +743,12 @@ def apply_adjust_hue(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> to
Returns:
torch.Tensor: Adjusted image.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
transformed = adjust_hue(input, params['hue_factor'].to(input.dtype) * 2 * pi)
return transformed
+@_validate_input
def apply_adjust_gamma(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Perform gamma correction on an image.
@@ -795,14 +762,12 @@ def apply_adjust_gamma(input: torch.Tensor, params: Dict[str, torch.Tensor]) ->
Returns:
torch.Tensor: Adjusted image.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
transformed = adjust_gamma(input, params['gamma_factor'].to(input.dtype))
return transformed
+@_validate_input
def apply_motion_blur(input: torch.Tensor, params: Dict[str, torch.Tensor],
flags: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Perform motion blur on an image.
@@ -826,9 +791,6 @@ def apply_motion_blur(input: torch.Tensor, params: Dict[str, torch.Tensor],
torch.Tensor: Adjusted image with the shape as the inpute (\*, C, H, W).
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
kernel_size: int = cast(int, params['ksize_factor'].unique().item())
angle = params['angle_factor']
direction = params['direction_factor']
@@ -837,6 +799,7 @@ def apply_motion_blur(input: torch.Tensor, params: Dict[str, torch.Tensor],
return motion_blur(input, kernel_size, angle, direction, border_type)
+@_validate_input
def apply_solarize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Solarize an image.
@@ -849,9 +812,6 @@ def apply_solarize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torc
Returns:
torch.Tensor: Adjusted image.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
thresholds = params['thresholds_factor']
additions: Optional[torch.Tensor]
if 'additions_factor' in params:
@@ -861,6 +821,7 @@ def apply_solarize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torc
return solarize(input, thresholds, additions)
+@_validate_input
def apply_posterize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Posterize an image.
@@ -872,14 +833,12 @@ def apply_posterize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> tor
Returns:
torch.Tensor: Adjusted image.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
bits = params['bits_factor']
return posterize(input, bits)
+@_validate_input
def apply_sharpness(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Sharpen an image.
@@ -891,14 +850,12 @@ def apply_sharpness(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> tor
Returns:
torch.Tensor: Adjusted image.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
factor = params['sharpness_factor']
return sharpness(input, factor)
+@_validate_input
def apply_equalize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Equalize an image.
@@ -908,12 +865,10 @@ def apply_equalize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torc
Returns:
torch.Tensor: Adjusted image.
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
-
return equalize(input)
+@_validate_input
def apply_mixup(input: torch.Tensor, labels: torch.Tensor,
params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Apply mixup to images in a batch.
@@ -954,8 +909,6 @@ def apply_mixup(input: torch.Tensor, labels: torch.Tensor,
tensor([[0.0000, 1.0000, 0.5000],
[1.0000, 0.0000, 0.9000]])
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
input_permute = input.index_select(dim=0, index=params['mixup_pairs'].to(input.device))
labels_permute = labels.index_select(dim=0, index=params['mixup_pairs'].to(labels.device))
@@ -967,6 +920,7 @@ def apply_mixup(input: torch.Tensor, labels: torch.Tensor,
return inputs, labels
+@_validate_input
def apply_cutmix(input: torch.Tensor, labels: torch.Tensor,
params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Apply cutmix to images in a batch.
@@ -1013,8 +967,6 @@ def apply_cutmix(input: torch.Tensor, labels: torch.Tensor,
[1., 1., 1., 1., 1.]]]]), tensor([[[0.0000, 1.0000, 0.1600],
[1.0000, 0.0000, 0.2400]]]))
"""
- input = _transform_input(input)
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
height, width = input.size(2), input.size(3)
num_mixes = params['mix_pairs'].size(0)
batch_size = params['mix_pairs'].size(1)
diff --git a/kornia/augmentation/mix_augmentation.py b/kornia/augmentation/mix_augmentation.py
index 6e2ca05f0..e1227f143 100644
--- a/kornia/augmentation/mix_augmentation.py
+++ b/kornia/augmentation/mix_augmentation.py
@@ -48,6 +48,8 @@ class RandomMixUp(MixAugmentationBase):
lambda_val (float or torch.Tensor, optional): min-max value of mixup strength. Default is 0-1.
same_on_batch (bool): apply the same transformation across the batch.
This flag will not maintain permutation order. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False
Inputs:
- Input image tensors, shape of :math:`(B, C, H, W)`.
@@ -79,8 +81,8 @@ class RandomMixUp(MixAugmentationBase):
"""
def __init__(self, lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
- same_on_batch: bool = False, p: float = 1.0) -> None:
- super(RandomMixUp, self).__init__(p=1., p_batch=p, same_on_batch=same_on_batch)
+ same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False) -> None:
+ super(RandomMixUp, self).__init__(p=1., p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
if lambda_val is None:
self.lambda_val = torch.tensor([0, 1.])
else:
@@ -143,6 +145,8 @@ class RandomCutMix(MixAugmentationBase):
If None, it will be set to [0, 1], which means no restriction.
same_on_batch (bool): apply the same transformation across the batch.
This flag will not maintain permutation order. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False
Inputs:
- Input image tensors, shape of :math:`(B, C, H, W)`.
@@ -177,8 +181,8 @@ class RandomCutMix(MixAugmentationBase):
def __init__(self, height: int, width: int, num_mix: int = 1,
cut_size: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
beta: Optional[Union[torch.Tensor, float]] = None, same_on_batch: bool = False,
- p: float = 1.) -> None:
- super(RandomCutMix, self).__init__(p=1., p_batch=p, same_on_batch=same_on_batch)
+ p: float = 1., keepdim: bool = False) -> None:
+ super(RandomCutMix, self).__init__(p=1., p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.height = height
self.width = width
self.num_mix = num_mix
diff --git a/kornia/augmentation/utils/__init__.py b/kornia/augmentation/utils/__init__.py
index 5ad991aab..65ff345a2 100644
--- a/kornia/augmentation/utils/__init__.py
+++ b/kornia/augmentation/utils/__init__.py
@@ -18,6 +18,9 @@ from kornia.augmentation.utils.helpers import (
_adapted_uniform,
_adapted_beta,
_shape_validation,
+ _validate_input,
+ _validate_input3D,
+ _transform_output_shape
)
__all__ = [
@@ -38,4 +41,7 @@ __all__ = [
"_joint_range_check",
"_singular_range_check",
"_tuple_range_reader",
+ "_validate_input",
+ "_validate_input3D",
+ "_transform_output_shape"
]
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 6a971fa60..e92171b54 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -1,7 +1,53 @@
-from typing import Tuple, Union, List, cast, Optional
+from typing import Tuple, Union, List, Callable
import torch
from torch.distributions import Uniform, Beta
+from functools import wraps
+
+
+def _validate_input(f: Callable) -> Callable:
+ r"""Validates the 2D input of the wrapped function.
+
+ Args:
+ f: a function that takes the first argument as tensor.
+
+ Returns:
+ the wrapped function after input is validated.
+ """
+ @wraps(f)
+ def wrapper(input: torch.Tensor, *args, **kwargs):
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+
+ _validate_shape(input.shape, required_shapes=('BCHW',))
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+
+ return f(input, *args, **kwargs)
+
+ return wrapper
+
+
+def _validate_input3D(f: Callable) -> Callable:
+ r"""Validates the 3D input of the wrapped function.
+
+ Args:
+ f: a function that takes the first argument as tensor.
+
+ Returns:
+ the wrapped function after input is validated.
+ """
+ @wraps(f)
+ def wrapper(input: torch.Tensor, *args, **kwargs):
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+
+ input_shape = len(input.shape)
+ assert input_shape == 5, f'Expect input of 5 dimensions, got {input_shape} instead'
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+
+ return f(input, *args, **kwargs)
+
+ return wrapper
from kornia.utils import _extract_device_dtype
@@ -84,10 +130,41 @@ def _validate_input_dtype(input: torch.Tensor, accepted_dtypes: List) -> None:
raise TypeError(f"Expected input of {accepted_dtypes}. Got {input.dtype}")
-def _validate_shape(shape: Union[Tuple, torch.Size], required_shapes: List[str] = ["BCHW"]) -> None:
- r"""Check if the dtype of the input tensor is in the range of accepted_dtypes
+def _transform_output_shape(output: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ shape: Tuple) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ r"""Collapse the broadcasted batch dimensions an input tensor to be the specified shape.
Args:
input: torch.Tensor
+ shape: List/tuple of int
+
+ Returns:
+ torch.Tensor
+ """
+ is_tuple = isinstance(output, tuple)
+ if is_tuple:
+ out_tensor, trans_matrix = output
+ else:
+ out_tensor = output
+ trans_matrix = None
+
+ if trans_matrix is not None:
+ if len(out_tensor.shape) > len(shape): # if output is broadcasted
+ assert trans_matrix.shape[0] == 1, f'Dimension 0 of transformation matrix is ' \
+ f'expected to be 1, got {trans_matrix.shape[0]}'
+ trans_matrix = trans_matrix.squeeze(0)
+
+ for dim in range(len(out_tensor.shape) - len(shape)):
+ assert out_tensor.shape[0] == 1, f'Dimension {dim} of input is ' \
+ f'expected to be 1, got {out_tensor.shape[0]}'
+ out_tensor = out_tensor.squeeze(0)
+
+ return (out_tensor, trans_matrix) if is_tuple else out_tensor # type: ignore
+
+
+def _validate_shape(shape: Union[Tuple, torch.Size], required_shapes: Tuple[str, ...] = ("BCHW",)) -> None:
+ r"""Check if the dtype of the input tensor is in the range of accepted_dtypes
+ Args:
+ shape: tensor shape
required_shapes: List. e.g. ["BCHW", "BCDHW"]
"""
passed = False
diff --git a/test/augmentation/test_base.py b/test/augmentation/test_base.py
index 8169b510f..abc841fe3 100644
--- a/test/augmentation/test_base.py
+++ b/test/augmentation/test_base.py
@@ -25,7 +25,7 @@ class TestBasicAugmentationBase:
augmentation = _BasicAugmentationBase(p=1., p_batch=1)
with patch.object(augmentation, "transform_tensor", autospec=True) as transform_tensor:
transform_tensor.side_effect = lambda x: x.unsqueeze(dim=2)
- output = augmentation.__infer_input__(input)
+ output = augmentation.transform_tensor(input)
assert output.shape == torch.Size([2, 3, 1, 4, 5])
assert_allclose(input, output[:, :, 0, :, :])
@@ -51,20 +51,23 @@ class TestBasicAugmentationBase:
assert "batch_prob" in output
assert len(output['degrees']) == output['batch_prob'].sum().item() == num
- def test_forward(self, device, dtype):
+ @pytest.mark.parametrize('keepdim', (True, False))
+ def test_forward(self, device, dtype, keepdim):
torch.manual_seed(42)
input = torch.rand((12, 3, 4, 5), device=device, dtype=dtype)
- expected_output = input.unsqueeze(dim=1)[..., :2, :2]
- augmentation = _BasicAugmentationBase(p=.3, p_batch=1.)
+ expected_output = input[..., :2, :2] if keepdim else input.unsqueeze(dim=0)[..., :2, :2]
+ augmentation = _BasicAugmentationBase(p=.3, p_batch=1., keepdim=keepdim)
with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform, \
patch.object(augmentation, "generate_parameters", autospec=True) as generate_parameters, \
- patch.object(augmentation, "transform_tensor", autospec=True) as transform_tensor:
+ patch.object(augmentation, "transform_tensor", autospec=True) as transform_tensor, \
+ patch.object(augmentation, "__check_batching__", autospec=True) as check_batching:
generate_parameters.side_effect = lambda shape: {
'degrees': torch.arange(0, shape[0], device=device, dtype=dtype)
}
- transform_tensor.side_effect = lambda x: x.unsqueeze(dim=1)
+ transform_tensor.side_effect = lambda x: x.unsqueeze(dim=0)
apply_transform.side_effect = lambda input, params: input[..., :2, :2]
+ check_batching.side_effect = lambda input: None
output = augmentation(input)
assert output.shape == expected_output.shape
assert_allclose(output, expected_output)
@@ -72,6 +75,21 @@ class TestBasicAugmentationBase:
class TestAugmentationBase2D:
+ @pytest.mark.parametrize('input_shape, in_trans_shape', [
+ ((2, 3, 4, 5), (2, 3, 3)),
+ ((3, 4, 5), (3, 3)),
+ ((4, 5), (3, 3)),
+ pytest.param((1, 2, 3, 4, 5), (2, 3, 3), marks=pytest.mark.xfail),
+ pytest.param((2, 3, 4, 5), (1, 3, 3), marks=pytest.mark.xfail),
+ pytest.param((2, 3, 4, 5), (3, 3), marks=pytest.mark.xfail),
+ ])
+ def test_check_batching(self, device, dtype, input_shape, in_trans_shape):
+ input = torch.rand(input_shape, device=device, dtype=dtype)
+ in_trans = torch.rand(in_trans_shape, device=device, dtype=dtype)
+ augmentation = AugmentationBase2D(p=1., p_batch=1)
+ augmentation.__check_batching__(input)
+ augmentation.__check_batching__((input, in_trans))
+
def test_forward(self, device, dtype):
torch.manual_seed(42)
input = torch.rand((2, 3, 4, 5), device=device, dtype=dtype)
diff --git a/test/augmentation/test_functional.py b/test/augmentation/test_functional.py
index b99df80a2..f24bc4751 100644
--- a/test/augmentation/test_functional.py
+++ b/test/augmentation/test_functional.py
@@ -23,7 +23,7 @@ class TestHorizontalFlipFn:
[0., 0., 0., 0.],
[2., 1., 0., 0.]], device=device, dtype=dtype) # 3 x 4
- assert (F.apply_hflip(input) == expected).all()
+ assert (F.apply_hflip(input[None, None]) == expected).all()
def test_batch_random_hflip(self, device, dtype):
batch_size = 5
@@ -51,7 +51,7 @@ class TestVerticalFlipFn:
[0., 0., 0.],
[0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
- assert (F.apply_vflip(input) == expected).all()
+ assert (F.apply_vflip(input[None, None]) == expected).all()
def test_batch_random_vflip(self, device, dtype):
batch_size = 5
@@ -86,7 +86,7 @@ class TestColorJitter:
expected = input
- assert_allclose(F.apply_color_jitter(input, jitter_param), expected, atol=1e-4, rtol=1e-5)
+ assert_allclose(F.apply_color_jitter(input[None], jitter_param), expected, atol=1e-4, rtol=1e-5)
def test_color_jitter_batch(self):
batch_size = 2
@@ -327,7 +327,7 @@ class TestRandomGrayscale:
[0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]]])
expected = expected.to(device)
- assert_allclose(F.apply_grayscale(data), expected)
+ assert_allclose(F.apply_grayscale(data[None]), expected)
def test_opencv_true_batch(self, device):
batch_size = 4
diff --git a/test/augmentation/test_transformation_matrix.py b/test/augmentation/test_transformation_matrix.py
index d93d3cc65..b949466eb 100644
--- a/test/augmentation/test_transformation_matrix.py
+++ b/test/augmentation/test_transformation_matrix.py
@@ -24,7 +24,7 @@ class TestHorizontalFlipFn:
[0., 1., 0.],
[0., 0., 1.]]) # 3 x 3
- assert (F.compute_hflip_transformation(input) == expected_transform).all()
+ assert (F.compute_hflip_transformation(input[None, None]) == expected_transform).all()
def test_batch_random_hflip(self, device):
batch_size = 5
@@ -57,7 +57,7 @@ class TestVerticalFlipFn:
[0., -1., 2.],
[0., 0., 1.]]) # 3 x 3
- assert (F.compute_vflip_transformation(input) == expected_transform).all()
+ assert (F.compute_vflip_transformation(input[None, None]) == expected_transform).all()
def test_batch_random_vflip(self, device):
batch_size = 5
@@ -85,7 +85,7 @@ class TestIntensityTransformation:
expected_transform = torch.eye(3).unsqueeze(0) # 3 x 3
- assert_allclose(F.compute_intensity_transformation(input), expected_transform, atol=1e-4, rtol=1e-5)
+ assert_allclose(F.compute_intensity_transformation(input[None]), expected_transform, atol=1e-4, rtol=1e-5)
def test_intensity_transformation_batch(self):
batch_size = 2