Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Enhance] Random generator refactor (#1459)

Jian Shifb7565a2f23b
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rst
index 3564693f7..13ff7a019 100644
--- a/docs/source/augmentation.rst
+++ b/docs/source/augmentation.rst
@@ -14,6 +14,43 @@ in bounding boxes or landmark keypoints for object detection tasks. It gives the
perform complex data augmentations pipelines.
+Benchmark
+---------
+
+.. table:: Here is a benchmark performed on `Google Colab <https://colab.research.google.com/drive/1b-HpK4EsZR8uolztgH4roNBLaDwcMULx?usp=sharing>`_
+ K80 GPU with different libraries and batch sizes. This benchmark shows
+ strong GPU augmentation speed acceleration brought by Kornia data augmentations. The image size is fixed to 224x224 and the
+ unit is milliseconds (ms).
+
+ +--------------------------------+-----------------+-----------------+-----------------------------------------------------+
+ | Libraries | TorchVision | Albumentations | Kornia (GPU) |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | Batch Size | 1 | 1 | 1 | 32 | 128 |
+ +================================+=================+=================+=================+=================+=================+
+ | RandomPerspective | 4.88±1.82 | 4.68±3.60 | 4.74±2.84 | 0.37±2.67 | 0.20±27.00 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | ColorJitter | 4.40±2.88 | 3.58±3.66 | 4.14±3.85 | 0.90±24.68 | 0.83±12.96 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | RandomAffine | 3.12±5.80 | 2.43±7.11 | 3.01±7.80 | 0.30±4.39 | 0.18±6.30 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | RandomVerticalFlip | 0.32±0.08 | 0.34±0.16 | 0.35±0.82 | 0.02±0.13 | 0.01±0.35 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | RandomHorizontalFlip | 0.32±0.08 | 0.34±0.18 | 0.31±0.59 | 0.01±0.26 | 0.01±0.37 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | RandomRotate | 1.82±4.70 | 1.59±4.33 | 1.58±4.44 | 0.25±2.09 | 0.17±5.69 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | RandomCrop | 4.09±3.41 | 4.03±4.94 | 3.84±3.07 | 0.16±1.17 | 0.08±9.42 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | RandomErasing | 2.31±1.47 | 1.89±1.08 | 2.32±3.31 | 0.44±2.82 | 0.57±9.74 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | RandomGrayscale | 0.41±0.18 | 0.43±0.60 | 0.45±1.20 | 0.03±0.11 | 0.03±7.10 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | RandomResizedCrop | 4.23±2.86 | 3.80±3.61 | 4.07±2.67 | 0.23±5.27 | 0.13±8.04 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+ | RandomCenterCrop | 2.93±1.29 | 2.81±1.38 | 2.88±2.34 | 0.13±2.20 | 0.07±9.41 |
+ +--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+
+
+
.. currentmodule:: kornia.augmentation
.. toctree::
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index c67ce1eab..2055971eb 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -1,6 +1,4 @@
-import warnings
-from typing import cast, Dict, List, Optional, Tuple, Union
-
+from typing import Any, cast, Dict, List, Optional, Tuple, Union
import torch
from torch.nn.functional import pad
@@ -39,10 +37,10 @@ from kornia.geometry.transform import (
warp_perspective,
)
from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
-from kornia.utils import _extract_device_dtype, create_meshgrid
+from kornia.utils import create_meshgrid
from . import random_generator as rg
-from .utils import _range_bound, _transform_input
+from .utils import _transform_input
class RandomHorizontalFlip(GeometricAugmentationBase2D):
@@ -85,16 +83,16 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
[ 0., 0., 1.]]]))
>>> seq.inverse(seq(input)).equal(input)
True
- """
-
- def __repr__(self) -> str:
- return self.__class__.__name__ + f"({super().__repr__()})"
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return dict(batch_shape=torch.as_tensor(batch_shape))
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> seq = RandomHorizontalFlip(p=1.0)
+ >>> (seq(input) == seq(input, params=seq._params)).all()
+ tensor(True)
+ """
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- w: int = cast(int, params['batch_shape'][-1])
+ w: int = int(params["forward_input_shape"][-1])
flip_mat: torch.Tensor = torch.tensor(
[[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype
)
@@ -152,16 +150,16 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
[ 0., 0., 1.]]]))
>>> seq.inverse(seq(input)).equal(input)
True
- """
-
- def __repr__(self) -> str:
- return self.__class__.__name__ + f"({super().__repr__()})"
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return dict(batch_shape=torch.as_tensor(batch_shape))
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> seq = RandomVerticalFlip(p=1.0)
+ >>> (seq(input) == seq(input, params=seq._params)).all()
+ tensor(True)
+ """
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- h: int = cast(int, params['batch_shape'][-2])
+ h: int = int(params["forward_input_shape"][-2])
flip_mat: torch.Tensor = torch.tensor(
[[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype
)
@@ -228,6 +226,12 @@ class ColorJitter(IntensityAugmentationBase2D):
[[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993],
[0.9993, 0.9993, 0.9993]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -242,43 +246,26 @@ class ColorJitter(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._device, self._dtype = _extract_device_dtype([brightness, contrast, hue, saturation])
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.hue = hue
-
- def __repr__(self) -> str:
- repr = f"brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- brightness: torch.Tensor = _range_bound(
- self.brightness, 'brightness', center=1.0, bounds=(0, 2), device=self._device, dtype=self._dtype
- )
- contrast: torch.Tensor = _range_bound(
- self.contrast, 'contrast', center=1.0, device=self._device, dtype=self._dtype
- )
- saturation: torch.Tensor = _range_bound(
- self.saturation, 'saturation', center=1.0, device=self._device, dtype=self._dtype
- )
- hue: torch.Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=self._device, dtype=self._dtype)
- return rg.random_color_jitter_generator(
- batch_shape[0], brightness, contrast, saturation, hue, self.same_on_batch, self.device, self.dtype
+ self._param_generator = cast(
+ rg.ColorJitterGenerator, rg.ColorJitterGenerator(brightness, contrast, saturation, hue)
)
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
transforms = [
- lambda img: adjust_brightness(img, params['brightness_factor'] - 1),
- lambda img: adjust_contrast(img, params['contrast_factor']),
- lambda img: adjust_saturation(img, params['saturation_factor']),
- lambda img: adjust_hue(img, params['hue_factor'] * 2 * pi),
+ lambda img: adjust_brightness(img, params["brightness_factor"] - 1),
+ lambda img: adjust_contrast(img, params["contrast_factor"]),
+ lambda img: adjust_saturation(img, params["saturation_factor"]),
+ lambda img: adjust_hue(img, params["hue_factor"] * 2 * pi),
]
jittered = input
- for idx in params['order'].tolist():
+ for idx in params["order"].tolist():
t = transforms[idx]
jittered = t(jittered)
@@ -309,8 +296,8 @@ class RandomGrayscale(IntensityAugmentationBase2D):
Examples:
>>> rng = torch.manual_seed(0)
>>> inputs = torch.randn((1, 3, 3, 3))
- >>> rec_er = RandomGrayscale(p=1.0)
- >>> rec_er(inputs)
+ >>> aug = RandomGrayscale(p=1.0)
+ >>> aug(inputs)
tensor([[[[-1.1344, -0.1330, 0.1517],
[-0.0791, 0.6711, -0.1413],
[-0.1717, -0.9023, 0.0819]],
@@ -322,6 +309,12 @@ class RandomGrayscale(IntensityAugmentationBase2D):
[[-1.1344, -0.1330, 0.1517],
[-0.0791, 0.6711, -0.1413],
[-0.1717, -0.9023, 0.0819]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomGrayscale(p=1.0)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -329,9 +322,6 @@ class RandomGrayscale(IntensityAugmentationBase2D):
) -> None:
super().__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__()})"
-
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
@@ -373,11 +363,17 @@ class RandomErasing(IntensityAugmentationBase2D):
Examples:
>>> rng = torch.manual_seed(0)
>>> inputs = torch.ones(1, 1, 3, 3)
- >>> rec_er = RandomErasing((.4, .8), (.3, 1/.3), p=0.5)
- >>> rec_er(inputs)
+ >>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=0.5)
+ >>> aug(inputs)
tensor([[[[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
# Note: Extra params, inplace=False in Torchvision.
@@ -392,37 +388,20 @@ class RandomErasing(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._device, self._dtype = _extract_device_dtype([scale, ratio])
self.scale = scale
self.ratio = ratio
self.value: float = float(value)
-
- def __repr__(self) -> str:
- repr = f"scale={self.scale}, ratio={self.ratio}, value={self.value}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)
- ratio = torch.as_tensor(self.ratio, device=self._device, dtype=self._dtype)
- return rg.random_rectangles_params_generator(
- batch_shape[0],
- batch_shape[-2],
- batch_shape[-1],
- scale=scale,
- ratio=ratio,
- value=self.value,
- same_on_batch=self.same_on_batch,
- device=self.device,
- dtype=self.dtype,
+ self._param_generator = cast(
+ rg.RectangleEraseGenerator, rg.RectangleEraseGenerator(scale, ratio, float(value))
)
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
_, c, h, w = input.size()
- values = params['values'].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, *input.shape[1:]).to(input)
+ values = params["values"].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, *input.shape[1:]).to(input)
- bboxes = bbox_generator(params['xs'], params['ys'], params['widths'], params['heights'])
+ bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])
mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W
mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W
transformed = torch.where(mask == 1.0, values, input)
@@ -435,8 +414,8 @@ class RandomPerspective(GeometricAugmentationBase2D):
.. image:: _static/img/RandomPerspective.png
Args:
- p: probability of the image being perspectively transformed..
- distortion_scale: it controls the degree of distortion and ranges from 0 to 1.
+ p: probability of the image being perspectively transformed.
+ distortion_scale: the degree of distortion, ranged from 0 to 1.
resample: the interpolation method to use.
return_transform: if ``True`` return the matrix describing the transformation
applied to each.
@@ -467,6 +446,12 @@ class RandomPerspective(GeometricAugmentationBase2D):
tensor([[[[0.0500, 0.0961, 0.0000],
[0.2011, 0.3144, 0.0000],
[0.0031, 0.0130, 0.0053]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomPerspective(0.5, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -480,35 +465,16 @@ class RandomPerspective(GeometricAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._device, self._dtype = _extract_device_dtype([distortion_scale])
- self.distortion_scale = distortion_scale
- self.resample: Resample = Resample.get(resample)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
- )
-
- def __repr__(self) -> str:
- repr = (
- f"distortion_scale={self.distortion_scale}, interpolation={self.resample.name}, "
- f"align_corners={self.align_corners}"
+ self._param_generator = cast(
+ rg.PerspectiveGenerator, rg.PerspectiveGenerator(distortion_scale)
)
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- distortion_scale = torch.as_tensor(self.distortion_scale, device=self._device, dtype=self._dtype)
- return rg.random_perspective_generator(
- batch_shape[0],
- batch_shape[-2],
- batch_shape[-1],
- distortion_scale,
- self.same_on_batch,
- self.device,
- self.dtype,
+ self.flags: Dict[str, Any] = dict(
+ align_corners=align_corners,
+ resample=Resample.get(resample)
)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return get_perspective_transform(params['start_points'].to(input), params['end_points'].to(input))
+ return get_perspective_transform(params["start_points"].to(input), params["end_points"].to(input))
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
@@ -516,7 +482,8 @@ class RandomPerspective(GeometricAugmentationBase2D):
_, _, height, width = input.shape
transform = cast(torch.Tensor, transform)
return warp_perspective(
- input, transform, (height, width), mode=self.resample.name.lower(), align_corners=self.align_corners
+ input, transform, (height, width), mode=self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"]
)
def inverse_transform(
@@ -589,6 +556,12 @@ class RandomAffine(GeometricAugmentationBase2D):
tensor([[[[0.4963, 0.7682, 0.0885],
[0.1320, 0.3074, 0.6341],
[0.4901, 0.8964, 0.4556]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomAffine((-15., 20.), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -606,104 +579,23 @@ class RandomAffine(GeometricAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._device, self._dtype = _extract_device_dtype([degrees, translate, scale, shear])
- self.degrees = degrees
- self.translate = translate
- self.scale = scale
- self.shear = shear
- self.resample: Resample = Resample.get(resample)
- self.padding_mode: SamplePadding = SamplePadding.get(padding_mode)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- resample=torch.tensor(self.resample.value),
- padding_mode=torch.tensor(self.padding_mode.value),
- align_corners=torch.tensor(align_corners),
+ self._param_generator = cast(
+ rg.AffineGenerator, rg.AffineGenerator(degrees, translate, scale, shear)
)
-
- def __repr__(self) -> str:
- repr = (
- f"degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shear}, "
- f"resample={self.resample.name}"
- )
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- degrees = _range_bound(self.degrees, 'degrees', 0, (-360, 360), device=self._device, dtype=self._dtype)
- translate: Optional[torch.Tensor] = None
- scale: Optional[torch.Tensor] = None
- shear: Optional[torch.Tensor] = None
-
- if self.translate is not None:
- translate = _range_bound(
- self.translate, 'translate', bounds=(0, 1), check='singular', device=self._device, dtype=self._dtype
- )
- if self.scale is not None:
- scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)
- if len(scale) == 2:
- scale = _range_bound(
- scale, 'scale', bounds=(0, float('inf')), check='singular', device=self._device, dtype=self._dtype
- )
- elif len(scale) == 4:
- scale = torch.cat(
- [
- _range_bound(
- scale[:2],
- 'scale_x',
- bounds=(0, float('inf')),
- check='singular',
- device=self._device,
- dtype=self._dtype,
- ),
- _range_bound(
- scale[2:],
- 'scale_y',
- bounds=(0, float('inf')),
- check='singular',
- device=self._device,
- dtype=self._dtype,
- ),
- ]
- )
- else:
- raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {scale}")
- if self.shear is not None:
- shear = torch.as_tensor(self.shear, device=self._device, dtype=self._dtype)
- shear = torch.stack(
- [
- _range_bound(
- shear if shear.dim() == 0 else shear[:2],
- 'shear-x',
- 0,
- (-360, 360),
- device=self._device,
- dtype=self._dtype,
- ),
- torch.tensor([0, 0], device=self._device, dtype=self._dtype)
- if shear.dim() == 0 or len(shear) == 2
- else _range_bound(shear[2:], 'shear-y', 0, (-360, 360), device=self._device, dtype=self._dtype),
- ]
- )
- return rg.random_affine_generator(
- batch_shape[0],
- batch_shape[-2],
- batch_shape[-1],
- degrees,
- translate,
- scale,
- shear,
- self.same_on_batch,
- self.device,
- self.dtype,
+ self.flags = dict(
+ resample=Resample.get(resample),
+ padding_mode=SamplePadding.get(padding_mode),
+ align_corners=align_corners,
)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return get_affine_matrix2d(
- torch.as_tensor(params['translations'], device=input.device, dtype=input.dtype),
- torch.as_tensor(params['center'], device=input.device, dtype=input.dtype),
- torch.as_tensor(params['scale'], device=input.device, dtype=input.dtype),
- torch.as_tensor(params['angle'], device=input.device, dtype=input.dtype),
- deg2rad(torch.as_tensor(params['sx'], device=input.device, dtype=input.dtype)),
- deg2rad(torch.as_tensor(params['sy'], device=input.device, dtype=input.dtype)),
+ torch.as_tensor(params["translations"], device=input.device, dtype=input.dtype),
+ torch.as_tensor(params["center"], device=input.device, dtype=input.dtype),
+ torch.as_tensor(params["scale"], device=input.device, dtype=input.dtype),
+ torch.as_tensor(params["angle"], device=input.device, dtype=input.dtype),
+ deg2rad(torch.as_tensor(params["sx"], device=input.device, dtype=input.dtype)),
+ deg2rad(torch.as_tensor(params["sy"], device=input.device, dtype=input.dtype)),
)
def apply_transform(
@@ -715,9 +607,9 @@ class RandomAffine(GeometricAugmentationBase2D):
input,
transform[:, :2, :],
(height, width),
- self.resample.name.lower(),
- align_corners=self.align_corners,
- padding_mode=self.padding_mode.name.lower(),
+ self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"],
+ padding_mode=self.flags["padding_mode"].name.lower(),
)
def inverse_transform(
@@ -778,6 +670,12 @@ class CenterCrop(GeometricAugmentationBase2D):
[ 0.6920, 0.6920, -0.3160, -0.3160],
[-1.2633, -1.2633, 0.3500, 0.3500],
[-1.2633, -1.2633, 0.3500, 0.3500]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = CenterCrop(2, p=1., cropping_mode="resample")
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -788,7 +686,7 @@ class CenterCrop(GeometricAugmentationBase2D):
return_transform: bool = False,
p: float = 1.0,
keepdim: bool = False,
- cropping_mode: str = 'slice',
+ cropping_mode: str = "slice",
) -> None:
# same_on_batch is always True for CenterCrop
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
@@ -799,46 +697,44 @@ class CenterCrop(GeometricAugmentationBase2D):
self.size = (size, size)
else:
raise Exception(f"Invalid size type. Expected (int, tuple(int, int). " f"Got: {type(size)}.")
- self.resample = Resample.get(resample)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
- )
- self.cropping_mode = cropping_mode
- def __repr__(self) -> str:
- repr = f"size={self.size}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
+ self.flags = dict(
+ resample=Resample.get(resample),
+ cropping_mode=cropping_mode,
+ align_corners=align_corners,
+ size=self.size
+ )
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.center_crop_generator(batch_shape[0], batch_shape[-2], batch_shape[-1], self.size, self.device)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform(params['src'].to(input), params['dst'].to(input))
+ transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- if self.cropping_mode == 'resample': # uses bilinear interpolation to crop
+ if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat(
- input, transform[:, :2, :], self.size, self.resample.name.lower(), 'zeros', self.align_corners
+ input, transform[:, :2, :], self.size, self.flags["resample"].name.lower(),
+ "zeros", self.flags["align_corners"]
)
- if self.cropping_mode == 'slice': # uses advanced slicing to crop
+ if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
# TODO: implement as separated function `crop_and_resize_iterative`
B, C, _, _ = input.shape
H, W = self.size
out = torch.empty(B, C, H, W, device=input.device, dtype=input.dtype)
for i in range(B):
- x1 = int(params['src'][i, 0, 0])
- x2 = int(params['src'][i, 1, 0]) + 1
- y1 = int(params['src'][i, 0, 1])
- y2 = int(params['src'][i, 3, 1]) + 1
+ x1 = int(params["src"][i, 0, 0])
+ x2 = int(params["src"][i, 1, 0]) + 1
+ y1 = int(params["src"][i, 0, 1])
+ y2 = int(params["src"][i, 3, 1]) + 1
out[i] = input[i : i + 1, :, y1:y2, x1:x2]
return out
- raise NotImplementedError(f"Not supported type: {self.cropping_mode}.")
+ raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
def inverse_transform(
self,
@@ -847,15 +743,15 @@ class CenterCrop(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
**kwargs,
) -> torch.Tensor:
- if self.cropping_mode != 'resample':
+ if self.flags["cropping_mode"] != "resample":
raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {self.cropping_mode}."
+ f"`inverse` is only applicable for resample cropping mode. Got {self.flags['cropping_mode']}."
)
if size is None:
size = self.size
- mode = self.resample.name.lower() if "mode" not in kwargs else kwargs['mode']
- align_corners = self.align_corners if "align_corners" not in kwargs else kwargs['align_corners']
- padding_mode = 'zeros' if "padding_mode" not in kwargs else kwargs['padding_mode']
+ mode = self.flags["resample"].name.lower() if "mode" not in kwargs else kwargs["mode"]
+ align_corners = self.flags["align_corners"] if "align_corners" not in kwargs else kwargs["align_corners"]
+ padding_mode = "zeros" if "padding_mode" not in kwargs else kwargs["padding_mode"]
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
@@ -907,6 +803,12 @@ class RandomRotation(GeometricAugmentationBase2D):
[8.6398e-03, 2.9485e-03, 5.8971e-03, 1.7365e-02],
[2.9054e-03, 9.9416e-01, 1.9825e+00, 2.3134e-02],
[2.5777e-05, 1.1640e-02, 9.9992e-01, 1.9392e+00]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomRotation(degrees=45.0, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
# Note: Extra params, center=None, fill=0 in TorchVision
@@ -922,21 +824,13 @@ class RandomRotation(GeometricAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._device, self._dtype = _extract_device_dtype([degrees])
- self.degrees = degrees
- self.resample: Resample = Resample.get(resample)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
+ self._param_generator = cast(
+ rg.PlainUniformGenerator, rg.PlainUniformGenerator((degrees, "degrees", 0., (-360., 360.)))
+ )
+ self.flags = dict(
+ resample=Resample.get(resample),
+ align_corners=align_corners,
)
-
- def __repr__(self) -> str:
- repr = f"degrees={self.degrees}, interpolation={self.resample.name}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- degrees = _range_bound(self.degrees, 'degrees', 0, (-360, 360), device=self._device, dtype=self._dtype)
- return rg.random_rotation_generator(batch_shape[0], degrees, self.same_on_batch, self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
# TODO: Update to use `get_rotation_matrix2d`
@@ -956,7 +850,8 @@ class RandomRotation(GeometricAugmentationBase2D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
transform = cast(torch.Tensor, transform)
- return affine(input, transform[..., :2, :3], self.resample.name.lower(), 'zeros', self.align_corners)
+ return affine(
+ input, transform[..., :2, :3], self.flags["resample"].name.lower(), "zeros", self.flags["align_corners"])
def inverse_transform(
self,
@@ -1025,6 +920,12 @@ class RandomCrop(GeometricAugmentationBase2D):
tensor([[[[3., 4., 4.],
[3., 4., 4.],
[6., 7., 7.]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomCrop((2, 2), p=1., cropping_mode="resample")
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -1033,68 +934,61 @@ class RandomCrop(GeometricAugmentationBase2D):
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',
+ 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,
keepdim: bool = False,
- cropping_mode: str = 'slice',
+ cropping_mode: str = "slice",
) -> None:
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
super().__init__(
p=1.0, 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
- self.fill = fill
- self.padding_mode = padding_mode
- self.resample: Resample = Resample.get(resample)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
- )
- self.cropping_mode = cropping_mode
-
- def __repr__(self) -> str:
- repr = (
- f"crop_size={self.size}, padding={self.padding}, fill={self.fill}, pad_if_needed={self.pad_if_needed}, "
- f"padding_mode={self.padding_mode}, resample={self.resample.name}"
- )
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.random_crop_generator(
- batch_shape[0],
- (batch_shape[-2], batch_shape[-1]),
- self.size,
- same_on_batch=self.same_on_batch,
- device=self.device,
- dtype=self.dtype,
+ self._param_generator = cast(rg.CropGenerator, rg.CropGenerator(size))
+ self.flags = dict(
+ size=size,
+ padding=padding,
+ pad_if_needed=pad_if_needed,
+ fill=fill,
+ padding_mode=padding_mode,
+ resample=Resample.get(resample),
+ align_corners=align_corners,
+ cropping_mode=cropping_mode,
)
def compute_padding(self, shape: torch.Size) -> List[int]:
if len(shape) != 4:
raise AssertionError(f"Expected BCHW. Got {shape}.")
padding = [0, 0, 0, 0]
- if self.padding is not None:
- if isinstance(self.padding, int):
- self.padding = cast(int, self.padding)
- padding = [self.padding, self.padding, self.padding, self.padding]
- elif isinstance(self.padding, tuple) and len(self.padding) == 2:
- self.padding = cast(Tuple[int, int], self.padding)
- padding = [self.padding[1], self.padding[1], self.padding[0], self.padding[0]]
- elif isinstance(self.padding, tuple) and len(self.padding) == 4:
- self.padding = cast(Tuple[int, int, int, int], self.padding)
- padding = [self.padding[3], self.padding[2], self.padding[1], self.padding[0]]
-
- if self.pad_if_needed and shape[-2] < self.size[0]:
- padding = [0, 0, (self.size[0] - shape[-2]), self.size[0] - shape[-2]]
-
- if self.pad_if_needed and shape[-1] < self.size[1]:
- padding = [self.size[1] - shape[-1], self.size[1] - shape[-1], 0, 0]
+ if self.flags["padding"] is not None:
+ if isinstance(self.flags["padding"], int):
+ padding = [self.flags["padding"]] * 4
+ elif isinstance(self.flags["padding"], tuple) and len(self.flags["padding"]) == 2:
+ padding = [
+ self.flags["padding"][1],
+ self.flags["padding"][1],
+ self.flags["padding"][0],
+ self.flags["padding"][0]
+ ]
+ elif isinstance(self.flags["padding"], tuple) and len(self.flags["padding"]) == 4:
+ padding = [
+ self.flags["padding"][3],
+ self.flags["padding"][2],
+ self.flags["padding"][1],
+ self.flags["padding"][0]
+ ]
+ else:
+ raise RuntimeError(
+ f"Expect `padding` to be a scalar, or length 2/4 list. Got {self.flags['padding']}.")
+
+ if self.flags["pad_if_needed"] and shape[-2] < self.flags["size"][0]:
+ padding = [0, 0, (self.flags["size"][0] - shape[-2]), self.flags["size"][0] - shape[-2]]
+
+ if self.flags["pad_if_needed"] and shape[-1] < self.flags["size"][1]:
+ padding = [self.flags["size"][1] - shape[-1], self.flags["size"][1] - shape[-1], 0, 0]
return padding
@@ -1102,38 +996,38 @@ class RandomCrop(GeometricAugmentationBase2D):
if padding is None:
padding = self.compute_padding(input.shape)
- input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+ input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
return input
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform(params['src'].to(input), params['dst'].to(input))
+ transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
return transform
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- if self.cropping_mode == 'resample': # uses bilinear interpolation to crop
+ if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat(
input,
transform,
- self.size,
- mode=self.resample.name.lower(),
- padding_mode='zeros',
- align_corners=self.align_corners,
+ self.flags["size"],
+ mode=self.flags["resample"].name.lower(),
+ padding_mode="zeros",
+ align_corners=self.flags["align_corners"],
)
- if self.cropping_mode == 'slice': # uses advanced slicing to crop
+ if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
B, C, _, _ = input.shape
- out = torch.empty(B, C, *self.size, device=input.device, dtype=input.dtype)
+ out = torch.empty(B, C, *self.flags["size"], device=input.device, dtype=input.dtype)
for i in range(B):
- x1 = int(params['src'][i, 0, 0])
- x2 = int(params['src'][i, 1, 0]) + 1
- y1 = int(params['src'][i, 0, 1])
- y2 = int(params['src'][i, 3, 1]) + 1
+ x1 = int(params["src"][i, 0, 0])
+ x2 = int(params["src"][i, 1, 0]) + 1
+ y1 = int(params["src"][i, 0, 1])
+ y2 = int(params["src"][i, 3, 1]) + 1
out[i] = input[i : i + 1, :, y1:y2, x1:x2]
return out
- raise NotImplementedError(f"Not supported type: {self.flags['mode']}.")
+ raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
def inverse_transform(
self,
@@ -1142,14 +1036,14 @@ class RandomCrop(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
**kwargs,
) -> torch.Tensor:
- if self.cropping_mode != 'resample':
+ if self.flags["cropping_mode"] != "resample":
raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {self.cropping_mode}."
+ f"`inverse` is only applicable for resample cropping mode. Got {self.flags['cropping_mode']}."
)
size = cast(Tuple[int, int], size)
- mode = self.resample.name.lower() if "mode" not in kwargs else kwargs['mode']
- align_corners = self.align_corners if "align_corners" not in kwargs else kwargs['align_corners']
- padding_mode = 'zeros' if "padding_mode" not in kwargs else kwargs['padding_mode']
+ mode = self.flags["resample"].name.lower() if "mode" not in kwargs else kwargs["mode"]
+ align_corners = self.flags["align_corners"] if "align_corners" not in kwargs else kwargs["align_corners"]
+ padding_mode = "zeros" if "padding_mode" not in kwargs else kwargs["padding_mode"]
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
@@ -1163,8 +1057,8 @@ class RandomCrop(GeometricAugmentationBase2D):
out = super().inverse(input, params, size, **kwargs)
if params is None:
params = self._params
- if 'padding_size' in params:
- padding_size = params['padding_size'].unique(dim=0).cpu().squeeze().numpy().tolist()
+ if "padding_size" in params:
+ padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().numpy().tolist()
padding_size = [-padding_size[0], -padding_size[1], -padding_size[2], -padding_size[3]]
else:
padding_size = [0, 0, 0, 0]
@@ -1193,7 +1087,7 @@ class RandomCrop(GeometricAugmentationBase2D):
)
self._params.update({"padding_size": _padding_size})
- if not self._params['batch_prob'].all():
+ if not self._params["batch_prob"].all():
# undo the pre-crop if nothing happened.
if isinstance(out, tuple) and isinstance(input, tuple):
return input[0], out[1]
@@ -1250,6 +1144,12 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
tensor([[[[1., 1., 2.],
[4., 4., 5.],
[7., 7., 8.]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample")
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -1263,83 +1163,54 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
align_corners: bool = True,
p: float = 1.0,
keepdim: bool = False,
- cropping_mode: str = 'slice',
+ cropping_mode: str = "slice",
) -> None:
# Since PyTorch does not support ragged tensor. So cropping function happens all the time.
super().__init__(
p=1.0, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
)
- self._device, self._dtype = _extract_device_dtype([scale, ratio])
- self.size = size
- self.scale = scale
- self.ratio = ratio
- self.resample: Resample = Resample.get(resample)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
- )
- self.cropping_mode = cropping_mode
-
- def __repr__(self) -> str:
- repr = f"size={self.size}, scale={self.scale}, ratio={self.ratio}, interpolation={self.resample.name}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)
- ratio = torch.as_tensor(self.ratio, device=self._device, dtype=self._dtype)
- target_size: torch.Tensor = rg.random_crop_size_generator(
- batch_shape[0],
- (batch_shape[-2], batch_shape[-1]),
- scale,
- ratio,
- self.same_on_batch,
- self.device,
- self.dtype,
- )['size']
- return rg.random_crop_generator(
- batch_shape[0],
- (batch_shape[-2], batch_shape[-1]),
- target_size,
- resize_to=self.size,
- same_on_batch=self.same_on_batch,
- device=self.device,
- dtype=self.dtype,
+ self._param_generator = cast(rg.ResizedCropGenerator, rg.ResizedCropGenerator(size, scale, ratio))
+ self.flags = dict(
+ size=size,
+ resample=Resample.get(resample),
+ align_corners=align_corners,
+ cropping_mode=cropping_mode,
)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform(params['src'].to(input), params['dst'].to(input))
+ transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- if self.cropping_mode == 'resample': # uses bilinear interpolation to crop
+ if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat(
input,
transform,
- self.size,
- mode=self.resample.name.lower(),
- padding_mode='zeros',
- align_corners=self.align_corners,
+ self.flags["size"],
+ mode=self.flags["resample"].name.lower(),
+ padding_mode="zeros",
+ align_corners=self.flags["align_corners"],
)
- if self.cropping_mode == 'slice': # uses advanced slicing to crop
+ if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
B, C, _, _ = input.shape
- out = torch.empty(B, C, *self.size, device=input.device, dtype=input.dtype)
+ out = torch.empty(B, C, *self.flags["size"], device=input.device, dtype=input.dtype)
for i in range(B):
- x1 = int(params['src'][i, 0, 0])
- x2 = int(params['src'][i, 1, 0]) + 1
- y1 = int(params['src'][i, 0, 1])
- y2 = int(params['src'][i, 3, 1]) + 1
+ x1 = int(params["src"][i, 0, 0])
+ x2 = int(params["src"][i, 1, 0]) + 1
+ y1 = int(params["src"][i, 0, 1])
+ y2 = int(params["src"][i, 3, 1]) + 1
out[i] = resize(
input[i : i + 1, :, y1:y2, x1:x2],
- self.size,
- interpolation=(self.resample.name).lower(),
- align_corners=self.align_corners,
+ self.flags["size"],
+ interpolation=(self.flags["resample"].name).lower(),
+ align_corners=self.flags["align_corners"],
)
return out
- raise NotImplementedError(f"Not supported type: {self.cropping_mode}.")
+ raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
def inverse_transform(
self,
@@ -1348,14 +1219,14 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
**kwargs,
) -> torch.Tensor:
- if self.cropping_mode != 'resample':
+ if self.flags["cropping_mode"] != "resample":
raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {self.cropping_mode}."
+ f"`inverse` is only applicable for resample cropping mode. Got {self.flags['cropping_mode']}."
)
size = cast(Tuple[int, int], size)
- mode = self.resample.name.lower() if "mode" not in kwargs else kwargs['mode']
- align_corners = self.align_corners if "align_corners" not in kwargs else kwargs['align_corners']
- padding_mode = 'zeros' if "padding_mode" not in kwargs else kwargs['padding_mode']
+ mode = self.flags["resample"].name.lower() if "mode" not in kwargs else kwargs["mode"]
+ align_corners = self.flags["align_corners"] if "align_corners" not in kwargs else kwargs["align_corners"]
+ padding_mode = "zeros" if "padding_mode" not in kwargs else kwargs["padding_mode"]
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
@@ -1408,20 +1279,15 @@ class Normalize(IntensityAugmentationBase2D):
if isinstance(std, (tuple, list)):
std = torch.tensor(std)
- self.mean = mean
- self.std = std
-
- def __repr__(self) -> str:
- repr = f"mean={self.mean}, std={self.std}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
+ self.flags = dict(mean=mean, std=std)
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- return normalize(input, self.mean, self.std)
+ return normalize(input, self.flags["mean"], self.flags["std"])
-class Denormalize(IntensityAugmentationBase2D):
+class Denormalize(Normalize):
r"""Denormalize tensor images with mean and standard deviation.
.. math::
@@ -1448,26 +1314,10 @@ class Denormalize(IntensityAugmentationBase2D):
torch.Size([1, 4, 3, 3])
"""
- def __init__(
- self,
- mean: torch.Tensor,
- std: torch.Tensor,
- return_transform: bool = False,
- p: float = 1.0,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
- self.mean = mean
- self.std = std
-
- def __repr__(self) -> str:
- repr = f"mean={self.mean}, std={self.std}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- return denormalize(input, self.mean, self.std)
+ return denormalize(input, self.flags["mean"], self.flags["std"])
class RandomMotionBlur(IntensityAugmentationBase2D):
@@ -1518,6 +1368,12 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
[0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
[0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
[0.5773, 1.0000, 1.0000, 1.0000, 0.7561]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomMotionBlur(3, 35., 0.5, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -1533,49 +1389,25 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__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
- self._device, self._dtype = _extract_device_dtype([angle, direction])
-
- self.angle = angle
- self.direction = direction
- self.border_type = BorderType.get(border_type)
- self.resample = Resample.get(resample)
- self.flags: Dict[str, torch.Tensor] = {
- "border_type": torch.tensor(self.border_type.value),
- "interpolation": torch.tensor(self.resample.value),
- }
-
- def __repr__(self) -> str:
- repr = (
- f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}, "
- + f"border_type='{self.border_type.name.lower()}'"
- )
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- angle = _range_bound(
- self.angle, 'angle', center=0.0, bounds=(-360, 360), device=self._device, dtype=self._dtype
- )
- direction = _range_bound(
- self.direction, 'direction', center=0.0, bounds=(-1, 1), device=self._device, dtype=self._dtype
- )
- return rg.random_motion_blur_generator(
- batch_shape[0], self.kernel_size, angle, direction, self.same_on_batch, self.device, self.dtype
+ self._param_generator = rg.MotionBlurGenerator(kernel_size, angle, direction)
+ self.flags = dict(
+ border_type=BorderType.get(border_type),
+ resample=Resample.get(resample)
)
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- kernel_size: int = cast(int, params['ksize_factor'].unique().item())
- angle = params['angle_factor']
- direction = params['direction_factor']
+ kernel_size: int = cast(int, params["ksize_factor"].unique().item())
+ angle = params["angle_factor"]
+ direction = params["direction_factor"]
return motion_blur(
input,
kernel_size,
angle,
direction,
- border_type=self.border_type.name.lower(),
- mode=self.resample.name.lower(),
+ border_type=self.flags["border_type"].name.lower(),
+ mode=self.flags["resample"].name.lower(),
)
@@ -1615,6 +1447,12 @@ class RandomSolarize(IntensityAugmentationBase2D):
[0.4394, 0.4923, 0.1129, 0.2594, 0.3844],
[0.3909, 0.2118, 0.1094, 0.2516, 0.3728],
[0.2278, 0.0000, 0.4876, 0.0353, 0.5100]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomSolarize(0.1, 0.1, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -1626,33 +1464,21 @@ class RandomSolarize(IntensityAugmentationBase2D):
p: float = 0.5,
keepdim: bool = False,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
- self._device, self._dtype = _extract_device_dtype([thresholds, additions])
- self.thresholds = thresholds
- self.additions = additions
-
- def __repr__(self) -> str:
- repr = f"thresholds={self.thresholds}, additions={self.additions}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- thresholds = _range_bound(
- self.thresholds, 'thresholds', center=0.5, bounds=(0.0, 1.0), device=self._device, dtype=self._dtype
- )
- additions = _range_bound(
- self.additions, 'additions', bounds=(-0.5, 0.5), device=self._device, dtype=self._dtype
- )
- return rg.random_solarize_generator(
- batch_shape[0], thresholds, additions, self.same_on_batch, self.device, self.dtype
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = cast(
+ rg.PlainUniformGenerator, rg.PlainUniformGenerator(
+ (thresholds, "thresholds", 0.5, (0.0, 1.0)),
+ (additions, "additions", 0., (-0.5, 0.5)),
+ )
)
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- thresholds = params['thresholds_factor']
+ thresholds = params["thresholds"]
additions: Optional[torch.Tensor]
- if 'additions_factor' in params:
- additions = params['additions_factor']
+ if "additions" in params:
+ additions = params["additions"]
else:
additions = None
return solarize(input, thresholds, additions)
@@ -1691,6 +1517,12 @@ class RandomPosterize(IntensityAugmentationBase2D):
[0.3451, 0.3765, 0.0000, 0.1569, 0.2824],
[0.5020, 0.6902, 0.7843, 0.1569, 0.2510],
[0.6588, 0.9098, 0.3765, 0.8471, 0.4078]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomPosterize(3, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -1702,26 +1534,12 @@ class RandomPosterize(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._device, self._dtype = _extract_device_dtype([bits])
- self.bits = bits
-
- def __repr__(self) -> str:
- repr = f"(bits={self.bits}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- bits = torch.as_tensor(self.bits, device=self._device, dtype=self._dtype)
- if len(bits.size()) == 0:
- bits = bits.repeat(2)
- bits[1] = 8
- elif not (len(bits.size()) == 1 and bits.size(0) == 2):
- raise ValueError(f"'bits' shall be either a scalar or a length 2 tensor. Got {bits}.")
- return rg.random_posterize_generator(batch_shape[0], bits, self.same_on_batch, self.device, self.dtype)
+ self._param_generator = cast(rg.PosterizeGenerator, rg.PosterizeGenerator(bits))
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- return posterize(input, params['bits_factor'])
+ return posterize(input, params["bits_factor"])
class RandomSharpness(IntensityAugmentationBase2D):
@@ -1755,6 +1573,12 @@ class RandomSharpness(IntensityAugmentationBase2D):
[0.3489, 0.4428, 0.1562, 0.2443, 0.2939],
[0.5185, 0.6462, 0.7050, 0.2288, 0.2823],
[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomSharpness(1., p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -1766,26 +1590,14 @@ class RandomSharpness(IntensityAugmentationBase2D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._device, self._dtype = _extract_device_dtype([sharpness])
- self.sharpness = sharpness
-
- def __repr__(self) -> str:
- repr = f"sharpness={self.sharpness}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- sharpness = torch.as_tensor(self.sharpness, device=self._device, dtype=self._dtype)
- if sharpness.dim() == 0:
- sharpness = sharpness.repeat(2)
- sharpness[0] = 0.0
- elif not (sharpness.dim() == 1 and sharpness.size(0) == 2):
- raise ValueError(f"'sharpness' must be a scalar or a length 2 tensor. Got {sharpness}.")
- return rg.random_sharpness_generator(batch_shape[0], sharpness, self.same_on_batch, self.device, self.dtype)
+ self._param_generator = cast(rg.PlainUniformGenerator, rg.PlainUniformGenerator(
+ (sharpness, "sharpness", 0., (0, float("inf"))))
+ )
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- factor = params['sharpness_factor']
+ factor = params["sharpness"]
return sharpness(input, factor)
@@ -1820,6 +1632,12 @@ class RandomEqualize(IntensityAugmentationBase2D):
[0.3489, 0.4017, 0.0223, 0.1689, 0.2939],
[0.5185, 0.6977, 0.8000, 0.1610, 0.2823],
[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> aug = RandomEqualize(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -1827,9 +1645,6 @@ class RandomEqualize(IntensityAugmentationBase2D):
) -> None:
super().__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__()})"
-
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
@@ -1868,54 +1683,35 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
[0.3826, 0.2638, 0.1902, 0.1620, 0.2141],
[0.6329, 0.6732, 0.5634, 0.4037, 0.2049],
[0.8307, 0.6753, 0.7147, 0.5768, 0.7097]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
self,
kernel_size: Tuple[int, int],
sigma: Tuple[float, float],
- border_type: str = 'reflect',
+ border_type: str = "reflect",
return_transform: bool = False,
same_on_batch: bool = False,
p: float = 0.5,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0)
- self.kernel_size = kernel_size
- self.sigma = sigma
- self.border_type: BorderType = BorderType.get(border_type)
-
- def __repr__(self) -> str:
- return self.__class__.__name__ + f"({super().__repr__()})"
+ self.flags = dict(
+ kernel_size=kernel_size,
+ sigma=sigma,
+ border_type=BorderType.get(border_type),
+ )
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type.name.lower())
-
-
-class GaussianBlur(RandomGaussianBlur):
- def __init__(
- self,
- kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
- border_type: str = 'reflect',
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- ) -> None:
- super().__init__(
- kernel_size=kernel_size,
- sigma=sigma,
- border_type=border_type,
- return_transform=return_transform,
- same_on_batch=same_on_batch,
- p=p,
- )
- warnings.warn(
- "GaussianBlur is no longer maintained and will be removed from the future versions. "
- "Please use RandomGaussianBlur instead.",
- category=DeprecationWarning,
- )
+ return gaussian_blur2d(
+ input, self.flags["kernel_size"], self.flags["sigma"], self.flags["border_type"].name.lower())
class RandomInvert(IntensityAugmentationBase2D):
@@ -1944,6 +1740,12 @@ class RandomInvert(IntensityAugmentationBase2D):
[0.3489, 0.4017, 0.0223, 0.1689, 0.2939],
[0.5185, 0.6977, 0.8000, 0.1610, 0.2823],
[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomInvert(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -1954,15 +1756,14 @@ class RandomInvert(IntensityAugmentationBase2D):
p: float = 0.5,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0)
- self.max_val = max_val
-
- def __repr__(self) -> str:
- return self.__class__.__name__ + f"({super().__repr__()})"
+ self.flags = dict(
+ max_val=max_val,
+ )
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- return invert(input, torch.as_tensor(self.max_val, device=input.device, dtype=input.dtype))
+ return invert(input, torch.as_tensor(self.flags["max_val"], device=input.device, dtype=input.dtype))
class RandomChannelShuffle(IntensityAugmentationBase2D):
@@ -1985,14 +1786,17 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
<BLANKLINE>
[[0., 1.],
[2., 3.]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomChannelShuffle(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0)
- def __repr__(self) -> str:
- return self.__class__.__name__ + f"({super().__repr__()})"
-
def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
B, C, _, _ = shape
channels = torch.rand(B, C).argsort(dim=1)
@@ -2003,7 +1807,7 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
) -> torch.Tensor:
out = torch.empty_like(input)
for i in range(out.shape[0]):
- out[i] = input[i, params['channels'][i]]
+ out[i] = input[i, params["channels"][i]]
return out
@@ -2026,6 +1830,12 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
>>> RandomGaussianNoise(mean=0., std=1., p=1.)(img)
tensor([[[[ 2.5410, 0.7066],
[-1.1788, 1.5684]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomGaussianNoise(mean=0., std=1., p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -2037,11 +1847,7 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
p: float = 0.5,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0)
- self.mean = mean
- self.std = std
-
- def __repr__(self) -> str:
- return self.__class__.__name__ + f"({super().__repr__()})"
+ self.flags = dict(mean=mean, std=std)
def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
noise = torch.randn(shape)
@@ -2050,7 +1856,7 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- return input + params['noise'].to(input.device) * self.std + self.mean
+ return input + params["noise"].to(input.device) * self.flags["std"] + self.flags["mean"]
class RandomFisheye(GeometricAugmentationBase2D):
@@ -2075,6 +1881,12 @@ class RandomFisheye(GeometricAugmentationBase2D):
>>> out = RandomFisheye(center_x, center_y, gamma)(img)
>>> out.shape
torch.Size([1, 1, 2, 2])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomFisheye(center_x, center_y, gamma, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -2087,29 +1899,24 @@ class RandomFisheye(GeometricAugmentationBase2D):
p: float = 0.5,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0)
- self.center_x = self._check_tensor(center_x)
- self.center_y = self._check_tensor(center_y)
- self.gamma = self._check_tensor(gamma)
- self.dist = torch.distributions.Uniform
-
- def __repr__(self) -> str:
- return self.__class__.__name__ + f"({super().__repr__()})"
+ self._check_tensor(center_x)
+ self._check_tensor(center_y)
+ self._check_tensor(gamma)
+ self._param_generator = cast(
+ rg.PlainUniformGenerator, rg.PlainUniformGenerator(
+ (center_x[:, None], "center_x", None, None),
+ (center_y[:, None], "center_y", None, None),
+ (gamma[:, None], "gamma", None, None),
+ )
+ )
- def _check_tensor(self, data: torch.Tensor) -> torch.Tensor:
+ def _check_tensor(self, data: torch.Tensor) -> None:
if not isinstance(data, torch.Tensor):
raise TypeError(f"Invalid input type. Expected torch.Tensor - got: {type(data)}")
if len(data.shape) != 1 and data.shape[0] != 2:
raise ValueError(f"Tensor must be of shape (2,). Got: {data.shape}.")
- return data
-
- def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
- center_x = self.dist(self.center_x[:1], self.center_x[1:]).rsample(shape[:1])
- center_y = self.dist(self.center_y[:1], self.center_y[1:]).rsample(shape[:1])
- gamma = self.dist(self.gamma[:1], self.gamma[1:]).rsample(shape[:1])
- return dict(center_x=center_x, center_y=center_y, gamma=gamma)
-
# TODO: It is incorrect to return identity
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return self.identity_matrix(input)
@@ -2123,9 +1930,9 @@ class RandomFisheye(GeometricAugmentationBase2D):
field_x = grid[..., 0].to(input) # 1xHxW
field_y = grid[..., 1].to(input) # 1xHxW
# vectorize the random parameters
- center_x = params['center_x'].view(B, 1, 1).to(input)
- center_y = params['center_y'].view(B, 1, 1).to(input)
- gamma = params['gamma'].view(B, 1, 1).to(input)
+ center_x = params["center_x"].view(B, 1, 1).to(input)
+ center_y = params["center_y"].view(B, 1, 1).to(input)
+ gamma = params["gamma"].view(B, 1, 1).to(input)
# compute and apply the distances respect to the camera optical center
distance = ((center_x - field_x) ** 2 + (center_y - field_y) ** 2) ** 0.5
field_x = field_x + field_x * distance ** gamma # BxHxw
@@ -2161,6 +1968,12 @@ class RandomElasticTransform(GeometricAugmentationBase2D):
>>> out = RandomElasticTransform()(img)
>>> out.shape
torch.Size([1, 1, 2, 2])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomElasticTransform(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -2169,22 +1982,21 @@ class RandomElasticTransform(GeometricAugmentationBase2D):
sigma: Tuple[float, float] = (32.0, 32.0),
alpha: Tuple[float, float] = (1.0, 1.0),
align_corners: bool = False,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
return_transform: bool = False,
same_on_batch: bool = False,
p: float = 0.5,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0)
- self.kernel_size = kernel_size
- self.sigma = sigma
- self.alpha = alpha
- self.align_corners = align_corners
- self.mode = mode
- self.padding_mode = padding_mode
-
- def __repr__(self) -> str:
- return self.__class__.__name__ + f"({super().__repr__()})"
+ self.flags = dict(
+ kernel_size=kernel_size,
+ sigma=sigma,
+ alpha=alpha,
+ align_corners=align_corners,
+ mode=mode,
+ padding_mode=padding_mode,
+ )
def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
B, _, H, W = shape
@@ -2202,8 +2014,8 @@ class RandomElasticTransform(GeometricAugmentationBase2D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return elastic_transform2d(
- input, params['noise'].to(input), self.kernel_size, self.sigma, self.alpha, self.align_corners, self.mode,
- self.padding_mode
+ input, params["noise"].to(input), self.flags["kernel_size"], self.flags["sigma"],
+ self.flags["alpha"], self.flags["align_corners"], self.flags["mode"], self.flags["padding_mode"]
)
@@ -2229,6 +2041,12 @@ class RandomThinPlateSpline(GeometricAugmentationBase2D):
>>> out = RandomThinPlateSpline()(img)
>>> out.shape
torch.Size([1, 1, 2, 2])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomThinPlateSpline(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -2240,7 +2058,7 @@ class RandomThinPlateSpline(GeometricAugmentationBase2D):
p: float = 0.5,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0)
- self.align_corners = align_corners
+ self.flags = dict(align_corners=align_corners)
self.dist = torch.distributions.Uniform(-scale, scale)
def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
@@ -2256,11 +2074,11 @@ class RandomThinPlateSpline(GeometricAugmentationBase2D):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- src = params['src'].to(input)
- dst = params['dst'].to(input)
+ src = params["src"].to(input)
+ dst = params["dst"].to(input)
# NOTE: warp_image_tps need to use inverse parameters
kernel, affine = get_tps_transform(dst, src)
- return warp_image_tps(input, src, kernel, affine, self.align_corners)
+ return warp_image_tps(input, src, kernel, affine, self.flags["align_corners"])
class RandomBoxBlur(IntensityAugmentationBase2D):
@@ -2286,21 +2104,29 @@ class RandomBoxBlur(IntensityAugmentationBase2D):
>>> out = RandomBoxBlur((7, 7))(img)
>>> out.shape
torch.Size([1, 1, 24, 24])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomBoxBlur((7, 7), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
self,
kernel_size: Tuple[int, int] = (3, 3),
- border_type: str = 'reflect',
+ border_type: str = "reflect",
normalized: bool = True,
return_transform: bool = False,
same_on_batch: bool = False,
p: float = 0.5,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0)
- self.kernel_size = kernel_size
- self.border_type = border_type
- self.normalized = normalized
+ self.flags = dict(
+ kernel_size=kernel_size,
+ border_type=border_type,
+ normalized=normalized,
+ )
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return self.identity_matrix(input)
@@ -2308,7 +2134,7 @@ class RandomBoxBlur(IntensityAugmentationBase2D):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- return box_blur(input, self.kernel_size, self.border_type, self.normalized)
+ return box_blur(input, self.flags["kernel_size"], self.flags["border_type"], self.flags["normalized"])
class PadTo(GeometricAugmentationBase2D):
@@ -2359,16 +2185,11 @@ class PadTo(GeometricAugmentationBase2D):
return_transform: bool = False,
) -> None:
super().__init__(p=1., return_transform=return_transform, same_on_batch=True, p_batch=1.)
- self.size = size
- self.pad_mode = pad_mode
- self.pad_value = pad_value
-
- def __repr__(self) -> str:
- return self.__class__.__name__ + f"({super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- input_size = torch.tensor(batch_shape[-2:], dtype=torch.long).expand(batch_shape[0], -1)
- return dict(input_size=input_size)
+ self.flags = dict(
+ size=size,
+ pad_mode=pad_mode,
+ pad_value=pad_value,
+ )
# TODO: It is incorrect to return identity
# TODO: Having a resampled version with ``warp_affine``
@@ -2379,10 +2200,10 @@ class PadTo(GeometricAugmentationBase2D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
_, _, height, width = input.shape
- height_pad: int = self.size[0] - height
- width_pad: int = self.size[1] - width
+ height_pad: int = self.flags["size"][0] - height
+ width_pad: int = self.flags["size"][1] - width
return torch.nn.functional.pad(
- input, [0, width_pad, 0, height_pad], mode=self.pad_mode, value=self.pad_value)
+ input, [0, width_pad, 0, height_pad], mode=self.flags["pad_mode"], value=self.flags["pad_value"])
def inverse_transform(
self,
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index 01738cd84..bad2d007e 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -16,11 +16,9 @@ from kornia.geometry import (
warp_perspective3d,
)
from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compute_tensor_center3d
-from kornia.utils import _extract_device_dtype
from . import random_generator as rg
from .base import AugmentationBase3D, TensorWithTransformMat
-from .utils import _range_bound, _singular_range_check, _tuple_range_reader
class RandomHorizontalFlip3D(AugmentationBase3D):
@@ -62,6 +60,12 @@ class RandomHorizontalFlip3D(AugmentationBase3D):
[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]]]))
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomHorizontalFlip3D(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -69,14 +73,8 @@ class RandomHorizontalFlip3D(AugmentationBase3D):
) -> None:
super().__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__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return dict(batch_shape=torch.as_tensor(batch_shape))
-
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- w: int = cast(int, params['batch_shape'][-1])
+ w: int = input.shape[-1]
flip_mat: torch.Tensor = torch.tensor(
[[-1, 0, 0, w - 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
)
@@ -133,6 +131,12 @@ class RandomVerticalFlip3D(AugmentationBase3D):
[ 0., -1., 0., 2.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.]]]))
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomVerticalFlip3D(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -140,14 +144,8 @@ class RandomVerticalFlip3D(AugmentationBase3D):
) -> None:
super().__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__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return dict(batch_shape=torch.as_tensor(batch_shape))
-
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- h: int = cast(int, params['batch_shape'][-2])
+ h: int = input.shape[-2]
flip_mat: torch.Tensor = torch.tensor(
[[1, 0, 0, 0], [0, -1, 0, h - 1], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
)
@@ -205,6 +203,12 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
[ 0., 0., -1., 2.],
[ 0., 0., 0., 1.]]]))
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomDepthicalFlip3D(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+
"""
def __init__(
@@ -212,9 +216,6 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
) -> None:
super().__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__()})"
-
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
d: int = input.shape[-3]
flip_mat: torch.Tensor = torch.tensor(
@@ -243,7 +244,7 @@ class RandomAffine3D(AugmentationBase3D):
(a, b), (m, n) and (x, y).
Set to 0 to deactivate rotations.
translate: tuple of maximum absolute fraction for horizontal, vertical and
- depthical translations (dx,dy,dz). For example translate=(a, b, c), then
+ depthical translations (dx,dy,dz). For example translate=(a, b, c), then
horizontal shift will be randomly sampled in the range -img_width * a < dx < img_width * a
vertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b.
depthical shift will be randomly sampled in the range -img_depth * c < dz < img_depth * c.
@@ -295,6 +296,12 @@ class RandomAffine3D(AugmentationBase3D):
[ 0.1131, 0.9669, -0.2286, 0.1486],
[-0.2049, 0.2478, 0.9469, 0.0102],
[ 0.0000, 0.0000, 0.0000, 1.0000]]]))
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomAffine3D((15., 20., 20.), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -334,74 +341,29 @@ class RandomAffine3D(AugmentationBase3D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._device, self._dtype = _extract_device_dtype([degrees, shears, translate, scale])
self.degrees = degrees
self.shears = shears
self.translate = translate
self.scale = scale
- self.resample = Resample.get(resample)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- resample=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
- )
-
- def __repr__(self) -> str:
- repr = (
- f"(degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shears}, "
- f"resample={self.resample.name}, align_corners={self.align_corners}"
- )
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- degrees = _tuple_range_reader(self.degrees, 3, self._device, self._dtype)
- shear: Optional[torch.Tensor] = None
- if self.shears is not None:
- shear = _tuple_range_reader(self.shears, 6, self._device, self._dtype)
-
- # check translation range
- translate: Optional[torch.Tensor] = None
- if self.translate is not None:
- translate = torch.as_tensor(self.translate, device=self._device, dtype=self._dtype)
- _singular_range_check(translate, 'translate', bounds=(0, 1), mode='3d')
-
- # check scale range
- scale: Optional[torch.Tensor] = None
- if self.scale is not None:
- scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)
- if scale.shape == torch.Size([2]):
- scale = scale.unsqueeze(0).repeat(3, 1)
- elif scale.shape != torch.Size([3, 2]):
- raise ValueError(f"'scale' shall be either shape (2) or (3, 2). Got {self.scale}.")
- _singular_range_check(scale[0], 'scale-x', bounds=(0, float('inf')), mode='2d')
- _singular_range_check(scale[1], 'scale-y', bounds=(0, float('inf')), mode='2d')
- _singular_range_check(scale[2], 'scale-z', bounds=(0, float('inf')), mode='2d')
- return rg.random_affine_generator3d(
- batch_shape[0],
- batch_shape[-3],
- batch_shape[-2],
- batch_shape[-1],
- degrees,
- translate,
- scale,
- shear,
- self.same_on_batch,
- self.device,
- self.dtype,
+ self.flags = dict(
+ resample=Resample.get(resample),
+ align_corners=align_corners
)
+ self._param_generator = cast(rg.AffineGenerator3D, rg.AffineGenerator3D(degrees, translate, scale, shears))
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
transform: torch.Tensor = get_affine_matrix3d(
- params['translations'],
- params['center'],
- params['scale'],
- params['angles'],
- deg2rad(params['sxy']),
- deg2rad(params['sxz']),
- deg2rad(params['syx']),
- deg2rad(params['syz']),
- deg2rad(params['szx']),
- deg2rad(params['szy']),
+ params["translations"],
+ params["center"],
+ params["scale"],
+ params["angles"],
+ deg2rad(params["sxy"]),
+ deg2rad(params["sxz"]),
+ deg2rad(params["syx"]),
+ deg2rad(params["syz"]),
+ deg2rad(params["szx"]),
+ deg2rad(params["szy"]),
).to(input)
return transform
@@ -413,8 +375,8 @@ class RandomAffine3D(AugmentationBase3D):
input,
transform[:, :3, :],
(input.shape[-3], input.shape[-2], input.shape[-1]),
- self.resample.name.lower(),
- align_corners=self.align_corners,
+ self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"],
)
@@ -472,6 +434,12 @@ class RandomRotation3D(AugmentationBase3D):
[-0.0603, 0.9669, 0.2478, -0.1545],
[ 0.2262, -0.2286, 0.9469, 0.0556],
[ 0.0000, 0.0000, 0.0000, 1.0000]]]))
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomRotation3D((15., 20., 20.), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -490,21 +458,11 @@ class RandomRotation3D(AugmentationBase3D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._device, self._dtype = _extract_device_dtype([degrees])
- self.degrees = degrees
- self.resample = Resample.get(resample)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- resample=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
+ self.flags = dict(
+ resample=Resample.get(resample),
+ align_corners=align_corners
)
-
- def __repr__(self) -> str:
- repr = f"degrees={self.degrees}, resample={self.resample.name}, align_corners={self.align_corners}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- degrees = _tuple_range_reader(self.degrees, 3, self._device, self._dtype)
- return rg.random_rotation_generator3d(batch_shape[0], degrees, self.same_on_batch, self.device, self.dtype)
+ self._param_generator = cast(rg.RotationGenerator3D, rg.RotationGenerator3D(degrees))
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
yaw: torch.Tensor = params["yaw"].to(input)
@@ -526,7 +484,9 @@ class RandomRotation3D(AugmentationBase3D):
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
transform = cast(torch.Tensor, transform)
- return affine3d(input, transform[..., :3, :4], self.resample.name.lower(), 'zeros', self.align_corners)
+ return affine3d(
+ input, transform[..., :3, :4], self.flags["resample"].name.lower(), "zeros", self.flags["align_corners"]
+ )
class RandomMotionBlur3D(AugmentationBase3D):
@@ -587,6 +547,12 @@ class RandomMotionBlur3D(AugmentationBase3D):
[0.4307, 0.4217, 0.2977, 0.5086, 0.5406],
[0.3686, 0.2778, 0.5228, 0.7592, 0.6455],
[0.2033, 0.3014, 0.4898, 0.6164, 0.3117]]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomMotionBlur3D(3, 35., 0.5, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -609,32 +575,11 @@ class RandomMotionBlur3D(AugmentationBase3D):
super().__init__(
p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
)
- self._device, self._dtype = _extract_device_dtype([angle, direction])
- self.kernel_size: Union[int, Tuple[int, int]] = kernel_size
- self.angle = angle
- self.direction = direction
- self.resample = Resample.get(resample)
- self.border_type = BorderType.get(border_type)
- self.flags: Dict[str, torch.Tensor] = {
- "border_type": torch.tensor(self.border_type.value),
- "interpolation": torch.tensor(self.resample.value),
- }
-
- def __repr__(self) -> str:
- repr = (
- f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}, "
- + f"border_type='{self.border_type.name.lower()}'"
- )
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- angle: torch.Tensor = _tuple_range_reader(self.angle, 3, self._device, self._dtype)
- direction = _range_bound(
- self.direction, 'direction', center=0.0, bounds=(-1, 1), device=self._device, dtype=self._dtype
- )
- return rg.random_motion_blur_generator3d(
- batch_shape[0], self.kernel_size, angle, direction, self.same_on_batch, self.device, self.dtype
+ self.flags = dict(
+ border_type=BorderType.get(border_type),
+ resample=Resample.get(resample),
)
+ self._param_generator = cast(rg.MotionBlurGenerator3D, rg.MotionBlurGenerator3D(kernel_size, angle, direction))
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return self.identity_matrix(input)
@@ -642,11 +587,12 @@ class RandomMotionBlur3D(AugmentationBase3D):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
- kernel_size: int = cast(int, params['ksize_factor'].unique().item())
- angle = params['angle_factor']
- direction = params['direction_factor']
+ kernel_size: int = cast(int, params["ksize_factor"].unique().item())
+ angle = params["angle_factor"]
+ direction = params["direction_factor"]
return motion_blur3d(
- input, kernel_size, angle, direction, self.border_type.name.lower(), self.resample.name.lower()
+ input, kernel_size, angle, direction, self.flags["border_type"].name.lower(),
+ self.flags["resample"].name.lower()
)
@@ -694,6 +640,12 @@ class CenterCrop3D(AugmentationBase3D):
<BLANKLINE>
[[-0.6136, 0.0316],
[ 0.6408, 0.4412]]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = CenterCrop3D(24, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -709,28 +661,24 @@ class CenterCrop3D(AugmentationBase3D):
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
super().__init__(p=1.0, return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
if isinstance(size, tuple):
- self.size = (size[0], size[1], size[2])
+ size = (size[0], size[1], size[2])
elif isinstance(size, int):
- self.size = (size, size, size)
+ size = (size, size, size)
else:
raise Exception(f"Invalid size type. Expected (int, tuple(int, int int). Got: {size}.")
- self.resample = Resample.get(resample)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
+ self.flags = dict(
+ size=size,
+ align_corners=align_corners,
+ resample=Resample.get(resample),
)
- def __repr__(self) -> str:
- repr = f"size={self.size}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.center_crop_generator3d(
- batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.size, device=self.device
+ batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.flags["size"], device=self.device
)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform3d(params['src'].to(input), params['dst'].to(input))
+ transform: torch.Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
@@ -739,7 +687,8 @@ class CenterCrop3D(AugmentationBase3D):
) -> torch.Tensor:
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat3d(
- input, transform, self.size, mode=self.resample.name.lower(), align_corners=self.align_corners
+ input, transform, self.flags["size"], mode=self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"]
)
@@ -791,6 +740,12 @@ class RandomCrop3D(AugmentationBase3D):
<BLANKLINE>
[[-1.2633, 0.3500],
[ 0.1665, 0.8744]]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomCrop3D((24, 24, 24), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -799,7 +754,7 @@ 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',
+ padding_mode: str = "constant",
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
return_transform: bool = False,
same_on_batch: bool = False,
@@ -811,76 +766,46 @@ class RandomCrop3D(AugmentationBase3D):
super().__init__(
p=1.0, 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
- self.fill = fill
- self.padding_mode = padding_mode
- self.resample = Resample.get(resample)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
- )
-
- def __repr__(self) -> str:
- repr = (
- f"crop_size={self.size}, padding={self.padding}, fill={self.fill}, pad_if_needed={self.pad_if_needed}, "
- f"padding_mode={self.padding_mode}, resample={self.resample.name}"
- )
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.random_crop_generator3d(
- batch_shape[0],
- (batch_shape[-3], batch_shape[-2], batch_shape[-1]),
- self.size,
- same_on_batch=self.same_on_batch,
- device=self.device,
- dtype=self.dtype,
+ self.flags = dict(
+ size=size,
+ padding=padding,
+ pad_if_needed=pad_if_needed,
+ padding_mode=padding_mode,
+ fill=fill,
+ resample=Resample.get(resample),
+ align_corners=align_corners,
)
+ self._param_generator = cast(rg.CropGenerator3D, rg.CropGenerator3D(size, None))
def precrop_padding(self, input: torch.Tensor) -> torch.Tensor:
- if self.padding is not None:
- if isinstance(self.padding, int):
- padding = [self.padding, self.padding, self.padding, self.padding, self.padding, self.padding]
- elif isinstance(self.padding, (tuple, list)) and len(self.padding) == 3:
- padding = [
- self.padding[0],
- self.padding[0],
- self.padding[1],
- self.padding[1],
- self.padding[2],
- self.padding[2],
- ]
- elif isinstance(self.padding, (tuple, list)) and len(self.padding) == 6:
- padding = [
- self.padding[0],
- self.padding[1],
- self.padding[2],
- self.padding[3], # type: ignore
- self.padding[4], # type: ignore
- self.padding[5], # type: ignore
- ]
+ padding = self.flags["padding"]
+ if padding is not None:
+ if isinstance(padding, int):
+ padding = [padding, padding, padding, padding, padding, padding]
+ elif isinstance(padding, (tuple, list)) and len(padding) == 3:
+ padding = [padding[0], padding[0], padding[1], padding[1], padding[2], padding[2]]
+ elif isinstance(padding, (tuple, list)) and len(padding) == 6:
+ padding = [padding[0], padding[1], padding[2], padding[3], padding[4], padding[5]] # type: ignore
else:
- raise ValueError(f"`padding` must be an integer, 3-element-list or 6-element-list. Got {self.padding}.")
- input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+ raise ValueError(f"`padding` must be an integer, 3-element-list or 6-element-list. Got {padding}.")
+ input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
- if self.pad_if_needed and input.shape[-3] < self.size[0]:
- padding = [0, 0, 0, 0, self.size[0] - input.shape[-3], self.size[0] - input.shape[-3]]
- input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+ if self.flags["pad_if_needed"] and input.shape[-3] < self.flags["size"][0]:
+ padding = [0, 0, 0, 0, self.flags["size"][0] - input.shape[-3], self.flags["size"][0] - input.shape[-3]]
+ input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
- if self.pad_if_needed and input.shape[-2] < self.size[1]:
- padding = [0, 0, (self.size[1] - input.shape[-2]), self.size[1] - input.shape[-2], 0, 0]
- input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+ if self.flags["pad_if_needed"] and input.shape[-2] < self.flags["size"][1]:
+ padding = [0, 0, (self.flags["size"][1] - input.shape[-2]), self.flags["size"][1] - input.shape[-2], 0, 0]
+ input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
- if self.pad_if_needed and input.shape[-1] < self.size[2]:
- padding = [self.size[2] - input.shape[-1], self.size[2] - input.shape[-1], 0, 0, 0, 0]
- input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+ if self.flags["pad_if_needed"] and input.shape[-1] < self.flags["size"][2]:
+ padding = [self.flags["size"][2] - input.shape[-1], self.flags["size"][2] - input.shape[-1], 0, 0, 0, 0]
+ input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
return input
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform3d(params['src'].to(input), params['dst'].to(input))
+ transform: torch.Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
@@ -889,7 +814,8 @@ class RandomCrop3D(AugmentationBase3D):
) -> torch.Tensor:
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat3d(
- input, transform, self.size, mode=self.resample.name.lower(), align_corners=self.align_corners
+ input, transform, self.flags["size"], mode=self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"]
)
def forward( # type: ignore
@@ -953,6 +879,12 @@ class RandomPerspective3D(AugmentationBase3D):
[[0.0000, 0.1153, 0.0000],
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000]]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomPerspective3D(0.5, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -966,36 +898,14 @@ class RandomPerspective3D(AugmentationBase3D):
keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._device, self._dtype = _extract_device_dtype([distortion_scale])
- self.distortion_scale = distortion_scale
- self.resample = Resample.get(resample)
- self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
- )
-
- def __repr__(self) -> str:
- repr = (
- f"distortion_scale={self.distortion_scale}, resample={self.resample.name}, "
- f"align_corners={self.align_corners}"
- )
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- distortion_scale = torch.as_tensor(self.distortion_scale, device=self._device, dtype=self._dtype)
- return rg.random_perspective_generator3d(
- batch_shape[0],
- batch_shape[-3],
- batch_shape[-2],
- batch_shape[-1],
- distortion_scale,
- self.same_on_batch,
- self.device,
- self.dtype,
+ self.flags = dict(
+ resample=Resample.get(resample),
+ align_corners=align_corners,
)
+ self._param_generator = cast(rg.PerspectiveGenerator3D, rg.PerspectiveGenerator3D(distortion_scale))
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return get_perspective_transform3d(params['start_points'], params['end_points']).to(input)
+ return get_perspective_transform3d(params["start_points"], params["end_points"]).to(input)
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
@@ -1005,8 +915,8 @@ class RandomPerspective3D(AugmentationBase3D):
input,
transform,
(input.shape[-3], input.shape[-2], input.shape[-1]),
- flags=self.resample.name.lower(),
- align_corners=self.align_corners,
+ flags=self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"],
)
@@ -1046,6 +956,12 @@ class RandomEqualize3D(AugmentationBase3D):
[[0.1610, 0.2823, 0.6816],
[0.9152, 0.3971, 0.8742],
[0.4194, 0.5529, 0.9527]]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomEqualize3D(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
"""
def __init__(
@@ -1053,9 +969,6 @@ class RandomEqualize3D(AugmentationBase3D):
) -> None:
super().__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__()})"
-
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return self.identity_matrix(input)
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index ba1c759c6..9d3497c83 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -1,5 +1,6 @@
import warnings
-from typing import cast, Dict, Optional, Tuple, Union
+from enum import Enum
+from typing import Any, cast, Dict, Optional, Tuple, Union
import torch
import torch.nn as nn
@@ -8,6 +9,7 @@ from torch.distributions import Bernoulli
import kornia
from kornia.utils.helpers import _torch_inverse_cast
+from .random_generator import RandomGeneratorBase
from .utils import (
_adapted_sampling,
_transform_input,
@@ -26,6 +28,11 @@ class _BasicAugmentationBase(nn.Module):
By default, the random computations will be happened on CPU with ``torch.get_default_dtype()``.
To change this behaviour, please use ``set_rng_device_and_dtype``.
+ For automatically generating the corresponding ``__repr__`` with full customized parameters, you may need to
+ implement ``_param_generator`` by inheriting ``RandomGeneratorBase`` for generating random parameters and
+ put all static parameters inside ``self.flags``. You may take the advantage of ``PlainUniformGenerator`` to
+ generate simple uniform parameters with less boilerplate code.
+
Args:
p: probability for applying an augmentation. This param controls the augmentation probabilities element-wise.
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
@@ -48,10 +55,20 @@ class _BasicAugmentationBase(nn.Module):
self._p_gen = Bernoulli(self.p)
if p_batch != 0.0 or p_batch != 1.0:
self._p_batch_gen = Bernoulli(self.p_batch)
+ self._param_generator: Optional[RandomGeneratorBase] = None
+ self.flags: Dict[str, Any] = {}
self.set_rng_device_and_dtype(torch.device('cpu'), torch.get_default_dtype())
def __repr__(self) -> str:
- return f"p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}"
+ txt = f"p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}"
+ if isinstance(self._param_generator, RandomGeneratorBase):
+ txt = f"{str(self._param_generator)}, {txt}"
+ for k, v in self.flags.items():
+ if isinstance(v, Enum):
+ txt += f", {k}={v.name.lower()}"
+ else:
+ txt += f", {k}={v}"
+ return f"{self.__class__.__name__}({txt})"
def __unpack_input__(self, input: torch.Tensor) -> torch.Tensor:
return input
@@ -65,6 +82,8 @@ class _BasicAugmentationBase(nn.Module):
raise NotImplementedError
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ if self._param_generator is not None:
+ return self._param_generator(batch_shape, self.same_on_batch)
return {}
def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
@@ -78,6 +97,8 @@ class _BasicAugmentationBase(nn.Module):
"""
self.device = device
self.dtype = dtype
+ if self._param_generator is not None:
+ self._param_generator.set_rng_device_and_dtype(device, dtype)
def __batch_prob_generator__(
self, batch_shape: torch.Size, p: float, p_batch: float, same_on_batch: bool
@@ -109,6 +130,10 @@ class _BasicAugmentationBase(nn.Module):
if _params is None:
_params = {}
_params['batch_prob'] = to_apply
+ # Added another input_size parameter for geometric transformations
+ # This might be needed for correctly inversing.
+ input_size = torch.tensor(batch_shape, dtype=torch.long)
+ _params.update({'forward_input_shape': input_size})
return _params
def apply_func(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> TensorWithTransformMat:
@@ -137,7 +162,7 @@ class _AugmentationBase(_BasicAugmentationBase):
Advanced augmentation base class with the functionality of transformation matrix calculations.
Args:
- pprobability for applying an augmentation. This param controls the augmentation probabilities
+ p: probability for applying an augmentation. This param controls the augmentation probabilities
element-wise for a batch.
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wise.
@@ -162,7 +187,7 @@ class _AugmentationBase(_BasicAugmentationBase):
self.return_transform = return_transform
def __repr__(self) -> str:
- return super().__repr__() + f", return_transform={self.return_transform}"
+ return self.__class__.__name__ + f"({super().__repr__()}, return_transform={self.return_transform})"
def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@@ -348,7 +373,7 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None
) -> torch.Tensor:
if params is not None:
- transform = self.compute_transformation(input, params)
+ transform = self.compute_transformation(input[params['batch_prob']], params)
elif not hasattr(self, "_transform_matrix"):
params = self.forward_parameters(input.shape)
transform = self.identity_matrix(input)
@@ -377,10 +402,10 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
batch_shape = input.shape
if params is None:
params = self._params
- if size is None and "input_size" in params:
+ if size is None and "forward_input_shape" in params:
# Majorly for cropping functions
- size = params['input_size'].unique(dim=0).squeeze().numpy().tolist()
- size = (size[0], size[1])
+ size = params['forward_input_shape'].numpy().tolist()
+ size = (size[-2], size[-1])
if 'batch_prob' not in params:
params['batch_prob'] = torch.tensor([True] * batch_shape[0])
warnings.warn("`batch_prob` is not found in params. Will assume applying on all data.")
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 8eb7625fe..ffb0fe216 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -76,6 +76,11 @@ class AugmentationSequential(ImageSequential):
>>> out = aug_list(input, input, bbox, points)
>>> [o.shape for o in out]
[torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 5, 6]), torch.Size([2, 4, 2]), torch.Size([2, 1, 2])]
+ >>> # apply the exact augmentation again.
+ >>> out_rep = aug_list(input, input, bbox, points, params=aug_list._params)
+ >>> [(o == o_rep).all() for o, o_rep in zip(out, out_rep)]
+ [tensor(True), tensor(True), tensor(True), tensor(True)]
+ >>> # inverse the augmentations
>>> out_inv = aug_list.inverse(*out)
>>> [o.shape for o in out_inv]
[torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 5, 6]), torch.Size([2, 4, 2]), torch.Size([2, 1, 2])]
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 5aaa8e813..799363126 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -96,7 +96,7 @@ class ImageSequential(SequentialBase):
keepdim: Optional[bool] = None,
random_apply: Union[int, bool, Tuple[int, int]] = False,
random_apply_weights: Optional[List[float]] = None,
- if_unsupported_ops: str = 'raise'
+ if_unsupported_ops: str = "raise"
) -> None:
super().__init__(*args, same_on_batch=same_on_batch, return_transform=return_transform, keepdim=keepdim)
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index 88bbd6214..bf0c2b0b8 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -161,7 +161,7 @@ class PatchSequential(ImageSequential):
if padding == "valid":
ph, pw = input.size(-2) // grid_size[0], input.size(-1) // grid_size[1]
return (-pw // 2, pw // 2 - pw, -ph // 2, ph // 2 - ph)
- if padding == 'same':
+ if padding == "same":
ph = input.size(-2) - input.size(-2) // grid_size[0] * grid_size[0]
pw = input.size(-1) - input.size(-1) // grid_size[1] * grid_size[1]
return (pw // 2, pw - pw // 2, ph // 2, ph - ph // 2)
diff --git a/kornia/augmentation/mix_augmentation.py b/kornia/augmentation/mix_augmentation.py
index fb160cca7..53da1054b 100644
--- a/kornia/augmentation/mix_augmentation.py
+++ b/kornia/augmentation/mix_augmentation.py
@@ -1,3 +1,4 @@
+import warnings
from typing import cast, Dict, Optional, Tuple, Union
import torch
@@ -86,36 +87,21 @@ class RandomMixUp(MixAugmentationBase):
keepdim: bool = False,
) -> None:
super().__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.lambda_val = lambda_val
-
- def __repr__(self) -> str:
- repr = f"lambda_val={self.lambda_val}"
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- if self.lambda_val is None:
- lambda_val = torch.tensor([0.0, 1.0], device=self.device, dtype=self.dtype)
- else:
- lambda_val = (
- cast(torch.Tensor, self.lambda_val)
- if isinstance(self.lambda_val, torch.Tensor)
- else torch.tensor(self.lambda_val, device=self.device, dtype=self.dtype)
- )
- return rg.random_mixup_generator(batch_shape[0], self.p, lambda_val, same_on_batch=self.same_on_batch)
+ self._param_generator = cast(rg.MixupGenerator, rg.MixupGenerator(lambda_val, p=p))
def apply_transform( # type: ignore
self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]
) -> Tuple[torch.Tensor, torch.Tensor]:
- input_permute = input.index_select(dim=0, index=params['mixup_pairs'].to(input.device))
- labels_permute = label.index_select(dim=0, index=params['mixup_pairs'].to(label.device))
+ input_permute = input.index_select(dim=0, index=params["mixup_pairs"].to(input.device))
+ labels_permute = label.index_select(dim=0, index=params["mixup_pairs"].to(label.device))
- lam = params['mixup_lambdas'].view(-1, 1, 1, 1).expand_as(input).to(label.device)
+ lam = params["mixup_lambdas"].view(-1, 1, 1, 1).expand_as(input).to(label.device)
inputs = input * (1 - lam) + input_permute * lam
out_labels = torch.stack(
[
label.to(input.dtype),
labels_permute.to(input.dtype),
- params['mixup_lambdas'].to(label.device, input.dtype),
+ params["mixup_lambdas"].to(label.device, input.dtype),
],
dim=-1,
).to(label.device)
@@ -188,7 +174,7 @@ class RandomCutMix(MixAugmentationBase):
>>> input = torch.rand(2, 1, 3, 3)
>>> input[0] = torch.ones((1, 3, 3))
>>> label = torch.tensor([0, 1])
- >>> cutmix = RandomCutMix(3, 3)
+ >>> cutmix = RandomCutMix()
>>> cutmix(input, label)
(tensor([[[[0.8879, 0.4510, 1.0000],
[0.1498, 0.4015, 1.0000],
@@ -203,8 +189,8 @@ class RandomCutMix(MixAugmentationBase):
def __init__(
self,
- height: int,
- width: int,
+ height: Optional[int] = None,
+ width: Optional[int] = None,
num_mix: int = 1,
cut_size: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
beta: Optional[Union[torch.Tensor, float]] = None,
@@ -213,60 +199,27 @@ class RandomCutMix(MixAugmentationBase):
keepdim: bool = False,
) -> None:
super().__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self.height = height
- self.width = width
- self.num_mix = num_mix
- self.beta = beta
- self.cut_size = cut_size
-
- def __repr__(self) -> str:
- repr = (
- f"num_mix={self.num_mix}, beta={self.beta}, cut_size={self.cut_size}, "
- f"height={self.height}, width={self.width}"
- )
- return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- if self.beta is None:
- beta = torch.tensor(1.0, device=self.device, dtype=self.dtype)
- else:
- beta = (
- cast(torch.Tensor, self.beta)
- if isinstance(self.beta, torch.Tensor)
- else torch.tensor(self.beta, device=self.device, dtype=self.dtype)
- )
- if self.cut_size is None:
- cut_size = torch.tensor([0.0, 1.0], device=self.device, dtype=self.dtype)
- else:
- cut_size = (
- cast(torch.Tensor, self.cut_size)
- if isinstance(self.cut_size, torch.Tensor)
- else torch.tensor(self.cut_size, device=self.device, dtype=self.dtype)
+ if height is not None or width is not None:
+ warnings.warn(
+ "height and width can be inferred automatically now. "
+ "The height and width arguments will be removed finally.",
+ category=DeprecationWarning
)
- return rg.random_cutmix_generator(
- batch_shape[0],
- width=self.width,
- height=self.height,
- p=self.p,
- cut_size=cut_size,
- num_mix=self.num_mix,
- beta=beta,
- same_on_batch=self.same_on_batch,
- )
+ self._param_generator = cast(rg.CutmixGenerator, rg.CutmixGenerator(cut_size, beta, num_mix, p=p))
def apply_transform( # type: ignore
self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor] # type: ignore
) -> Tuple[torch.Tensor, torch.Tensor]:
height, width = input.size(2), input.size(3)
- num_mixes = params['mix_pairs'].size(0)
- batch_size = params['mix_pairs'].size(1)
+ num_mixes = params["mix_pairs"].size(0)
+ batch_size = params["mix_pairs"].size(1)
- _shape_validation(params['mix_pairs'], [num_mixes, batch_size], 'mix_pairs')
- _shape_validation(params['crop_src'], [num_mixes, batch_size, 4, 2], 'crop_src')
+ _shape_validation(params["mix_pairs"], [num_mixes, batch_size], "mix_pairs")
+ _shape_validation(params["crop_src"], [num_mixes, batch_size, 4, 2], "crop_src")
out_inputs = input.clone()
out_labels = []
- for pair, crop in zip(params['mix_pairs'], params['crop_src']):
+ for pair, crop in zip(params["mix_pairs"], params["crop_src"]):
input_permute = input.index_select(dim=0, index=pair.to(input.device))
labels_permute = label.index_select(dim=0, index=pair.to(label.device))
w, h = infer_bbox_shape(crop)
diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.py
index 28201bebf..e84620fd4 100644
--- a/kornia/augmentation/random_generator/random_generator.py
+++ b/kornia/augmentation/random_generator/random_generator.py
@@ -1,12 +1,1105 @@
-from typing import cast, Dict, Optional, Tuple, Union
+from functools import partial
+from typing import Any, cast, Dict, List, Optional, Tuple, Union
import torch
-from torch.distributions import Bernoulli
+import torch.nn as nn
+from torch.distributions import Bernoulli, Beta, Distribution, Uniform
from kornia.geometry.bbox import bbox_generator
-from kornia.utils import _extract_device_dtype
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
-from ..utils import _adapted_beta, _adapted_sampling, _adapted_uniform, _common_param_check, _joint_range_check
+from ..utils import (
+ _adapted_beta,
+ _adapted_rsampling,
+ _adapted_sampling,
+ _adapted_uniform,
+ _common_param_check,
+ _joint_range_check,
+ _range_bound,
+)
+
+# factor, name, center, range
+ParameterBound = Tuple[Any, str, Optional[float], Optional[Tuple[float, float]]]
+
+
+class _PostInitInjectionMetaClass(type):
+ """To inject the ``__post_init__`` function after the creation of each instance."""
+ def __call__(cls, *args, **kwargs):
+ obj = type.__call__(cls, *args, **kwargs)
+ obj.__post_init__()
+ return obj
+
+
+class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):
+ """Base class for generating random augmentation parameters."""
+ def __init__(self) -> None:
+ super().__init__()
+
+ def __post_init__(self) -> None:
+ self.set_rng_device_and_dtype()
+
+ def set_rng_device_and_dtype(
+ self, device: torch.device = torch.device('cpu'), dtype: torch.dtype = torch.float32
+ ) -> None:
+ """Change the random generation device and dtype.
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ self.make_samplers(device, dtype)
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ raise NotImplementedError
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ raise NotImplementedError
+
+
+class PlainUniformGenerator(RandomGeneratorBase):
+ r"""Generate random parameters that distributed uniformly.
+
+ Args:
+ *samplers: a list of tuple in a pattern of ``(factor, name, center, range)``, in which
+ the factor can be a two-numbered tuple, or a ``(2,)`` shaped torch tensor. The name
+ will be the corresponding key of the returning dict. The center and range must be
+ both provided worked as a validator to the given factor.
+
+ Returns:
+ A dict of parameters to be passed for transformation according the number of samplers
+ and the pointed returning name of each tuple.
+ - ``name``: element-wise probabilities with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+
+ Example:
+ >>> _ = torch.manual_seed(44)
+ >>> PlainUniformGenerator(
+ ... ((0., 1.), "factor_1", None, None),
+ ... (torch.tensor([-0.5, 0.5]), "factor_2", 0.1, (-1., 1.)),
+ ... )(torch.Size([2]))
+ {'factor_1': tensor([0.7196, 0.7307]), 'factor_2': tensor([ 0.3278, -0.3657])}
+ """
+ def __init__(self, *samplers: ParameterBound) -> None:
+ super().__init__()
+ self.samplers = samplers
+ names = []
+ for factor, name, _, _ in samplers:
+ if name in names:
+ raise RuntimeError(f"factor name `{name}` has already been registered. Please check the duplication.")
+ names.append(name)
+ if isinstance(factor, torch.nn.Parameter):
+ self.register_parameter(name, factor)
+ elif isinstance(factor, torch.Tensor):
+ self.register_buffer(name, factor)
+
+ def __repr__(self) -> str:
+ repr = ", ".join([f"{name}={factor}" for factor, name, _, _ in self.samplers])
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self.sampler_dict: Dict[str, Distribution] = {}
+ for factor, name, center, bound in self.samplers:
+ if center is None and bound is None:
+ factor = torch.as_tensor(factor, device=device, dtype=dtype)
+ elif center is None or bound is None:
+ raise ValueError(f"`center` and `bound` should be both None or provided. Got {center} and {bound}.")
+ else:
+ factor = _range_bound(
+ factor, name, center=center, bounds=bound, device=device, dtype=dtype
+ )
+ self.sampler_dict.update({name: Uniform(factor[0], factor[1], validate_args=False)})
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([t for t, _, _, _ in self.samplers])
+
+ return dict({
+ name: _adapted_rsampling((batch_size,), dist, same_on_batch).to(
+ device=_device, dtype=_dtype) for name, dist in self.sampler_dict.items()
+ })
+
+
+class ProbabilityGenerator(RandomGeneratorBase):
+ r"""Generate random probabilities for a batch of inputs.
+
+ Args:
+ p: probability to generate an 1-d binary mask. Default value is 0.5.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - probs (torch.Tensor): element-wise probabilities with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ def __init__(self, p: float = 0.5) -> None:
+ super().__init__()
+ self.p = p
+
+ def __repr__(self) -> str:
+ repr = f"p={self.p}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ p = torch.tensor(float(self.p), device=device, dtype=dtype)
+ self.sampler = Bernoulli(p)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ probs_mask: torch.Tensor = _adapted_sampling((batch_size,), self.sampler, same_on_batch).bool()
+ return dict(probs=probs_mask)
+
+
+class AffineGenerator(RandomGeneratorBase):
+ r"""Get parameters for ``affine`` for a random affine transform.
+
+ Args:
+ degrees: Range of degrees to select from like (min, max).
+ translate: 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: 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: Range of degrees to select from.
+ If float, a shear parallel to the x axis in the range (-shear, +shear) will be applied.
+ If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied.
+ If (a, b, c, d), then 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.
+ If tensor, shear is a 2x2 tensor, a x-axis shear in (shear[0][0], shear[0][1]) and y-axis shear in
+ (shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - translations (torch.Tensor): element-wise translations with a shape of (B, 2).
+ - center (torch.Tensor): element-wise center with a shape of (B, 2).
+ - scale (torch.Tensor): element-wise scales with a shape of (B, 2).
+ - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).
+ - sx (torch.Tensor): element-wise x-axis shears with a shape of (B,).
+ - sy (torch.Tensor): element-wise y-axis shears with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ def __init__(
+ self,
+ degrees: Union[torch.Tensor, float, Tuple[float, float]],
+ translate: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
+ shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
+ ) -> None:
+ super().__init__()
+ self.degrees = degrees
+ self.translate = translate
+ self.scale = scale
+ self.shear = shear
+
+ def __repr__(self) -> str:
+ repr = f"degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shear}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ _degrees = _range_bound(self.degrees, 'degrees', 0, (-360, 360)).to(device=device, dtype=dtype)
+ _translate = self.translate if self.translate is None else \
+ _range_bound(self.translate, 'translate', bounds=(0, 1), check='singular').to(device=device, dtype=dtype)
+ _scale: Optional[torch.Tensor] = None
+ if self.scale is not None:
+ if len(self.scale) == 2:
+ _scale = _range_bound(
+ self.scale[:2], 'scale', bounds=(0, float('inf')), check='singular').to(device=device, dtype=dtype)
+ elif len(self.scale) == 4:
+ _scale = torch.cat([
+ _range_bound(self.scale[:2], 'scale_x', bounds=(0, float('inf')), check='singular'),
+ _range_bound(self.scale[2:], 'scale_y', bounds=(0, float('inf')), check='singular'), # type:ignore
+ ]).to(device=device, dtype=dtype)
+ else:
+ raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {self.scale}")
+ _shear: Optional[torch.Tensor] = None
+ if self.shear is not None:
+ shear = torch.as_tensor(self.shear, device=device, dtype=dtype)
+ if shear.shape == torch.Size([2, 2]):
+ _shear = shear
+ else:
+ _shear = torch.stack([
+ _range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),
+ torch.tensor([0, 0], device=device, dtype=dtype) if shear.dim() == 0 or len(shear) == 2
+ else _range_bound(shear[2:], 'shear-y', 0, (-360, 360)),
+ ])
+
+ translate_x_sampler: Optional[Uniform] = None
+ translate_y_sampler: Optional[Uniform] = None
+ scale_2_sampler: Optional[Uniform] = None
+ scale_4_sampler: Optional[Uniform] = None
+ shear_x_sampler: Optional[Uniform] = None
+ shear_y_sampler: Optional[Uniform] = None
+
+ if _translate is not None:
+ translate_x_sampler = Uniform(-_translate[0], _translate[0], validate_args=False)
+ translate_y_sampler = Uniform(-_translate[1], _translate[1], validate_args=False)
+ if _scale is not None:
+ if len(_scale) == 2:
+ scale_2_sampler = Uniform(_scale[0], _scale[1], validate_args=False)
+ elif len(_scale) == 4:
+ scale_2_sampler = Uniform(_scale[0], _scale[1], validate_args=False)
+ scale_4_sampler = Uniform(_scale[2], _scale[3], validate_args=False)
+ else:
+ raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {self.scale}")
+ if _shear is not None:
+ _joint_range_check(cast(torch.Tensor, _shear)[0], "shear")
+ _joint_range_check(cast(torch.Tensor, _shear)[1], "shear")
+ shear_x_sampler = Uniform(_shear[0][0], _shear[0][1], validate_args=False)
+ shear_y_sampler = Uniform(_shear[1][0], _shear[1][1], validate_args=False)
+
+ self.degree_sampler = Uniform(_degrees[0], _degrees[1], validate_args=False)
+ self.translate_x_sampler = translate_x_sampler
+ self.translate_y_sampler = translate_y_sampler
+ self.scale_2_sampler = scale_2_sampler
+ self.scale_4_sampler = scale_4_sampler
+ self.shear_x_sampler = shear_x_sampler
+ self.shear_y_sampler = shear_y_sampler
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type: ignore
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ _device, _dtype = _extract_device_dtype([self.degrees, self.translate, self.scale, self.shear])
+ _common_param_check(batch_size, same_on_batch)
+ if not (isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0):
+ raise AssertionError(f"`width` and `height` must be positive integers. Got {width}, {height}.")
+
+ angle = _adapted_rsampling((batch_size,), self.degree_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+
+ # compute tensor ranges
+ if self.scale_2_sampler is not None:
+ _scale = _adapted_rsampling((batch_size,), self.scale_2_sampler, same_on_batch).unsqueeze(1).repeat(1, 2)
+ if self.scale_4_sampler is not None:
+ _scale[:, 1] = _adapted_rsampling((batch_size,), self.scale_4_sampler, same_on_batch)
+ _scale = _scale.to(device=_device, dtype=_dtype)
+ else:
+ _scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)
+
+ if self.translate_x_sampler is not None and self.translate_y_sampler is not None:
+ translations = torch.stack([
+ _adapted_rsampling((batch_size,), self.translate_x_sampler, same_on_batch) * width,
+ _adapted_rsampling((batch_size,), self.translate_y_sampler, same_on_batch) * height,
+ ], dim=-1)
+ translations = translations.to(device=_device, dtype=_dtype)
+ else:
+ translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)
+
+ center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
+ center = center.expand(batch_size, -1)
+
+ if self.shear_x_sampler is not None and self.shear_y_sampler is not None:
+ sx = _adapted_rsampling((batch_size,), self.shear_x_sampler, same_on_batch)
+ sy = _adapted_rsampling((batch_size,), self.shear_y_sampler, same_on_batch)
+ sx = sx.to(device=_device, dtype=_dtype)
+ sy = sy.to(device=_device, dtype=_dtype)
+ else:
+ sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
+
+ return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)
+
+
+class ColorJitterGenerator(RandomGeneratorBase):
+ r"""Generate random color jiter parameters for a batch of images.
+
+ Args:
+ brightness: The brightness factor to apply.
+ contrast: The contrast factor to apply.
+ saturation: The saturation factor to apply.
+ hue: The hue factor to apply.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - brightness_factor: element-wise brightness factors with a shape of (B,).
+ - contrast_factor: element-wise contrast factors with a shape of (B,).
+ - hue_factor: element-wise hue factors with a shape of (B,).
+ - saturation_factor: element-wise saturation factors with a shape of (B,).
+ - order: applying orders of the color adjustments with a shape of (4). In which,
+ 0 is brightness adjustment; 1 is contrast adjustment;
+ 2 is saturation adjustment; 3 is hue adjustment.
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ def __init__(
+ self,
+ brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ ) -> None:
+ super().__init__()
+ self.brightness = brightness
+ self.contrast = contrast
+ self.saturation = saturation
+ self.hue = hue
+
+ def __repr__(self) -> str:
+ repr = f"brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ brightness: torch.Tensor = _range_bound(
+ self.brightness, 'brightness', center=1.0, bounds=(0, 2), device=device, dtype=dtype
+ )
+ contrast: torch.Tensor = _range_bound(
+ self.contrast, 'contrast', center=1.0, device=device, dtype=dtype
+ )
+ saturation: torch.Tensor = _range_bound(
+ self.saturation, 'saturation', center=1.0, device=device, dtype=dtype
+ )
+ hue: torch.Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=device, dtype=dtype)
+
+ _joint_range_check(brightness, "brightness", (0, 2))
+ _joint_range_check(contrast, "contrast", (0, float('inf')))
+ _joint_range_check(hue, "hue", (-0.5, 0.5))
+ _joint_range_check(saturation, "saturation", (0, float('inf')))
+
+ self.brightness_sampler = Uniform(brightness[0], brightness[1], validate_args=False)
+ self.contrast_sampler = Uniform(contrast[0], contrast[1], validate_args=False)
+ self.hue_sampler = Uniform(hue[0], hue[1], validate_args=False)
+ self.saturation_sampler = Uniform(saturation[0], saturation[1], validate_args=False)
+ self.randperm = partial(torch.randperm, device=device, dtype=dtype)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.brightness, self.contrast, self.hue, self.saturation])
+ brightness_factor = _adapted_rsampling((batch_size,), self.brightness_sampler, same_on_batch)
+ contrast_factor = _adapted_rsampling((batch_size,), self.contrast_sampler, same_on_batch)
+ hue_factor = _adapted_rsampling((batch_size,), self.hue_sampler, same_on_batch)
+ saturation_factor = _adapted_rsampling((batch_size,), self.saturation_sampler, same_on_batch)
+ return dict(
+ brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),
+ contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),
+ hue_factor=hue_factor.to(device=_device, dtype=_dtype),
+ saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),
+ order=self.randperm(4).to(device=_device, dtype=_dtype).long(),
+ )
+
+
+class CropGenerator(RandomGeneratorBase):
+ r"""Get parameters for ```crop``` transformation for crop transform.
+
+ Args:
+ size (tuple): Desired size of the crop operation, like (h, w).
+ If tensor, it must be (B, 2).
+ resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ def __init__(
+ self,
+ size: Union[Tuple[int, int], torch.Tensor],
+ resize_to: Optional[Tuple[int, int]] = None
+ ) -> None:
+ super().__init__()
+ self.size = size
+ self.resize_to = resize_to
+
+ def __repr__(self) -> str:
+ repr = f"crop_size={self.size}"
+ if self.resize_to is not None:
+ repr += f", resize_to={self.resize_to}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self.rand_sampler = Uniform(
+ torch.tensor(0., device=device, dtype=dtype), torch.tensor(1., device=device, dtype=dtype))
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])
+
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ )
+
+ input_size = (batch_shape[-2], batch_shape[-1])
+ if not isinstance(self.size, torch.Tensor):
+ size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ else:
+ size = self.size.to(device=_device, dtype=_dtype)
+ if size.shape != torch.Size([batch_size, 2]):
+ raise AssertionError(
+ "If `size` is a tensor, it must be shaped as (B, 2). "
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}."
+ )
+ if not (input_size[0] > 0 and input_size[1] > 0 and (size > 0).all()):
+ raise AssertionError(f"Got non-positive input size or size. {input_size}, {size}.")
+ size = size.floor()
+
+ x_diff = input_size[1] - size[:, 1] + 1
+ y_diff = input_size[0] - size[:, 0] + 1
+
+ # Start point will be 0 if diff < 0
+ x_diff = x_diff.clamp(0)
+ y_diff = y_diff.clamp(0)
+
+ if same_on_batch:
+ # If same_on_batch, select the first then repeat.
+ x_start = (_adapted_rsampling(
+ (batch_size,), self.rand_sampler, same_on_batch).to(x_diff) * x_diff[0]).floor()
+ y_start = (_adapted_rsampling(
+ (batch_size,), self.rand_sampler, same_on_batch).to(y_diff) * y_diff[0]).floor()
+ else:
+ x_start = (_adapted_rsampling(
+ (batch_size,), self.rand_sampler, same_on_batch).to(x_diff) * x_diff).floor()
+ y_start = (_adapted_rsampling(
+ (batch_size,), self.rand_sampler, same_on_batch).to(y_diff) * y_diff).floor()
+ crop_src = bbox_generator(
+ x_start.view(-1).to(device=_device, dtype=_dtype),
+ y_start.view(-1).to(device=_device, dtype=_dtype),
+ torch.where(size[:, 1] == 0, torch.tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
+ torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
+ )
+
+ if self.resize_to is None:
+ crop_dst = bbox_generator(
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ size[:, 1],
+ size[:, 0],
+ )
+ else:
+ if not (
+ len(self.resize_to) == 2
+ and isinstance(self.resize_to[0], (int,))
+ and isinstance(self.resize_to[1], (int,))
+ and self.resize_to[0] > 0
+ and self.resize_to[1] > 0
+ ):
+ raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {self.resize_to}.")
+ crop_dst = torch.tensor(
+ [[
+ [0, 0],
+ [self.resize_to[1] - 1, 0],
+ [self.resize_to[1] - 1, self.resize_to[0] - 1],
+ [0, self.resize_to[0] - 1]
+ ]],
+ device=_device,
+ dtype=_dtype,
+ ).repeat(batch_size, 1, 1)
+
+ _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+
+ return dict(src=crop_src, dst=crop_dst, input_size=_input_size)
+
+
+class ResizedCropGenerator(CropGenerator):
+ r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
+
+ Args:
+ output_size (Tuple[int, int]): expected output size of each edge.
+ scale (torch.Tensor): range of size of the origin size cropped with (2,) shape.
+ ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - size (torch.Tensor): element-wise cropping sizes with a shape of (B, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+
+ Examples:
+ >>> _ = torch.manual_seed(42)
+ >>> random_crop_size_generator(3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))
+ {'size': tensor([[29., 29.],
+ [27., 28.],
+ [26., 29.]])}
+ """
+ def __init__(
+ self,
+ output_size: Tuple[int, int],
+ scale: Union[torch.Tensor, Tuple[float, float]],
+ ratio: Union[torch.Tensor, Tuple[float, float]]
+ ) -> None:
+ self.scale = scale
+ self.ratio = ratio
+ self.output_size = output_size
+ if not (
+ len(output_size) == 2
+ and isinstance(output_size[0], (int,))
+ and isinstance(output_size[1], (int,))
+ and output_size[0] > 0
+ and output_size[1] > 0
+ ):
+ raise AssertionError(f"`output_size` must be a tuple of 2 positive integers. Got {output_size}.")
+ super().__init__(size=output_size, resize_to=self.output_size) # fake an intermedia crop size
+
+ def __repr__(self) -> str:
+ repr = f"scale={self.scale}, resize_to={self.ratio}, output_size={self.output_size}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
+ ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
+ _joint_range_check(scale, "scale")
+ _joint_range_check(ratio, "ratio")
+ self.rand_sampler = Uniform(
+ torch.tensor(0., device=device, dtype=dtype), torch.tensor(1., device=device, dtype=dtype))
+ self.log_ratio_sampler = Uniform(torch.log(ratio[0]), torch.log(ratio[1]), validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ size = (batch_shape[-2], batch_shape[-1])
+ _device, _dtype = _extract_device_dtype([self.scale, self.ratio])
+
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ size=torch.zeros([0, 2], device=_device, dtype=_dtype),
+ )
+
+ rand = _adapted_rsampling(
+ (batch_size, 10), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+ area = (rand * (self.scale[1] - self.scale[0]) + self.scale[0]) * size[0] * size[1]
+ log_ratio = _adapted_rsampling(
+ (batch_size, 10), self.log_ratio_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+ aspect_ratio = torch.exp(log_ratio)
+
+ w = torch.sqrt(area * aspect_ratio).round().floor()
+ h = torch.sqrt(area / aspect_ratio).round().floor()
+ # Element-wise w, h condition
+ cond = ((0 < w) * (w < size[0]) * (0 < h) * (h < size[1])).int()
+
+ # torch.argmax is not reproducible across devices: https://github.com/pytorch/pytorch/issues/17738
+ # Here, we will select the first occurrence of the duplicated elements.
+ cond_bool, argmax_dim1 = ((cond.cumsum(1) == 1) & cond.bool()).max(1)
+ h_out = w[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
+ w_out = h[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
+
+ if not cond_bool.all():
+ # Fallback to center crop
+ in_ratio = float(size[0]) / float(size[1])
+ _min = self.ratio.min() if isinstance(self.ratio, torch.Tensor) else min(self.ratio)
+ if in_ratio < _min: # type:ignore
+ h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)
+ w_ct = torch.round(h_ct / _min)
+ elif in_ratio > _min: # type:ignore
+ w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)
+ h_ct = torch.round(w_ct * _min)
+ else: # whole image
+ h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)
+ w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)
+ h_ct = h_ct.floor()
+ w_ct = w_ct.floor()
+
+ h_out = h_out.where(cond_bool, h_ct)
+ w_out = w_out.where(cond_bool, w_ct)
+
+ # Update the crop size.
+ self.size = torch.stack([h_out, w_out], dim=1)
+ return super().forward(batch_shape, same_on_batch)
+
+
+class PerspectiveGenerator(RandomGeneratorBase):
+ r"""Get parameters for ``perspective`` for a random perspective transform.
+
+ Args:
+ distortion_scale: the degree of distortion, ranged from 0 to 1.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - start_points (torch.Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
+ - end_points (torch.Tensor): element-wise perspective target areas with a shape of (B, 4, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ def __init__(self, distortion_scale: Union[torch.Tensor, float] = 0.5) -> None:
+ super().__init__()
+ self.distortion_scale = distortion_scale
+
+ def __repr__(self) -> str:
+ repr = f"distortion_scale={self.distortion_scale}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self._distortion_scale = torch.as_tensor(self.distortion_scale, device=device, dtype=dtype)
+ if not (self._distortion_scale.dim() == 0 and 0 <= self._distortion_scale <= 1):
+ raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {self._distortion_scale}.")
+ self.rand_val_sampler = Uniform(
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ _device, _dtype = _extract_device_dtype([self.distortion_scale])
+ _common_param_check(batch_size, same_on_batch)
+ if not (type(height) is int and height > 0 and type(width) is int and width > 0):
+ raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
+
+ start_points: torch.Tensor = torch.tensor(
+ [[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],
+ device=_device,
+ dtype=_dtype,
+ ).expand(batch_size, -1, -1)
+
+ # generate random offset not larger than half of the image
+ fx = self._distortion_scale * width / 2
+ fy = self._distortion_scale * height / 2
+
+ factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2).to(device=_device, dtype=_dtype)
+
+ # TODO: This line somehow breaks the gradcheck
+ rand_val: torch.Tensor = _adapted_rsampling(
+ start_points.shape, self.rand_val_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+
+ pts_norm = torch.tensor(
+ [[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype
+ )
+
+ end_points = start_points + factor * rand_val * pts_norm
+
+ return dict(start_points=start_points, end_points=end_points)
+
+
+class RectangleEraseGenerator(RandomGeneratorBase):
+ r"""Get parameters for ```erasing``` transformation for erasing transform.
+
+ Args:
+ scale (torch.Tensor): range of size of the origin size cropped. Shape (2).
+ ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
+ value (float): value to be filled in the erased area.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - widths (torch.Tensor): element-wise erasing widths with a shape of (B,).
+ - heights (torch.Tensor): element-wise erasing heights with a shape of (B,).
+ - xs (torch.Tensor): element-wise erasing x coordinates with a shape of (B,).
+ - ys (torch.Tensor): element-wise erasing y coordinates with a shape of (B,).
+ - values (torch.Tensor): element-wise filling values with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ 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.
+ ) -> None:
+ super().__init__()
+ self.scale = scale
+ self.ratio = ratio
+ self.value = value
+
+ def __repr__(self) -> str:
+ repr = f"scale={self.scale}, resize_to={self.ratio}, value={self.value}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
+ ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
+
+ if not (isinstance(self.value, (int, float)) and self.value >= 0 and self.value <= 1):
+ raise AssertionError(f"'value' must be a number between 0 - 1. Got {self.value}.")
+ _joint_range_check(scale, 'scale', bounds=(0, float('inf')))
+ _joint_range_check(ratio, 'ratio', bounds=(0, float('inf')))
+
+ self.scale_sampler = Uniform(scale[0], scale[1], validate_args=False)
+
+ if ratio[0] < 1.0 and ratio[1] > 1.0:
+ self.ratio_sampler1 = Uniform(ratio[0], 1, validate_args=False)
+ self.ratio_sampler2 = Uniform(1, ratio[1], validate_args=False)
+ self.index_sampler = Uniform(
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False
+ )
+ else:
+ self.ratio_sampler = Uniform(ratio[0], ratio[1], validate_args=False)
+ self.uniform_sampler = Uniform(
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+ if not (type(height) is int and height > 0 and type(width) is int and width > 0):
+ raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
+
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.ratio, self.scale])
+ images_area = height * width
+ target_areas = _adapted_rsampling(
+ (batch_size,), self.scale_sampler, same_on_batch).to(device=_device, dtype=_dtype) * images_area
+
+ if self.ratio[0] < 1.0 and self.ratio[1] > 1.0:
+ aspect_ratios1 = _adapted_rsampling((batch_size,), self.ratio_sampler1, same_on_batch)
+ aspect_ratios2 = _adapted_rsampling((batch_size,), self.ratio_sampler2, same_on_batch)
+ if same_on_batch:
+ rand_idxs = torch.round(
+ _adapted_rsampling((1,), self.index_sampler, same_on_batch)).repeat(batch_size).bool()
+ else:
+ rand_idxs = torch.round(
+ _adapted_rsampling((batch_size,), self.index_sampler, same_on_batch)).bool()
+ aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
+ else:
+ aspect_ratios = _adapted_rsampling((batch_size,), self.ratio_sampler, same_on_batch)
+
+ aspect_ratios = aspect_ratios.to(device=_device, dtype=_dtype)
+
+ # based on target areas and aspect ratios, rectangle params are computed
+ heights = torch.min(
+ torch.max(
+ torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)
+ ),
+ torch.tensor(height, device=_device, dtype=_dtype),
+ )
+
+ widths = torch.min(
+ torch.max(
+ torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)
+ ),
+ torch.tensor(width, device=_device, dtype=_dtype),
+ )
+
+ xs_ratio = _adapted_rsampling(
+ (batch_size,), self.uniform_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+ ys_ratio = _adapted_rsampling(
+ (batch_size,), self.uniform_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+
+ xs = xs_ratio * (width - widths + 1)
+ ys = ys_ratio * (height - heights + 1)
+
+ return dict(
+ widths=widths.floor(),
+ heights=heights.floor(),
+ xs=xs.floor(),
+ ys=ys.floor(),
+ values=torch.tensor([self.value] * batch_size, device=_device, dtype=_dtype),
+ )
+
+
+class MotionBlurGenerator(RandomGeneratorBase):
+ r"""Get parameters for motion blur.
+
+ Args:
+ kernel_size: motion kernel size (odd and positive).
+ If int, the kernel will have a fixed size.
+ If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
+ angle: angle of the motion blur in degrees (anti-clockwise rotation).
+ If float, it will generate the value from (-angle, angle).
+ direction: forward/backward direction of the motion blur.
+ Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
+ while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
+ uniformly (but still angled) motion blur.
+ If float, it will generate the value from (-direction, direction).
+ If Tuple[int, int], it will randomly generate the value from the range.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+
+ def __init__(
+ self,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: Union[torch.Tensor, float, Tuple[float, float]],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
+ ) -> None:
+ super().__init__()
+ self.kernel_size = kernel_size
+ self.angle = angle
+ self.direction = direction
+
+ def __repr__(self) -> str:
+ repr = f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ angle = _range_bound(self.angle, 'angle', center=0.0, bounds=(-360, 360)).to(device=device, dtype=dtype)
+ direction = _range_bound(self.direction, 'direction', center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
+ if isinstance(self.kernel_size, int):
+ if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):
+ raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {self.kernel_size}.")
+ self.ksize_sampler = Uniform(self.kernel_size // 2, self.kernel_size // 2, validate_args=False)
+ elif isinstance(self.kernel_size, tuple):
+ # kernel_size is fixed across the batch
+ if len(self.kernel_size) != 2:
+ raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {self.kernel_size}.")
+ self.ksize_sampler = Uniform(self.kernel_size[0] // 2, self.kernel_size[1] // 2, validate_args=False)
+ else:
+ raise TypeError(f"Unsupported type: {type(self.kernel_size)}")
+
+ self.angle_sampler = Uniform(angle[0], angle[1], validate_args=False)
+ self.direction_sampler = Uniform(direction[0], direction[1], validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ # self.ksize_factor.expand((batch_size, -1))
+ _device, _dtype = _extract_device_dtype([self.angle, self.direction])
+ angle_factor = _adapted_rsampling((batch_size,), self.angle_sampler, same_on_batch)
+ direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)
+ ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1
+
+ return dict(
+ ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
+ angle_factor=angle_factor.to(device=_device, dtype=_dtype),
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype),
+ )
+
+
+class PosterizeGenerator(RandomGeneratorBase):
+ r"""Generate random posterize parameters for a batch of images.
+
+ Args:
+ bits: Integer that ranged from (0, 8], in which 0 gives black image and 8 gives the original.
+ If int x, bits will be generated from (x, 8).
+ If tuple (x, y), bits will be generated from (x, y).
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - bits_factor (torch.Tensor): element-wise bit factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ def __init__(self, bits: Union[int, Tuple[int, int], torch.Tensor]) -> None:
+ super().__init__()
+ self.bits = bits
+
+ def __repr__(self) -> str:
+ repr = f"bits={self.bits}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ bits = torch.as_tensor(self.bits, device=device, dtype=dtype)
+ if len(bits.size()) == 0:
+ bits = bits.repeat(2)
+ bits[1] = 8
+ elif not (len(bits.size()) == 1 and bits.size(0) == 2):
+ raise ValueError(f"'bits' shall be either a scalar or a length 2 tensor. Got {bits}.")
+ _joint_range_check(bits, 'bits', (0, 8))
+ self.bit_sampler = Uniform(bits[0], bits[1], validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.bits if isinstance(self.bits, torch.Tensor) else None])
+ bits_factor = _adapted_rsampling((batch_size,), self.bit_sampler, same_on_batch)
+ return dict(bits_factor=bits_factor.to(device=_device, dtype=torch.int32))
+
+
+class MixupGenerator(RandomGeneratorBase):
+ r"""Generate mixup indexes and lambdas for a batch of inputs.
+
+ Args:
+ lambda_val (torch.Tensor, optional): min-max strength for mixup images, ranged from [0., 1.].
+ If None, it will be set to tensor([0., 1.]), which means no restrictions.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - mix_pairs (torch.Tensor): element-wise probabilities with a shape of (B,).
+ - mixup_lambdas (torch.Tensor): element-wise probabilities with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+
+ def __init__(self, lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None, p: float = 1.0) -> None:
+ super().__init__()
+ self.lambda_val = lambda_val
+ self.p = p
+
+ def __repr__(self) -> str:
+ repr = f"lambda_val={self.lambda_val}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ if self.lambda_val is None:
+ lambda_val = torch.tensor([0.0, 1.0], device=device, dtype=dtype)
+ else:
+ lambda_val = torch.as_tensor(self.lambda_val, device=device, dtype=dtype)
+
+ _joint_range_check(lambda_val, 'lambda_val', bounds=(0, 1))
+ self.lambda_sampler = Uniform(lambda_val[0], lambda_val[1], validate_args=False)
+ self.prob_sampler = Bernoulli(torch.tensor(float(self.p), device=device, dtype=dtype))
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ batch_size = batch_shape[0]
+
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.lambda_val])
+
+ with torch.no_grad():
+ batch_probs: torch.Tensor = _adapted_sampling((batch_size,), self.prob_sampler, same_on_batch)
+ mixup_pairs: torch.Tensor = torch.randperm(batch_size, device=_device, dtype=_dtype).long()
+ mixup_lambdas: torch.Tensor = _adapted_rsampling((batch_size,), self.lambda_sampler, same_on_batch)
+ mixup_lambdas = mixup_lambdas * batch_probs
+
+ return dict(
+ mixup_pairs=mixup_pairs.to(device=_device, dtype=torch.long),
+ mixup_lambdas=mixup_lambdas.to(device=_device, dtype=_dtype),
+ )
+
+
+class CutmixGenerator(RandomGeneratorBase):
+ r"""Generate cutmix indexes and lambdas for a batch of inputs.
+
+ Args:
+ p (float): probability of applying cutmix.
+ num_mix (int): number of images to mix with. Default is 1.
+ beta (torch.Tensor, optional): hyperparameter for generating cut size from beta distribution.
+ If None, it will be set to 1.
+ cut_size (torch.Tensor, optional): controlling the minimum and maximum cut ratio from [0, 1].
+ If None, it will be set to [0, 1], which means no restriction.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - mix_pairs (torch.Tensor): element-wise probabilities with a shape of (num_mix, B).
+ - crop_src (torch.Tensor): element-wise probabilities with a shape of (num_mix, B, 4, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+
+ def __init__(
+ self,
+ cut_size: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ beta: Optional[Union[torch.Tensor, float]] = None,
+ num_mix: int = 1,
+ p: float = 1.0,
+ ) -> None:
+ super().__init__()
+ self.cut_size = cut_size
+ self.beta = beta
+ self.num_mix = num_mix
+ self.p = p
+
+ if not (num_mix >= 1 and isinstance(num_mix, (int,))):
+ raise AssertionError(f"`num_mix` must be an integer greater than 1. Got {num_mix}.")
+
+ def __repr__(self) -> str:
+ repr = f"cut_size={self.cut_size}, beta={self.beta}, num_mix={self.num_mix}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ if self.beta is None:
+ self._beta = torch.tensor(1.0, device=device, dtype=dtype)
+ else:
+ self._beta = torch.as_tensor(self.beta, device=device, dtype=dtype)
+ if self.cut_size is None:
+ self._cut_size = torch.tensor([0.0, 1.0], device=device, dtype=dtype)
+ else:
+ self._cut_size = torch.as_tensor(self.cut_size, device=device, dtype=dtype)
+
+ _joint_range_check(self._cut_size, 'cut_size', bounds=(0, 1))
+
+ self.beta_sampler = Beta(self._beta, self._beta)
+ self.prob_sampler = Bernoulli(torch.tensor(float(self.p), device=device, dtype=dtype))
+ self.rand_sampler = Uniform(
+ torch.tensor(0., device=device, dtype=dtype),
+ torch.tensor(1., device=device, dtype=dtype),
+ validate_args=False
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ if not (type(height) is int and height > 0 and type(width) is int and width > 0):
+ raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
+ _device, _dtype = _extract_device_dtype([self.beta, self.cut_size])
+ _common_param_check(batch_size, same_on_batch)
+
+ if batch_size == 0:
+ return dict(
+ mix_pairs=torch.zeros([0, 3], device=_device, dtype=torch.long),
+ crop_src=torch.zeros([0, 4, 2], device=_device, dtype=torch.long),
+ )
+
+ with torch.no_grad():
+ batch_probs: torch.Tensor = _adapted_sampling(
+ (batch_size * self.num_mix,), self.prob_sampler, same_on_batch)
+ mix_pairs: torch.Tensor = torch.rand(self.num_mix, batch_size, device=_device, dtype=_dtype).argsort(dim=1)
+ cutmix_betas: torch.Tensor = _adapted_rsampling((batch_size * self.num_mix,), self.beta_sampler, same_on_batch)
+
+ # Note: torch.clamp does not accept tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:
+ # Argument 1 to "clamp" of "_TensorBase" has incompatible type "Tensor"; expected "float"
+ cutmix_betas = torch.min(torch.max(cutmix_betas, self._cut_size[0]), self._cut_size[1])
+ cutmix_rate = torch.sqrt(1.0 - cutmix_betas) * batch_probs
+
+ cut_height = (cutmix_rate * height).floor().to(device=_device, dtype=_dtype)
+ cut_width = (cutmix_rate * width).floor().to(device=_device, dtype=_dtype)
+ _gen_shape = (1,)
+
+ if same_on_batch:
+ _gen_shape = (cut_height.size(0),)
+ cut_height = cut_height[0]
+ cut_width = cut_width[0]
+
+ # Reserve at least 1 pixel for cropping.
+ x_start: torch.Tensor = _adapted_rsampling(
+ _gen_shape, self.rand_sampler, same_on_batch) * (width - cut_width - 1)
+ y_start: torch.Tensor = _adapted_rsampling(
+ _gen_shape, self.rand_sampler, same_on_batch) * (height - cut_height - 1)
+ x_start = x_start.floor().to(device=_device, dtype=_dtype)
+ y_start = y_start.floor().to(device=_device, dtype=_dtype)
+
+ crop_src = bbox_generator(x_start.squeeze(), y_start.squeeze(), cut_width, cut_height)
+
+ # (B * num_mix, 4, 2) => (num_mix, batch_size, 4, 2)
+ crop_src = crop_src.view(self.num_mix, batch_size, 4, 2)
+
+ return dict(
+ mix_pairs=mix_pairs.to(device=_device, dtype=torch.long),
+ crop_src=crop_src.floor().to(device=_device, dtype=_dtype),
+ )
def random_prob_generator(
@@ -42,6 +1135,7 @@ def random_prob_generator(
return probs_mask
+@_deprecated(replace_with=ColorJitterGenerator.__name__)
def random_color_jitter_generator(
batch_size: int,
brightness: Optional[torch.Tensor] = None,
@@ -107,6 +1201,7 @@ def random_color_jitter_generator(
)
+@_deprecated(replace_with=PerspectiveGenerator.__name__)
def random_perspective_generator(
batch_size: int,
height: int,
@@ -169,6 +1264,7 @@ def random_perspective_generator(
return dict(start_points=start_points, end_points=end_points)
+@_deprecated(replace_with=AffineGenerator.__name__)
def random_affine_generator(
batch_size: int,
height: int,
@@ -271,6 +1367,7 @@ def random_affine_generator(
return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)
+@_deprecated()
def random_rotation_generator(
batch_size: int,
degrees: torch.Tensor,
@@ -308,6 +1405,7 @@ def random_rotation_generator(
return dict(degrees=_degrees)
+@_deprecated(replace_with=CropGenerator.__name__)
def random_crop_generator(
batch_size: int,
input_size: Tuple[int, int],
@@ -442,6 +1540,7 @@ def random_crop_generator(
return dict(src=crop_src, dst=crop_dst, input_size=_input_size)
+@_deprecated()
def random_crop_size_generator(
batch_size: int,
size: Tuple[int, int],
@@ -526,6 +1625,7 @@ def random_crop_size_generator(
return dict(size=torch.stack([h_out, w_out], dim=1).to(device=_device, dtype=_dtype))
+@_deprecated(replace_with=RectangleEraseGenerator.__name__)
def random_rectangles_params_generator(
batch_size: int,
height: int,
@@ -716,6 +1816,7 @@ def center_crop_generator(
return dict(src=points_src, dst=points_dst, input_size=_input_size)
+@_deprecated(replace_with=MotionBlurGenerator.__name__)
def random_motion_blur_generator(
batch_size: int,
kernel_size: Union[int, Tuple[int, int]],
@@ -786,6 +1887,7 @@ def random_motion_blur_generator(
)
+@_deprecated()
def random_solarize_generator(
batch_size: int,
thresholds: torch.Tensor = torch.tensor([0.4, 0.6]),
@@ -842,6 +1944,7 @@ def random_solarize_generator(
)
+@_deprecated()
def random_posterize_generator(
batch_size: int,
bits: torch.Tensor = torch.tensor([3, 5]),
@@ -874,6 +1977,7 @@ def random_posterize_generator(
return dict(bits_factor=bits_factor.to(device=bits.device, dtype=torch.int32))
+@_deprecated()
def random_sharpness_generator(
batch_size: int,
sharpness: torch.Tensor = torch.tensor([0, 1.0]),
diff --git a/kornia/augmentation/random_generator/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.py
index 1049dd8b3..746eda56d 100644
--- a/kornia/augmentation/random_generator/random_generator3d.py
+++ b/kornia/augmentation/random_generator/random_generator3d.py
@@ -1,13 +1,594 @@
from typing import Dict, Optional, Tuple, Union
import torch
+from torch.distributions import Uniform
from kornia.geometry.bbox import bbox_generator3d
-from kornia.utils import _extract_device_dtype
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
-from ..utils import _adapted_uniform, _joint_range_check
+from ..utils import (
+ _adapted_rsampling,
+ _adapted_uniform,
+ _common_param_check,
+ _joint_range_check,
+ _range_bound,
+ _singular_range_check,
+ _tuple_range_reader,
+)
+from .random_generator import RandomGeneratorBase
+class AffineGenerator3D(RandomGeneratorBase):
+ r"""Get parameters for ```3d affine``` transformation random affine transform.
+
+ Args:
+ degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
+ If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
+ If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
+ If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
+ and (-c, c).
+ If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
+ (a, b), (m, n) and (x, y).
+ Set to 0 to deactivate rotations.
+ translate: tuple of maximum absolute fraction for horizontal, vertical and
+ depthical translations (dx,dy,dz). For example translate=(a, b, c), then
+ horizontal shift will be randomly sampled in the range -img_width * a < dx < img_width * a
+ vertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b.
+ depthical shift will be randomly sampled in the range -img_depth * c < dz < img_depth * c.
+ Will not translate by default.
+ scale: scaling factor interval.
+ If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.
+ If ((a, b), (c, d), (e, f)), the scale is randomly sampled from the range a <= scale_x <= b,
+ c <= scale_y <= d, e <= scale_z <= f. Will keep original scale by default.
+ shears: Range of degrees to select from.
+ If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be applied.
+ If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.
+ If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i])
+ will be applied.
+ If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1])
+ will be applied.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - translations (torch.Tensor): element-wise translations with a shape of (B, 3).
+ - center (torch.Tensor): element-wise center with a shape of (B, 3).
+ - scale (torch.Tensor): element-wise scales with a shape of (B, 3).
+ - angle (torch.Tensor): element-wise rotation angles with a shape of (B, 3).
+ - sxy (torch.Tensor): element-wise x-y-facet shears with a shape of (B,).
+ - sxz (torch.Tensor): element-wise x-z-facet shears with a shape of (B,).
+ - syx (torch.Tensor): element-wise y-x-facet shears with a shape of (B,).
+ - syz (torch.Tensor): element-wise y-z-facet shears with a shape of (B,).
+ - szx (torch.Tensor): element-wise z-x-facet shears with a shape of (B,).
+ - szy (torch.Tensor): element-wise z-y-facet shears with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ def __init__(
+ self,
+ degrees: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float],
+ Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
+ ],
+ translate: Optional[Union[torch.Tensor, Tuple[float, float, float]]] = None,
+ scale: Optional[
+ Union[
+ torch.Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]
+ ]
+ ] = None,
+ shears: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float],
+ Tuple[float, float, float, float, float, float],
+ Tuple[
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ ],
+ ] = None,
+ ) -> None:
+ super().__init__()
+ self.degrees = degrees
+ self.shears = shears
+ self.translate = translate
+ self.scale = scale
+
+ def __repr__(self) -> str:
+ repr = f"degrees={self.degrees}, shears={self.shears}, translate={self.translate}, scale={self.scale}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ degrees = _tuple_range_reader(self.degrees, 3, device, dtype)
+ shear: Optional[torch.Tensor] = None
+ if self.shears is not None:
+ shear = _tuple_range_reader(self.shears, 6, device, dtype)
+ self.sxy_sampler = Uniform(shear[0, 0], shear[0, 1], validate_args=False)
+ self.sxz_sampler = Uniform(shear[1, 0], shear[1, 1], validate_args=False)
+ self.syx_sampler = Uniform(shear[2, 0], shear[2, 1], validate_args=False)
+ self.syz_sampler = Uniform(shear[3, 0], shear[3, 1], validate_args=False)
+ self.szx_sampler = Uniform(shear[4, 0], shear[4, 1], validate_args=False)
+ self.szy_sampler = Uniform(shear[5, 0], shear[5, 1], validate_args=False)
+
+ # check translation range
+ self._translate: Optional[torch.Tensor] = None
+ if self.translate is not None:
+ self._translate = torch.as_tensor(self.translate, device=device, dtype=dtype)
+ _singular_range_check(self._translate, 'translate', bounds=(0, 1), mode='3d')
+
+ # check scale range
+ self._scale: Optional[torch.Tensor] = None
+ if self.scale is not None:
+ _scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
+ if _scale.shape == torch.Size([2]):
+ self._scale = _scale.unsqueeze(0).repeat(3, 1)
+ elif _scale.shape != torch.Size([3, 2]):
+ raise ValueError(f"'scale' shall be either shape (2) or (3, 2). Got {self.scale}.")
+ else:
+ self._scale = _scale
+ _singular_range_check(self._scale[0], 'scale-x', bounds=(0, float('inf')), mode='2d')
+ _singular_range_check(self._scale[1], 'scale-y', bounds=(0, float('inf')), mode='2d')
+ _singular_range_check(self._scale[2], 'scale-z', bounds=(0, float('inf')), mode='2d')
+ self.scale_1_sampler = Uniform(self._scale[0, 0], self._scale[0, 1], validate_args=False)
+ self.scale_2_sampler = Uniform(self._scale[1, 0], self._scale[1, 1], validate_args=False)
+ self.scale_3_sampler = Uniform(self._scale[2, 0], self._scale[2, 1], validate_args=False)
+
+ self.yaw_sampler = Uniform(degrees[0][0], degrees[0][1], validate_args=False)
+ self.pitch_sampler = Uniform(degrees[1][0], degrees[1][1], validate_args=False)
+ self.roll_sampler = Uniform(degrees[2][0], degrees[2][1], validate_args=False)
+
+ self.uniform_sampler = Uniform(
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ batch_size = batch_shape[0]
+ depth = batch_shape[-3]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ if not (
+ type(depth) is int and depth > 0 and type(height) is int and height > 0 and type(width) is int and width > 0
+ ):
+ raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
+
+ _device, _dtype = _extract_device_dtype([self.degrees, self.translate, self.scale, self.shears])
+
+ # degrees = degrees.to(device=device, dtype=dtype)
+ yaw = _adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch)
+ pitch = _adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch)
+ roll = _adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch)
+ angles = torch.stack([yaw, pitch, roll], dim=1)
+
+ # compute tensor ranges
+ if self._scale is not None:
+ scale = torch.stack(
+ [
+ _adapted_rsampling((batch_size,), self.scale_1_sampler, same_on_batch),
+ _adapted_rsampling((batch_size,), self.scale_2_sampler, same_on_batch),
+ _adapted_rsampling((batch_size,), self.scale_3_sampler, same_on_batch),
+ ],
+ dim=1,
+ )
+ else:
+ scale = torch.ones(batch_size, device=_device, dtype=_dtype).reshape(batch_size, 1).repeat(1, 3)
+
+ if self._translate is not None:
+ max_dx: torch.Tensor = self._translate[0] * width
+ max_dy: torch.Tensor = self._translate[1] * height
+ max_dz: torch.Tensor = self._translate[2] * depth
+ # translations should be in x,y,z
+ translations = torch.stack(
+ [
+ (_adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch) - 0.5) * max_dx * 2,
+ (_adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch) - 0.5) * max_dy * 2,
+ (_adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch) - 0.5) * max_dz * 2,
+ ],
+ dim=1,
+ )
+ else:
+ translations = torch.zeros((batch_size, 3), device=_device, dtype=_dtype)
+
+ # center should be in x,y,z
+ center: torch.Tensor = torch.tensor([width, height, depth], device=_device, dtype=_dtype).view(1, 3) / 2.0 - 0.5
+ center = center.expand(batch_size, -1)
+
+ if self.shears is not None:
+ sxy = _adapted_rsampling((batch_size,), self.sxy_sampler, same_on_batch)
+ sxz = _adapted_rsampling((batch_size,), self.sxz_sampler, same_on_batch)
+ syx = _adapted_rsampling((batch_size,), self.syx_sampler, same_on_batch)
+ syz = _adapted_rsampling((batch_size,), self.syz_sampler, same_on_batch)
+ szx = _adapted_rsampling((batch_size,), self.szx_sampler, same_on_batch)
+ szy = _adapted_rsampling((batch_size,), self.szy_sampler, same_on_batch)
+ else:
+ sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
+
+ return dict(
+ translations=torch.as_tensor(translations, device=_device, dtype=_dtype),
+ center=torch.as_tensor(center, device=_device, dtype=_dtype),
+ scale=torch.as_tensor(scale, device=_device, dtype=_dtype),
+ angles=torch.as_tensor(angles, device=_device, dtype=_dtype),
+ sxy=torch.as_tensor(sxy, device=_device, dtype=_dtype),
+ sxz=torch.as_tensor(sxz, device=_device, dtype=_dtype),
+ syx=torch.as_tensor(syx, device=_device, dtype=_dtype),
+ syz=torch.as_tensor(syz, device=_device, dtype=_dtype),
+ szx=torch.as_tensor(szx, device=_device, dtype=_dtype),
+ szy=torch.as_tensor(szy, device=_device, dtype=_dtype),
+ )
+
+
+class CropGenerator3D(RandomGeneratorBase):
+ r"""Get parameters for ```crop``` transformation for crop transform.
+
+ Args:
+ size (tuple): Desired size of the crop operation, like (d, h, w).
+ If tensor, it must be (B, 3).
+ resize_to (tuple): Desired output size of the crop, like (d, h, w). If None, no resize will be performed.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ def __init__(
+ self,
+ size: Union[Tuple[int, int, int], torch.Tensor],
+ resize_to: Optional[Tuple[int, int, int]] = None
+ ) -> None:
+ super().__init__()
+ self.size = size
+ self.resize_to = resize_to
+
+ def __repr__(self) -> str:
+ repr = f"crop_size={self.size}"
+ if self.resize_to is not None:
+ repr += f", resize_to={self.resize_to}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self.rand_sampler = Uniform(
+ torch.tensor(0., device=device, dtype=dtype), torch.tensor(1., device=device, dtype=dtype))
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size, _, depth, height, width = batch_shape
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])
+
+ if not isinstance(self.size, torch.Tensor):
+ size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ else:
+ size = self.size.to(device=_device, dtype=_dtype)
+ if size.shape != torch.Size([batch_size, 3]):
+ raise AssertionError(
+ "If `size` is a tensor, it must be shaped as (B, 3). "
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
+ )
+ if not (
+ isinstance(depth, (int,)) and isinstance(height, (int,)) and isinstance(width, (int,))
+ and depth > 0 and height > 0 and width > 0
+ ):
+ raise AssertionError(f"`batch_shape` should not contain negative values. Got {(batch_shape)}.")
+
+ x_diff = width - size[:, 2] + 1
+ y_diff = height - size[:, 1] + 1
+ z_diff = depth - size[:, 0] + 1
+
+ if (x_diff < 0).any() or (y_diff < 0).any() or (z_diff < 0).any():
+ raise ValueError(
+ f"input_size {(depth, height, width)} cannot be smaller than crop size {str(size)} in any dimension.")
+
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
+ dst=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
+ )
+
+ x_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+ y_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+ z_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+
+ x_start = (x_start * x_diff).floor()
+ y_start = (y_start * y_diff).floor()
+ z_start = (z_start * z_diff).floor()
+
+ crop_src = bbox_generator3d(
+ x_start.view(-1),
+ y_start.view(-1),
+ z_start.view(-1),
+ size[:, 2] - 1,
+ size[:, 1] - 1,
+ size[:, 0] - 1,
+ )
+
+ if self.resize_to is None:
+ crop_dst = bbox_generator3d(
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ size[:, 2] - 1,
+ size[:, 1] - 1,
+ size[:, 0] - 1,
+ )
+ else:
+ if not (
+ len(self.resize_to) == 3
+ and isinstance(self.resize_to[0], (int,))
+ and isinstance(self.resize_to[1], (int,))
+ and isinstance(self.resize_to[2], (int,))
+ and self.resize_to[0] > 0
+ and self.resize_to[1] > 0
+ and self.resize_to[2] > 0
+ ):
+ raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {self.resize_to}.")
+ crop_dst = torch.tensor(
+ [
+ [
+ [0, 0, 0],
+ [self.resize_to[-1] - 1, 0, 0],
+ [self.resize_to[-1] - 1, self.resize_to[-2] - 1, 0],
+ [0, self.resize_to[-2] - 1, 0],
+ [0, 0, self.resize_to[-3] - 1],
+ [self.resize_to[-1] - 1, 0, self.resize_to[-3] - 1],
+ [self.resize_to[-1] - 1, self.resize_to[-2] - 1, self.resize_to[-3] - 1],
+ [0, self.resize_to[-2] - 1, self.resize_to[-3] - 1],
+ ]
+ ],
+ device=_device,
+ dtype=_dtype,
+ ).repeat(batch_size, 1, 1)
+
+ return dict(src=crop_src.to(device=_device), dst=crop_dst.to(device=_device))
+
+
+class RotationGenerator3D(RandomGeneratorBase):
+ r"""Get parameters for ``rotate`` for a random 3D rotate transform.
+
+ Args:
+ degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
+ If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
+ If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
+ If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
+ and (-c, c).
+ If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
+ (a, b), (m, n) and (x, y).
+ Set to 0 to deactivate rotations.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - yaw (torch.Tensor): element-wise rotation yaws with a shape of (B,).
+ - pitch (torch.Tensor): element-wise rotation pitches with a shape of (B,).
+ - roll (torch.Tensor): element-wise rotation rolls with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ def __init__(
+ self,
+ degrees: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
+ ]
+ ) -> None:
+ super().__init__()
+ self.degrees = degrees
+
+ def __repr__(self) -> str:
+ repr = f"degrees={self.degrees}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ degrees = _tuple_range_reader(self.degrees, 3, device, dtype)
+ self.yaw_sampler = Uniform(degrees[0][0], degrees[0][1], validate_args=False)
+ self.pitch_sampler = Uniform(degrees[1][0], degrees[1][1], validate_args=False)
+ self.roll_sampler = Uniform(degrees[2][0], degrees[2][1], validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.degrees])
+
+ return dict(
+ yaw=_adapted_rsampling(
+ (batch_size,), self.yaw_sampler, same_on_batch).to(device=_device, dtype=_dtype),
+ pitch=_adapted_rsampling(
+ (batch_size,), self.pitch_sampler, same_on_batch).to(device=_device, dtype=_dtype),
+ roll=_adapted_rsampling(
+ (batch_size,), self.roll_sampler, same_on_batch).to(device=_device, dtype=_dtype),
+ )
+
+
+class MotionBlurGenerator3D(RandomGeneratorBase):
+ r"""Get parameters for motion blur.
+
+ Args:
+ kernel_size: motion kernel size (odd and positive).
+ If int, the kernel will have a fixed size.
+ If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
+ angle: angle of the motion blur in degrees (anti-clockwise rotation).
+ If float, it will generate the value from (-angle, angle).
+ direction: forward/backward direction of the motion blur.
+ Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
+ while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
+ uniformly (but still angled) motion blur.
+ If float, it will generate the value from (-direction, direction).
+ If Tuple[int, int], it will randomly generate the value from the range.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+
+ def __init__(
+ self,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
+ ],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
+ ) -> None:
+ super().__init__()
+ self.kernel_size = kernel_size
+ self.angle = angle
+ self.direction = direction
+
+ def __repr__(self) -> str:
+ repr = f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ angle: torch.Tensor = _tuple_range_reader(self.angle, 3, device=device, dtype=dtype)
+ direction = _range_bound(self.direction, 'direction', center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
+ if isinstance(self.kernel_size, int):
+ if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):
+ raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {self.kernel_size}.")
+ self.ksize_sampler = Uniform(self.kernel_size // 2, self.kernel_size // 2, validate_args=False)
+ elif isinstance(self.kernel_size, tuple):
+ # kernel_size is fixed across the batch
+ if len(self.kernel_size) != 2:
+ raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {self.kernel_size}.")
+ self.ksize_sampler = Uniform(self.kernel_size[0] // 2, self.kernel_size[1] // 2, validate_args=False)
+ else:
+ raise TypeError(f"Unsupported type: {type(self.kernel_size)}")
+
+ self.yaw_sampler = Uniform(angle[0][0], angle[0][1], validate_args=False)
+ self.pitch_sampler = Uniform(angle[1][0], angle[1][1], validate_args=False)
+ self.roll_sampler = Uniform(angle[2][0], angle[2][1], validate_args=False)
+ self.direction_sampler = Uniform(direction[0], direction[1], validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ # self.ksize_factor.expand((batch_size, -1))
+ _device, _dtype = _extract_device_dtype([self.angle, self.direction])
+ yaw_factor = _adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch)
+ pitch_factor = _adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch)
+ roll_factor = _adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch)
+ angle_factor = torch.stack([yaw_factor, pitch_factor, roll_factor], dim=1)
+
+ direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)
+ ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1
+
+ return dict(
+ ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
+ angle_factor=angle_factor.to(device=_device, dtype=_dtype),
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype),
+ )
+
+
+class PerspectiveGenerator3D(RandomGeneratorBase):
+ r"""Get parameters for ``perspective`` for a random perspective transform.
+
+ Args:
+ distortion_scale: controls the degree of distortion and ranges from 0 to 1.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - src (torch.Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): perspective target bounding boxes with a shape (B, 8, 3).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+ def __init__(self, distortion_scale: Union[torch.Tensor, float] = 0.5) -> None:
+ super().__init__()
+ self.distortion_scale = distortion_scale
+
+ def __repr__(self) -> str:
+ repr = f"distortion_scale={self.distortion_scale}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self._distortion_scale = torch.as_tensor(self.distortion_scale, device=device, dtype=dtype)
+ if not (self._distortion_scale.dim() == 0 and 0 <= self._distortion_scale <= 1):
+ raise AssertionError(
+ f"'distortion_scale' must be a scalar within [0, 1]. Got {self._distortion_scale}")
+ self.rand_sampler = Uniform(
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ depth = batch_shape[-3]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.distortion_scale])
+
+ start_points: torch.Tensor = torch.tensor(
+ [
+ [
+ [0.0, 0, 0],
+ [width - 1, 0, 0],
+ [width - 1, height - 1, 0],
+ [0, height - 1, 0],
+ [0.0, 0, depth - 1],
+ [width - 1, 0, depth - 1],
+ [width - 1, height - 1, depth - 1],
+ [0, height - 1, depth - 1],
+ ]
+ ],
+ device=_device,
+ dtype=_dtype,
+ ).expand(batch_size, -1, -1)
+
+ # generate random offset not larger than half of the image
+ fx = self._distortion_scale * width / 2
+ fy = self._distortion_scale * height / 2
+ fz = self._distortion_scale * depth / 2
+
+ factor = torch.stack([fx, fy, fz], dim=0).view(-1, 1, 3).to(device=_device, dtype=_dtype)
+
+ rand_val: torch.Tensor = _adapted_rsampling(
+ start_points.shape, self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+
+ pts_norm = torch.tensor(
+ [[[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]],
+ device=_device,
+ dtype=_dtype,
+ )
+ end_points = start_points + factor * rand_val * pts_norm
+
+ return dict(
+ start_points=start_points,
+ end_points=end_points,
+ )
+
+
+@_deprecated(replace_with=RotationGenerator3D.__name__)
def random_rotation_generator3d(
batch_size: int,
degrees: torch.Tensor,
@@ -45,6 +626,7 @@ def random_rotation_generator3d(
)
+@_deprecated(replace_with=AffineGenerator3D.__name__)
def random_affine_generator3d(
batch_size: int,
depth: int,
@@ -171,6 +753,7 @@ def random_affine_generator3d(
)
+@_deprecated(replace_with=MotionBlurGenerator3D.__name__)
def random_motion_blur_generator3d(
batch_size: int,
kernel_size: Union[int, Tuple[int, int]],
@@ -296,17 +879,19 @@ def center_crop_generator3d(
# [x, y, z] origin
# top-left-front, top-right-front, bottom-right-front, bottom-left-front
# top-left-back, top-right-back, bottom-right-back, bottom-left-back
+ # Note: DeprecationWarning: an integer is required (got type float).
+ # Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
points_src: torch.Tensor = torch.tensor(
[
[
- [start_x, start_y, start_z],
- [end_x, start_y, start_z],
- [end_x, end_y, start_z],
- [start_x, end_y, start_z],
- [start_x, start_y, end_z],
- [end_x, start_y, end_z],
- [end_x, end_y, end_z],
- [start_x, end_y, end_z],
+ [int(start_x), int(start_y), int(start_z)],
+ [int(end_x), int(start_y), int(start_z)],
+ [int(end_x), int(end_y), int(start_z)],
+ [int(start_x), int(end_y), int(start_z)],
+ [int(start_x), int(start_y), int(end_z)],
+ [int(end_x), int(start_y), int(end_z)],
+ [int(end_x), int(end_y), int(end_z)],
+ [int(start_x), int(end_y), int(end_z)],
]
],
device=device,
@@ -335,6 +920,7 @@ def center_crop_generator3d(
return dict(src=points_src, dst=points_dst)
+@_deprecated(replace_with=CropGenerator3D.__name__)
def random_crop_generator3d(
batch_size: int,
input_size: Tuple[int, int, int],
@@ -457,6 +1043,7 @@ def random_crop_generator3d(
return dict(src=crop_src.to(device=_device), dst=crop_dst.to(device=_device))
+@_deprecated(replace_with=PerspectiveGenerator3D.__name__)
def random_perspective_generator3d(
batch_size: int,
depth: int,
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 308f017b8..0acc3043f 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -32,7 +32,7 @@ def _range_bound(
# Currently, single value factor will not out of scope as long as the user provided it.
# Note: I personally think throw an error will be better than a coarse clamp.
factor_bound = factor.repeat(2) * torch.tensor([-1.0, 1.0], device=factor.device, dtype=factor.dtype) + center
- factor_bound = factor_bound.clamp(bounds[0], bounds[1])
+ factor_bound = factor_bound.clamp(bounds[0], bounds[1]).to(device=device, dtype=dtype)
else:
factor_bound = torch.as_tensor(factor, device=device, dtype=dtype)
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 8236e6ed5..e4596b8df 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -1,11 +1,34 @@
import warnings
-from typing import Any, List, Optional, Tuple
+from functools import partial, wraps
+from inspect import isclass, isfunction
+from typing import Any, Callable, List, Optional, Tuple
import torch
from kornia.utils._compat import solve, torch_version_geq
+def _deprecated(func: Callable = None, replace_with: Optional[str] = None):
+ if func is None:
+ return partial(_deprecated, replace_with=replace_with)
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ name: str = ""
+ if isclass(func):
+ name = func.__class__.__name__
+ if isfunction(func):
+ name = func.__name__
+ if replace_with is not None:
+ warnings.warn(f"`{name}` is deprecated in favor of `{replace_with}`.", category=DeprecationWarning)
+ else:
+ warnings.warn(
+ f"`{name}` is deprecated and will be removed in the future versions.", category=DeprecationWarning)
+ return func(*args, **kwargs)
+
+ return wrapper
+
+
def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:
"""Check if all the input are in the same device (only if when they are torch.Tensor).
diff --git a/requirements/dev.txt b/requirements/dev.txt
index da1a38bc6..e774ad883 100644
--- a/requirements/dev.txt
+++ b/requirements/dev.txt
@@ -1,5 +1,6 @@
pytest==6.2.5
pytest-flake8==1.0.7
+flake8==3.9.2 # flake8==4.0.1 is buggy
pytest-cov==3.0.0
pytest-mypy==0.8.1
pytest-xdist==2.4.0
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index a3faca343..dc4eb126d 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -137,25 +137,31 @@ class CommonTests(BaseTester):
# generate_parameters can be called and returns the correct amount of parameters
batch_shape = (4, 3, 5, 6)
- generated_params = augmentation.generate_parameters(batch_shape)
+ generated_params = augmentation.forward_parameters(batch_shape)
assert isinstance(generated_params, dict)
# compute_transformation can be called and returns the correct shaped transformation matrix
- expected_transformation_shape = torch.Size((batch_shape[0], 3, 3))
+ expected_transformation_shape = torch.Size((generated_params['batch_prob'].sum(), 3, 3))
test_input = torch.ones(batch_shape, device=self.device, dtype=self.dtype)
- transformation = augmentation.compute_transformation(test_input, generated_params)
+ transformation = augmentation.compute_transformation(
+ test_input[generated_params['batch_prob']], generated_params)
assert transformation.shape == expected_transformation_shape
# apply_transform can be called and returns the correct batch sized output
- output = augmentation.apply_transform(test_input, generated_params, transformation)
- assert output.shape[0] == batch_shape[0]
+ if generated_params['batch_prob'].sum() != 0:
+ output = augmentation.apply_transform(
+ test_input[generated_params['batch_prob']], generated_params, transformation)
+ assert output.shape[0] == generated_params['batch_prob'].sum()
+ else:
+ # Re-generate parameters if 0 batch size
+ self._test_smoke_implementation(params)
def _test_smoke_call_implementation(self, params):
batch_shape = (4, 3, 5, 6)
expected_transformation_shape = torch.Size((batch_shape[0], 3, 3))
test_input = torch.ones(batch_shape, device=self.device, dtype=self.dtype)
augmentation = self._create_augmentation_from_params(**params, return_transform=False)
- generated_params = augmentation.generate_parameters(batch_shape)
+ generated_params = augmentation.forward_parameters(batch_shape)
test_transform = torch.rand(expected_transformation_shape, device=self.device, dtype=self.dtype)
output = augmentation(test_input, params=generated_params)
@@ -182,7 +188,7 @@ class CommonTests(BaseTester):
expected_transformation_shape = torch.Size((batch_shape[0], 3, 3))
test_input = torch.ones(batch_shape, device=self.device, dtype=self.dtype)
augmentation = self._create_augmentation_from_params(**params, return_transform=True)
- generated_params = augmentation.generate_parameters(batch_shape)
+ generated_params = augmentation.forward_parameters(batch_shape)
test_transform = torch.rand(expected_transformation_shape, device=self.device, dtype=self.dtype)
output, transformation = augmentation(test_input, params=generated_params)
diff --git a/test/augmentation/test_augmentation_mix.py b/test/augmentation/test_augmentation_mix.py
index 945730b39..4d96881b1 100644
--- a/test/augmentation/test_augmentation_mix.py
+++ b/test/augmentation/test_augmentation_mix.py
@@ -8,7 +8,7 @@ class TestRandomMixUp:
def test_smoke(self, device, dtype):
f = RandomMixUp()
repr = "RandomMixUp(lambda_val=None, p=1.0, p_batch=1.0, same_on_batch=False)"
- assert str(f) == repr
+ assert str(f) == repr, str(f)
def test_random_mixup_p1(self, device, dtype):
torch.manual_seed(0)
@@ -96,17 +96,16 @@ class TestRandomMixUp:
class TestRandomCutMix:
- def test_smoke(self, device, dtype):
- f = RandomCutMix(width=3, height=3)
+ def test_smoke(self):
+ f = RandomCutMix()
repr = (
- "RandomCutMix(num_mix=1, beta=None, cut_size=None, height=3, width=3, p=1.0, "
- "p_batch=1.0, same_on_batch=False)"
+ "RandomCutMix(cut_size=None, beta=None, num_mix=1, p=1.0, p_batch=1.0, same_on_batch=False)"
)
assert str(f) == repr
def test_random_mixup_p1(self, device, dtype):
torch.manual_seed(76)
- f = RandomCutMix(width=4, height=3, p=1.0)
+ f = RandomCutMix(p=1.0)
input = torch.stack(
[torch.ones(1, 3, 4, device=device, dtype=dtype), torch.zeros(1, 3, 4, device=device, dtype=dtype)]
@@ -133,7 +132,7 @@ class TestRandomCutMix:
def test_random_mixup_p0(self, device, dtype):
torch.manual_seed(76)
- f = RandomCutMix(p=0.0, width=4, height=3)
+ f = RandomCutMix(p=0.0)
input = torch.stack(
[torch.ones(1, 3, 4, device=device, dtype=dtype), torch.zeros(1, 3, 4, device=device, dtype=dtype)]
@@ -151,7 +150,7 @@ class TestRandomCutMix:
torch.manual_seed(76)
# beta 0 => resample 0.5 area
# beta cannot be 0 after torch 1.8.0
- f = RandomCutMix(beta=1e-7, width=4, height=3, p=1.0)
+ f = RandomCutMix(beta=1e-7, p=1.0)
input = torch.stack(
[torch.ones(1, 3, 4, device=device, dtype=dtype), torch.zeros(1, 3, 4, device=device, dtype=dtype)]
@@ -177,7 +176,7 @@ class TestRandomCutMix:
def test_random_mixup_num2(self, device, dtype):
torch.manual_seed(76)
- f = RandomCutMix(width=4, height=3, num_mix=5, p=1.0)
+ f = RandomCutMix(num_mix=5, p=1.0)
input = torch.stack(
[torch.ones(1, 3, 4, device=device, dtype=dtype), torch.zeros(1, 3, 4, device=device, dtype=dtype)]
@@ -211,7 +210,7 @@ class TestRandomCutMix:
def test_random_mixup_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- f = RandomCutMix(same_on_batch=True, width=4, height=3, p=1.0)
+ f = RandomCutMix(same_on_batch=True, p=1.0)
input = torch.stack(
[torch.ones(1, 3, 4, device=device, dtype=dtype), torch.zeros(1, 3, 4, device=device, dtype=dtype)]
diff --git a/test/augmentation/test_backward.py b/test/augmentation/test_backward.py
index 64a38de09..5820b2e7a 100644
--- a/test/augmentation/test_backward.py
+++ b/test/augmentation/test_backward.py
@@ -51,7 +51,7 @@ class TestColorJitterBackward:
if len(list(aug.parameters())) != 0:
mse = nn.MSELoss()
- opt = torch.optim.SGD(aug.parameters(), lr=0.1)
+ opt = torch.optim.SGD(aug.parameters(), lr=10)
loss = mse(output, torch.ones_like(output) * 2)
loss.backward()
opt.step()
@@ -135,57 +135,60 @@ class TestRandomAffineBackward:
mse = nn.MSELoss()
opt = torch.optim.SGD(aug.parameters(), lr=10)
loss = mse(output, torch.ones_like(output) * 2)
- loss.backward()
+ try:
+ loss.backward()
+ except Exception as e:
+ assert False, (list(aug.named_parameters()), e)
opt.step()
if not isinstance(degrees, (int, float, list, tuple)):
- assert isinstance(aug.degrees, torch.Tensor)
+ assert isinstance(aug._param_generator.degrees, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.degrees.is_cuda:
+ if resample == 'nearest' and aug._param_generator.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.0):
+ elif resample == 'nearest' or torch.all(aug._param_generator.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0
+ assert (degrees.to(device=device, dtype=dtype) - aug._param_generator.degrees.data).sum() == 0
else:
- assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() != 0
+ assert (degrees.to(device=device, dtype=dtype) - aug._param_generator.degrees.data).sum() != 0
if not isinstance(translate, (int, float, list, tuple)):
- assert isinstance(aug.translate, torch.Tensor)
+ assert isinstance(aug._param_generator.translate, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.translate.is_cuda:
+ if resample == 'nearest' and aug._param_generator.translate.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.translate._grad == 0.0):
+ elif resample == 'nearest' or torch.all(aug._param_generator.translate._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (translate.to(device=device, dtype=dtype) - aug.translate.data).sum() == 0
+ assert (translate.to(device=device, dtype=dtype) - aug._param_generator.translate.data).sum() == 0
else:
- assert (translate.to(device=device, dtype=dtype) - aug.translate.data).sum() != 0
+ assert (translate.to(device=device, dtype=dtype) - aug._param_generator.translate.data).sum() != 0
if not isinstance(scale, (int, float, list, tuple)):
- assert isinstance(aug.scale, torch.Tensor)
+ assert isinstance(aug._param_generator.scale, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.scale.is_cuda:
+ if resample == 'nearest' and aug._param_generator.scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.scale._grad == 0.0):
+ elif resample == 'nearest' or torch.all(aug._param_generator.scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() == 0
+ assert (scale.to(device=device, dtype=dtype) - aug._param_generator.scale.data).sum() == 0
else:
- assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() != 0
+ assert (scale.to(device=device, dtype=dtype) - aug._param_generator.scale.data).sum() != 0
if not isinstance(shear, (int, float, list, tuple)):
- assert isinstance(aug.shear, torch.Tensor)
+ assert isinstance(aug._param_generator.shear, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.shear.is_cuda:
+ if resample == 'nearest' and aug._param_generator.shear.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.shear._grad == 0.0):
+ elif resample == 'nearest' or torch.all(aug._param_generator.shear._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (shear.to(device=device, dtype=dtype) - aug.shear.data).sum() == 0
+ assert (shear.to(device=device, dtype=dtype) - aug._param_generator.shear.data).sum() == 0
else:
- assert (shear.to(device=device, dtype=dtype) - aug.shear.data).sum() != 0
+ assert (shear.to(device=device, dtype=dtype) - aug._param_generator.shear.data).sum() != 0
class TestRandomRotationBackward:
@@ -225,17 +228,17 @@ class TestRandomRotationBackward:
opt.step()
if not isinstance(degrees, (int, float, list, tuple)):
- assert isinstance(aug.degrees, torch.Tensor)
+ assert isinstance(aug._param_generator.degrees, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.degrees.is_cuda:
+ if resample == 'nearest' and aug._param_generator.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.0):
+ elif resample == 'nearest' or torch.all(aug._param_generator.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0
+ assert (degrees.to(device=device, dtype=dtype) - aug._param_generator.degrees.data).sum() == 0
else:
- assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() != 0
+ assert (degrees.to(device=device, dtype=dtype) - aug._param_generator.degrees.data).sum() != 0
class TestRandomPerspectiveBackward:
@@ -276,17 +279,21 @@ class TestRandomPerspectiveBackward:
opt.step()
if not isinstance(distortion_scale, (float, int)):
- assert isinstance(aug.distortion_scale, torch.Tensor)
+ assert isinstance(aug._param_generator.distortion_scale, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.distortion_scale.is_cuda:
+ if resample == 'nearest' and aug._param_generator.distortion_scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.distortion_scale._grad == 0.0):
+ elif resample == 'nearest' or torch.all(aug._param_generator.distortion_scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (distortion_scale.to(device=device, dtype=dtype) - aug.distortion_scale.data).sum() == 0
+ assert (
+ distortion_scale.to(device=device, dtype=dtype) - aug._param_generator.distortion_scale.data
+ ).sum() == 0
else:
- assert (distortion_scale.to(device=device, dtype=dtype) - aug.distortion_scale.data).sum() != 0
+ assert (
+ distortion_scale.to(device=device, dtype=dtype) - aug._param_generator.distortion_scale.data
+ ).sum() != 0
class TestRandomMotionBlurBackward:
@@ -328,26 +335,26 @@ class TestRandomMotionBlurBackward:
opt.step()
if not isinstance(angle, (float, int, list, tuple)):
- assert isinstance(aug.angle, torch.Tensor)
- if resample == 'nearest' and aug.angle.is_cuda:
+ assert isinstance(aug._param_generator.angle, torch.Tensor)
+ if resample == 'nearest' and aug._param_generator.angle.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.angle._grad == 0.0):
+ elif resample == 'nearest' or torch.all(aug._param_generator.angle._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() == 0
+ assert (angle.to(device=device, dtype=dtype) - aug._param_generator.angle.data).sum() == 0
else:
# Assert if param not updated
- assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() != 0
+ assert (angle.to(device=device, dtype=dtype) - aug._param_generator.angle.data).sum() != 0
if not isinstance(direction, (list, tuple)):
- assert isinstance(aug.direction, torch.Tensor)
- if torch.all(aug.direction._grad == 0.0):
+ assert isinstance(aug._param_generator.direction, torch.Tensor)
+ if torch.all(aug._param_generator.direction._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (direction.to(device=device, dtype=dtype) - aug.direction.data).sum() == 0
+ assert (direction.to(device=device, dtype=dtype) - aug._param_generator.direction.data).sum() == 0
else:
# Assert if param not updated
- assert (direction.to(device=device, dtype=dtype) - aug.direction.data).sum() != 0
+ assert (direction.to(device=device, dtype=dtype) - aug._param_generator.direction.data).sum() != 0
class TestRandomSharpnessBackward:
@@ -379,9 +386,9 @@ class TestRandomSharpnessBackward:
opt.step()
if not isinstance(sharpness, (float, int, list, tuple)):
- assert isinstance(aug.sharpness, torch.Tensor)
+ assert isinstance(aug._param_generator.sharpness, torch.Tensor)
# Assert if param not updated
- assert (sharpness.to(device=device, dtype=dtype) - aug.sharpness.data).sum() != 0
+ assert (sharpness.to(device=device, dtype=dtype) - aug._param_generator.sharpness.data).sum() != 0
class TestRandomResizedCropBackward:
diff --git a/test/augmentation/test_backward_3d.py b/test/augmentation/test_backward_3d.py
index 7280c5879..c982ffd12 100644
--- a/test/augmentation/test_backward_3d.py
+++ b/test/augmentation/test_backward_3d.py
@@ -197,17 +197,17 @@ class TestRandomRotation3DBackward:
opt.step()
if not isinstance(degrees, (int, float, list, tuple)):
- assert isinstance(aug.degrees, torch.Tensor)
+ assert isinstance(aug._param_generator.degrees, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.degrees.is_cuda:
+ if resample == 'nearest' and aug._param_generator.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.0):
+ elif resample == 'nearest' or torch.all(aug._param_generator.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0
+ assert (degrees.to(device=device, dtype=dtype) - aug._param_generator.degrees.data).sum() == 0
else:
- assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() != 0
+ assert (degrees.to(device=device, dtype=dtype) - aug._param_generator.degrees.data).sum() != 0
class TestRandomPerspective3DBackward:
@@ -248,17 +248,21 @@ class TestRandomPerspective3DBackward:
opt.step()
if not isinstance(distortion_scale, (float, int)):
- assert isinstance(aug.distortion_scale, torch.Tensor)
+ assert isinstance(aug._param_generator.distortion_scale, torch.Tensor)
# Assert if param not updated
- if resample == 'nearest' and aug.distortion_scale.is_cuda:
+ if resample == 'nearest' and aug._param_generator.distortion_scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.distortion_scale._grad == 0.0):
+ elif resample == 'nearest' or torch.all(aug._param_generator.distortion_scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (distortion_scale.to(device=device, dtype=dtype) - aug.distortion_scale.data).sum() == 0
+ assert (
+ distortion_scale.to(device=device, dtype=dtype) - aug._param_generator.distortion_scale.data
+ ).sum() == 0
else:
- assert (distortion_scale.to(device=device, dtype=dtype) - aug.distortion_scale.data).sum() != 0
+ assert (
+ distortion_scale.to(device=device, dtype=dtype) - aug._param_generator.distortion_scale.data
+ ).sum() != 0
class TestRandomMotionBlur3DBackward:
@@ -301,23 +305,23 @@ class TestRandomMotionBlur3DBackward:
opt.step()
if not isinstance(angle, (float, int, list, tuple)):
- assert isinstance(aug.angle, torch.Tensor)
- if resample == 'nearest' and aug.angle.is_cuda:
+ assert isinstance(aug._param_generator.angle, torch.Tensor)
+ if resample == 'nearest' and aug._param_generator.angle.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.angle._grad == 0.0):
+ elif resample == 'nearest' or torch.all(aug._param_generator.angle._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() == 0
+ assert (angle.to(device=device, dtype=dtype) - aug._param_generator.angle.data).sum() == 0
else:
# Assert if param not updated
- assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() != 0
+ assert (angle.to(device=device, dtype=dtype) - aug._param_generator.angle.data).sum() != 0
if not isinstance(direction, (list, tuple)):
- assert isinstance(aug.direction, torch.Tensor)
- if torch.all(aug.direction._grad == 0.0):
+ assert isinstance(aug._param_generator.direction, torch.Tensor)
+ if torch.all(aug._param_generator.direction._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
- assert (direction.to(device=device, dtype=dtype) - aug.direction.data).sum() == 0
+ assert (direction.to(device=device, dtype=dtype) - aug._param_generator.direction.data).sum() == 0
else:
# Assert if param not updated
- assert (direction.to(device=device, dtype=dtype) - aug.direction.data).sum() != 0
+ assert (direction.to(device=device, dtype=dtype) - aug._param_generator.direction.data).sum() != 0
diff --git a/test/augmentation/test_base.py b/test/augmentation/test_base.py
index 1ae78f7f3..8f4d397a1 100644
--- a/test/augmentation/test_base.py
+++ b/test/augmentation/test_base.py
@@ -10,9 +10,9 @@ from kornia.testing import assert_close
class TestBasicAugmentationBase:
- def test_smoke(self, device, dtype):
+ def test_smoke(self):
base = _BasicAugmentationBase(p=0.5, p_batch=1.0, same_on_batch=True)
- __repr__ = "p=0.5, p_batch=1.0, same_on_batch=True"
+ __repr__ = "_BasicAugmentationBase(p=0.5, p_batch=1.0, same_on_batch=True)"
assert str(base) == __repr__
def test_infer_input(self, device, dtype):
diff --git a/test/augmentation/test_motionblur.py b/test/augmentation/test_motionblur.py
index 69266dbb7..e4de24a86 100644
--- a/test/augmentation/test_motionblur.py
+++ b/test/augmentation/test_motionblur.py
@@ -67,7 +67,7 @@ class TestRandomMotionBlur:
f._params['ksize_factor'].unique().item(),
f._params['angle_factor'],
f._params['direction_factor'],
- f.border_type.name.lower(),
+ f.flags['border_type'].name.lower(),
)
assert_close(output, expected, rtol=1e-4, atol=1e-4)
@@ -149,7 +149,7 @@ class TestRandomMotionBlur3D:
f._params['ksize_factor'].unique().item(),
f._params['angle_factor'],
f._params['direction_factor'],
- f.border_type.name.lower(),
+ f.flags['border_type'].name.lower(),
)
assert_close(output, expected, rtol=1e-4, atol=1e-4)
diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.py
index 622cf4867..99d885fd0 100644
--- a/test/augmentation/test_random_generator.py
+++ b/test/augmentation/test_random_generator.py
@@ -2,21 +2,19 @@ import pytest
import torch
from kornia.augmentation.random_generator import (
+ AffineGenerator,
center_crop_generator,
- random_affine_generator,
- random_color_jitter_generator,
- random_crop_generator,
- random_crop_size_generator,
+ ColorJitterGenerator,
+ CropGenerator,
+ MotionBlurGenerator,
+ PerspectiveGenerator,
+ PlainUniformGenerator,
+ PosterizeGenerator,
+ ProbabilityGenerator,
random_cutmix_generator,
random_mixup_generator,
- random_motion_blur_generator,
- random_perspective_generator,
- random_posterize_generator,
- random_prob_generator,
- random_rectangles_params_generator,
- random_rotation_generator,
- random_sharpness_generator,
- random_solarize_generator,
+ RectangleEraseGenerator,
+ ResizedCropGenerator,
)
from kornia.testing import assert_close
from kornia.utils._compat import torch_version_geq
@@ -40,8 +38,8 @@ class TestRandomProbGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('p', [0.0, 0.5, 1.0])
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('same_on_batch', [True, False])
- def test_valid_param_combinations(self, p, batch_size, same_on_batch, device, dtype):
- random_prob_generator(batch_size=batch_size, p=p, same_on_batch=same_on_batch)
+ def test_valid_param_combinations(self, p, batch_size, same_on_batch):
+ ProbabilityGenerator(p)(torch.Size([batch_size]), same_on_batch)
@pytest.mark.parametrize(
'p',
@@ -51,9 +49,9 @@ class TestRandomProbGen(RandomGeneratorBaseTests):
(2.0),
],
)
- def test_invalid_param_combinations(self, p, device, dtype):
+ def test_invalid_param_combinations(self, p):
with pytest.raises(Exception):
- random_prob_generator(batch_size=8, p=p)
+ ProbabilityGenerator(p)(torch.Size([8]))
@pytest.mark.parametrize(
'p,expected',
@@ -62,15 +60,15 @@ class TestRandomProbGen(RandomGeneratorBaseTests):
def test_random_gen(self, p, expected, device, dtype):
torch.manual_seed(42)
batch_size = 8
- res = random_prob_generator(batch_size=batch_size, p=p)
- assert (res == torch.tensor(expected)).long().sum() == batch_size
+ res = ProbabilityGenerator(p)(torch.Size([batch_size]))
+ assert (res['probs'] == torch.tensor(expected)).long().sum() == batch_size
@pytest.mark.parametrize("seed,expected", [(42, [False] * 8), (0, [True] * 8)])
def test_same_on_batch(self, seed, expected, device, dtype):
torch.manual_seed(seed)
batch_size = 8
- res = random_prob_generator(batch_size=batch_size, p=0.5, same_on_batch=True)
- assert (res == torch.tensor(expected)).long().sum() == batch_size
+ res = ProbabilityGenerator(0.5)(torch.Size([batch_size]), True)
+ assert (res['probs'] == torch.tensor(expected)).long().sum() == batch_size
class TestColorJitterGen(RandomGeneratorBaseTests):
@@ -83,14 +81,16 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
def test_valid_param_combinations(
self, brightness, contrast, saturation, hue, batch_size, same_on_batch, device, dtype
):
- random_color_jitter_generator(
- batch_size,
- brightness.to(device=device, dtype=dtype) if brightness is not None else None,
- contrast.to(device=device, dtype=dtype) if contrast is not None else None,
- saturation.to(device=device, dtype=dtype) if saturation is not None else None,
- hue.to(device=device, dtype=dtype) if hue is not None else None,
- same_on_batch,
- )
+ ColorJitterGenerator(
+ torch.as_tensor(
+ brightness if brightness is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ torch.as_tensor(
+ contrast if contrast is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ torch.as_tensor(
+ saturation if saturation is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ torch.as_tensor(
+ hue if hue is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ )(torch.Size([batch_size]), same_on_batch)
@pytest.mark.parametrize(
'brightness,contrast,saturation,hue',
@@ -98,33 +98,31 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
# Should be failed if value out of bounds or tensor.shape != [1, 2]
(torch.tensor([-1.0, 2.0]), None, None, None),
(torch.tensor([0.0, 3.0]), None, None, None),
- (torch.tensor(0.0), None, None, None),
(torch.tensor([0.0]), None, None, None),
(torch.tensor([0.0, 1.0, 2.0]), None, None, None),
(None, torch.tensor([-1.0, 2.0]), None, None),
- (None, torch.tensor(0.0), None, None),
(None, torch.tensor([0.0]), None, None),
(None, torch.tensor([0.0, 1.0, 2.0]), None, None),
(None, None, torch.tensor([-1.0, 2.0]), None),
- (None, None, torch.tensor(0.0), None),
(None, None, torch.tensor([0.0]), None),
(None, None, torch.tensor([0.0, 1.0, 2.0]), None),
(None, None, None, torch.tensor([-1.0, 0.0])),
(None, None, None, torch.tensor([0, 1.0])),
- (None, None, None, torch.tensor(0.0)),
(None, None, None, torch.tensor([0.0])),
(None, None, None, torch.tensor([0.0, 1.0, 2.0])),
],
)
def test_invalid_param_combinations(self, brightness, contrast, saturation, hue, device, dtype):
with pytest.raises(Exception):
- random_color_jitter_generator(
- 8,
- brightness.to(device=device, dtype=dtype) if brightness is not None else None,
- contrast.to(device=device, dtype=dtype) if contrast is not None else None,
- saturation.to(device=device, dtype=dtype) if saturation is not None else None,
- hue.to(device=device, dtype=dtype) if hue is not None else None,
- )
+ ColorJitterGenerator(
+ torch.as_tensor(
+ brightness if brightness is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ torch.as_tensor(
+ contrast if contrast is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ torch.as_tensor(
+ saturation if saturation is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ torch.as_tensor(hue if hue is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ )(torch.Size([8]))
def test_random_gen(self, device, dtype):
# TODO(jian): crashes with pytorch 1.10, cuda and fp64
@@ -132,13 +130,12 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
pytest.skip("AssertionError: Tensor-likes are not close!")
torch.manual_seed(42)
batch_size = 8
- jitter_params = random_color_jitter_generator(
- batch_size,
+ jitter_params = ColorJitterGenerator(
brightness=torch.tensor([0.8, 1.2], device=device, dtype=dtype),
contrast=torch.tensor([0.7, 1.3], device=device, dtype=dtype),
saturation=torch.tensor([0.6, 1.4], device=device, dtype=dtype),
hue=torch.tensor([-0.1, 0.1], device=device, dtype=dtype),
- )
+ )(torch.Size([batch_size]))
expected_jitter_params = {
'brightness_factor': torch.tensor(
@@ -178,14 +175,12 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
batch_size = 8
- jitter_params = random_color_jitter_generator(
- batch_size,
+ jitter_params = ColorJitterGenerator(
brightness=torch.tensor([0.8, 1.2], device=device, dtype=dtype),
contrast=torch.tensor([0.7, 1.3], device=device, dtype=dtype),
saturation=torch.tensor([0.6, 1.4], device=device, dtype=dtype),
hue=torch.tensor([-0.1, 0.1], device=device, dtype=dtype),
- same_on_batch=True,
- )
+ )(torch.Size([batch_size]), same_on_batch=True)
expected_res = {
'brightness_factor': torch.tensor([1.1529] * batch_size, device=device, dtype=dtype),
@@ -208,13 +203,8 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, height, width, distortion_scale, batch_size, same_on_batch, device, dtype):
- random_perspective_generator(
- batch_size=8,
- height=height,
- width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch,
- )
+ PerspectiveGenerator(distortion_scale.to(device=device, dtype=dtype))(
+ torch.Size([batch_size, 1, height, width]), same_on_batch)
@pytest.mark.parametrize(
'height,width,distortion_scale',
@@ -229,17 +219,15 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
)
def test_invalid_param_combinations(self, height, width, distortion_scale, device, dtype):
with pytest.raises(Exception):
- random_perspective_generator(
- batch_size=8,
- height=height,
- width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype),
- )
+ PerspectiveGenerator(distortion_scale.to(device=device, dtype=dtype))(
+ torch.Size([8, 1, height, width]))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
- res = random_perspective_generator(batch_size, 200, 200, torch.tensor(0.5, device=device, dtype=dtype))
+ res = PerspectiveGenerator(torch.tensor(0.5, device=device, dtype=dtype))(
+ torch.Size([batch_size, 1, 200, 200]))
+
expected = dict(
start_points=torch.tensor(
[
@@ -265,9 +253,8 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
- res = random_perspective_generator(
- batch_size, 200, 200, torch.tensor(0.5, device=device, dtype=dtype), same_on_batch=True
- )
+ res = PerspectiveGenerator(torch.tensor(0.5, device=device, dtype=dtype))(
+ torch.Size([batch_size, 1, 200, 200]), same_on_batch=True)
expected = dict(
start_points=torch.tensor(
[[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]]], device=device, dtype=dtype
@@ -295,16 +282,12 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
def test_valid_param_combinations(
self, batch_size, height, width, degrees, translate, scale, shear, same_on_batch, device, dtype
):
- random_affine_generator(
- batch_size=batch_size,
- height=height,
- width=width,
+ AffineGenerator(
degrees=degrees.to(device=device, dtype=dtype),
translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
- shear=shear.to(device=device, dtype=dtype) if shear is not None else None,
- same_on_batch=same_on_batch,
- )
+ shear=shear.to(device=device, dtype=dtype) if shear is not None else None
+ )(torch.Size([batch_size, 1, height, width]), same_on_batch)
@pytest.mark.parametrize(
'height,width,degrees,translate,scale,shear',
@@ -318,23 +301,18 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
(100, 100, torch.tensor([10, 20]), None, torch.tensor([1]), None),
(100, 100, torch.tensor([10, 20]), None, torch.tensor([1, 2, 3]), None),
(100, 100, torch.tensor([10, 20]), None, None, torch.tensor([1])),
- (100, 100, torch.tensor([10, 20]), None, None, torch.tensor([1, 2])),
(10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3])),
- (10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3, 4])),
(10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3, 4, 5])),
],
)
def test_invalid_param_combinations(self, height, width, degrees, translate, scale, shear, device, dtype):
with pytest.raises(Exception):
- random_affine_generator(
- batch_size=8,
- height=height,
- width=width,
+ AffineGenerator(
degrees=degrees.to(device=device, dtype=dtype),
translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
- shear=shear.to(device=device, dtype=dtype) if shear is not None else None,
- )
+ shear=shear.to(device=device, dtype=dtype) if shear is not None else None
+ )(torch.Size([8, 1, height, width]))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -342,16 +320,12 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
translate = torch.tensor([0.1, 0.1], device=device, dtype=dtype)
scale = torch.tensor([0.7, 1.2], device=device, dtype=dtype)
shear = torch.tensor([[10, 20], [10, 20]], device=device, dtype=dtype)
- res = random_affine_generator(
- batch_size=2,
- height=200,
- width=200,
- degrees=degrees,
- translate=translate,
- scale=scale,
- shear=shear,
- same_on_batch=False,
- )
+ res = AffineGenerator(
+ degrees=degrees.to(device=device, dtype=dtype),
+ translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
+ scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
+ shear=shear.to(device=device, dtype=dtype) if shear is not None else None
+ )(torch.Size([2, 1, 200, 200]))
expected = dict(
translations=torch.tensor([[-4.3821, -9.7371], [4.0358, 11.7457]], device=device, dtype=dtype),
center=torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
@@ -374,16 +348,12 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
translate = torch.tensor([0.1, 0.1], device=device, dtype=dtype)
scale = torch.tensor([0.7, 1.2], device=device, dtype=dtype)
shear = torch.tensor([[10, 20], [10, 20]], device=device, dtype=dtype)
- res = random_affine_generator(
- batch_size=2,
- height=200,
- width=200,
- degrees=degrees,
- translate=translate,
- scale=scale,
- shear=shear,
- same_on_batch=True,
- )
+ res = AffineGenerator(
+ degrees=degrees.to(device=device, dtype=dtype),
+ translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
+ scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
+ shear=shear.to(device=device, dtype=dtype) if shear is not None else None
+ )(torch.Size([2, 1, 200, 200]), True)
expected = dict(
translations=torch.tensor([[-4.6854, 18.3722], [-4.6854, 18.3722]], device=device, dtype=dtype),
center=torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
@@ -401,42 +371,6 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
assert_close(res['sy'], expected['sy'], rtol=1e-4, atol=1e-4)
-class TestRandomRotationGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('degrees', [torch.tensor([0, 30])])
- @pytest.mark.parametrize('same_on_batch', [True, False])
- def test_valid_param_combinations(self, batch_size, degrees, same_on_batch, device, dtype):
- random_rotation_generator(
- batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=same_on_batch
- )
-
- @pytest.mark.parametrize('degrees', [(torch.tensor(10)), (torch.tensor([10])), (torch.tensor([10, 20, 30]))])
- def test_invalid_param_combinations(self, degrees, device, dtype):
- batch_size = 8
- with pytest.raises(Exception):
- random_rotation_generator(batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype))
-
- def test_random_gen(self, device, dtype):
- torch.manual_seed(42)
- degrees = torch.tensor([10, 20])
- res = random_rotation_generator(
- batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=False
- )
- expected = dict(degrees=torch.tensor([18.8227, 19.1500], device=device, dtype=dtype))
- assert res.keys() == expected.keys()
- assert_close(res['degrees'], expected['degrees'])
-
- def test_same_on_batch(self, device, dtype):
- torch.manual_seed(42)
- degrees = torch.tensor([10, 20])
- res = random_rotation_generator(
- batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=True
- )
- expected = dict(degrees=torch.tensor([18.8227, 18.8227], device=device, dtype=dtype))
- assert res.keys() == expected.keys()
- assert_close(res['degrees'], expected['degrees'])
-
-
class TestRandomCropGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('batch_size', [0, 2])
@pytest.mark.parametrize('input_size', [(200, 200)])
@@ -446,15 +380,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
def test_valid_param_combinations(self, batch_size, input_size, size, resize_to, same_on_batch, device, dtype):
if isinstance(size, torch.Tensor):
size = size.repeat(batch_size, 1).to(device=device, dtype=dtype)
- random_crop_generator(
- batch_size=batch_size,
- input_size=input_size,
- size=size,
- resize_to=resize_to,
- same_on_batch=same_on_batch,
- device=device,
- dtype=dtype,
- )
+ CropGenerator(size, resize_to)(torch.Size([batch_size, 1, *input_size]), same_on_batch)
@pytest.mark.parametrize(
'input_size,size,resize_to',
@@ -463,21 +389,15 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
def test_invalid_param_combinations(self, input_size, size, resize_to, device, dtype):
batch_size = 2
with pytest.raises(Exception):
- random_crop_generator(
- batch_size=batch_size,
- input_size=input_size,
- size=size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size,
- resize_to=resize_to,
- )
+ CropGenerator(
+ size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size, resize_to
+ )(torch.Size([batch_size, 1, *input_size]))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
- res = random_crop_generator(
- batch_size=2,
- input_size=(100, 100),
- size=torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype),
- resize_to=(200, 200),
- )
+ res = CropGenerator(
+ torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype), (200, 200)
+ )(torch.Size([2, 1, 100, 100]))
expected = dict(
src=torch.tensor(
[[[36, 19], [95, 19], [95, 68], [36, 68]], [[19, 29], [98, 29], [98, 98], [19, 98]]],
@@ -497,13 +417,9 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- res = random_crop_generator(
- batch_size=2,
- input_size=(100, 100),
- size=torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype),
- resize_to=(200, 200),
- same_on_batch=True,
- )
+ res = CropGenerator(
+ torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype), (200, 200)
+ )(torch.Size([2, 1, 100, 100]), True)
expected = dict(
src=torch.tensor(
[[[36, 46], [95, 46], [95, 95], [36, 95]], [[36, 46], [115, 46], [115, 115], [36, 115]]],
@@ -529,13 +445,11 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('ratio', [torch.tensor([0.9, 1.1])])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, size, scale, ratio, same_on_batch, device, dtype):
- random_crop_size_generator(
- batch_size=batch_size,
- size=size,
- scale=scale.to(device=device, dtype=dtype),
- ratio=ratio.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch,
- )
+ ResizedCropGenerator(
+ size,
+ torch.as_tensor(scale, device=device, dtype=dtype),
+ torch.as_tensor(ratio, device=device, dtype=dtype)
+ )(torch.Size([batch_size, 1, 300, 300]), same_on_batch)
@pytest.mark.parametrize(
'size,scale,ratio',
@@ -551,62 +465,81 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
def test_invalid_param_combinations(self, size, scale, ratio, device, dtype):
batch_size = 2
with pytest.raises(Exception):
- random_crop_size_generator(
- batch_size=batch_size,
- size=size,
- scale=scale.to(device=device, dtype=dtype),
- ratio=ratio.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch, # noqa: F821 raises NameError
- )
+ ResizedCropGenerator(
+ size,
+ torch.as_tensor(scale, device=device, dtype=dtype),
+ torch.as_tensor(ratio, device=device, dtype=dtype)
+ )(torch.Size([batch_size, 1, 300, 300]))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
- res = random_crop_size_generator(
- batch_size=8,
- size=(100, 100),
- scale=torch.tensor([0.7, 1.3], device=device, dtype=dtype),
- ratio=torch.tensor([0.9, 1.1], device=device, dtype=dtype),
- same_on_batch=False,
- )
+ res = ResizedCropGenerator(
+ (100, 100),
+ torch.tensor([0.7, 1.3], device=device, dtype=dtype),
+ torch.tensor([0.9, 1.1], device=device, dtype=dtype)
+ )(torch.Size([2, 1, 300, 300]))
expected = dict(
- size=torch.tensor(
- [[99, 94], [91, 95], [90, 96], [87, 86], [94, 98], [87, 81], [85, 93], [83, 90]],
+ src=torch.tensor(
+ [
+ [[3., 12.], [298., 12.], [298., 294.], [3., 294.]],
+ [[8., 20.], [284., 20.], [284., 298.], [8., 298.]]
+ ],
device=device,
dtype=dtype,
- )
- )
- assert res.keys() == expected.keys()
- assert_close(res['size'], expected['size'])
-
- res = random_crop_size_generator(
- batch_size=100,
- size=(100, 100),
- scale=torch.tensor([0.999, 1.0], device=device, dtype=dtype),
- ratio=torch.tensor([1.0, 1.0], device=device, dtype=dtype),
- same_on_batch=False,
+ ),
+ dst=torch.tensor(
+ [
+ [[0., 0.], [99., 0.], [99., 99.], [0., 99.]],
+ [[0., 0.], [99., 0.], [99., 99.], [0., 99.]]
+ ],
+ device=device,
+ dtype=dtype,
+ ),
+ input_size=torch.tensor(
+ [[300, 300], [300, 300]],
+ device=device,
+ dtype=torch.int64,
+ ),
)
- expected = dict(size=torch.tensor([[100, 100]], device=device, dtype=dtype).repeat(100, 1))
assert res.keys() == expected.keys()
- assert_close(res['size'], expected['size'])
+ assert_close(res['src'], expected['src'])
+ assert_close(res['dst'], expected['dst'])
+ assert_close(res['input_size'], expected['input_size'])
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- res = random_crop_size_generator(
- batch_size=8,
- size=(100, 100),
- scale=torch.tensor([0.7, 1.3], device=device, dtype=dtype),
- ratio=torch.tensor([0.9, 1.1], device=device, dtype=dtype),
- same_on_batch=True,
- )
+ res = ResizedCropGenerator(
+ (100, 100),
+ torch.tensor([0.7, 1.3], device=device, dtype=dtype),
+ torch.tensor([0.9, 1.1], device=device, dtype=dtype)
+ )(torch.Size([2, 1, 300, 300]), same_on_batch=True)
expected = dict(
- size=torch.tensor(
- [[99, 95], [99, 95], [99, 95], [99, 95], [99, 95], [99, 95], [99, 95], [99, 95]],
+ src=torch.tensor(
+ [
+ [[5., 0.], [283., 0.], [283., 298.], [5., 298.]],
+ [[5., 0.], [283., 0.], [283., 298.], [5., 298.]]
+ ],
device=device,
dtype=dtype,
- )
+ ),
+ dst=torch.tensor(
+ [
+ [[0., 0.], [99., 0.], [99., 99.], [0., 99.]],
+ [[0., 0.], [99., 0.], [99., 99.], [0., 99.]]
+ ],
+ device=device,
+ dtype=dtype,
+ ),
+ input_size=torch.tensor(
+ [[300, 300], [300, 300]],
+ device=device,
+ dtype=torch.int64,
+ ),
)
assert res.keys() == expected.keys()
- assert_close(res['size'], expected['size'])
+ assert_close(res['src'], expected['src'])
+ assert_close(res['dst'], expected['dst'])
+ assert_close(res['input_size'], expected['input_size'])
class TestRandomRectangleGen(RandomGeneratorBaseTests):
@@ -620,15 +553,11 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
def test_valid_param_combinations(
self, batch_size, height, width, scale, ratio, value, same_on_batch, device, dtype
):
- random_rectangles_params_generator(
- batch_size=batch_size,
- height=height,
- width=width,
+ RectangleEraseGenerator(
scale=scale.to(device=device, dtype=dtype),
ratio=ratio.to(device=device, dtype=dtype),
value=value,
- same_on_batch=same_on_batch,
- )
+ )(torch.Size([batch_size, 1, height, width]), same_on_batch)
@pytest.mark.parametrize(
'height,width,scale,ratio,value',
@@ -647,15 +576,11 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
def test_invalid_param_combinations(self, height, width, scale, ratio, value, device, dtype):
batch_size = 8
with pytest.raises(Exception):
- random_rectangles_params_generator(
- batch_size=batch_size,
- height=height,
- width=width,
+ RectangleEraseGenerator(
scale=scale.to(device=device, dtype=dtype),
ratio=ratio.to(device=device, dtype=dtype),
value=value,
- same_on_batch=same_on_batch, # noqa: F821 raises NameError
- )
+ )(torch.Size([batch_size, 1, height, width]))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -663,9 +588,11 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
scale = torch.tensor([0.7, 1.3], device=device, dtype=dtype)
ratio = torch.tensor([0.7, 1.3], device=device, dtype=dtype)
value = 0.5
- res = random_rectangles_params_generator(
- batch_size=2, height=height, width=width, scale=scale, ratio=ratio, value=value, same_on_batch=False
- )
+ res = RectangleEraseGenerator(
+ scale=scale.to(device=device, dtype=dtype),
+ ratio=ratio.to(device=device, dtype=dtype),
+ value=value,
+ )(torch.Size([2, 1, height, width]))
expected = dict(
widths=torch.tensor([100, 100], device=device, dtype=dtype),
heights=torch.tensor([0, 0], device=device, dtype=dtype),
@@ -686,9 +613,11 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
scale = torch.tensor([0.7, 1.3], device=device, dtype=dtype)
ratio = torch.tensor([0.7, 1.3], device=device, dtype=dtype)
value = 0.5
- res = random_rectangles_params_generator(
- batch_size=2, height=height, width=width, scale=scale, ratio=ratio, value=value, same_on_batch=True
- )
+ res = RectangleEraseGenerator(
+ scale=scale.to(device=device, dtype=dtype),
+ ratio=ratio.to(device=device, dtype=dtype),
+ value=value,
+ )(torch.Size([2, 1, height, width]), True)
expected = dict(
widths=torch.tensor([100, 100], device=device, dtype=dtype),
heights=torch.tensor([0, 0], device=device, dtype=dtype),
@@ -758,13 +687,11 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
@pytest.mark.parametrize('direction', [torch.tensor([-1, -1]), torch.tensor([1, 1])])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, kernel_size, angle, direction, same_on_batch, device, dtype):
- random_motion_blur_generator(
- batch_size=batch_size,
+ MotionBlurGenerator(
kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch,
- )
+ )(torch.Size([batch_size]), same_on_batch)
@pytest.mark.parametrize(
'kernel_size,angle,direction',
@@ -778,24 +705,21 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
)
def test_invalid_param_combinations(self, kernel_size, angle, direction, device, dtype):
with pytest.raises(Exception):
- random_motion_blur_generator(
- batch_size=8,
+ MotionBlurGenerator(
kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- )
+ )(torch.Size([8]))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
angle = torch.tensor([30, 90])
direction = torch.tensor([-1, 1])
- res = random_motion_blur_generator(
- batch_size=2,
+ res = MotionBlurGenerator(
kernel_size=3,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=False,
- )
+ )(torch.Size([2]))
expected = dict(
ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
angle_factor=torch.tensor([82.9362, 84.9002], device=device, dtype=dtype),
@@ -810,13 +734,11 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
torch.manual_seed(42)
angle = torch.tensor([30, 90])
direction = torch.tensor([-1, 1])
- res = random_motion_blur_generator(
- batch_size=2,
+ res = MotionBlurGenerator(
kernel_size=3,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=True,
- )
+ )(torch.Size([2]), True)
expected = dict(
ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
angle_factor=torch.tensor([82.9362, 82.9362], device=device, dtype=dtype),
@@ -828,105 +750,25 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
assert_close(res['direction_factor'], expected['direction_factor'], rtol=1e-4, atol=1e-4)
-class TestRandomSolarizeGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('thresholds', [torch.tensor([0, 1]), torch.tensor([0.4, 0.6])])
- @pytest.mark.parametrize('additions', [torch.tensor([-0.5, 0.5])])
- @pytest.mark.parametrize('same_on_batch', [True, False])
- def test_valid_param_combinations(self, batch_size, thresholds, additions, same_on_batch, device, dtype):
- random_solarize_generator(
- batch_size=batch_size,
- thresholds=thresholds.to(device=device, dtype=dtype),
- additions=additions.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch,
- )
-
- @pytest.mark.parametrize(
- 'thresholds,additions',
- [
- (torch.tensor([0, 2]), torch.tensor([-0.5, 0.5])),
- (torch.tensor([-1, 1]), torch.tensor([-0.5, 0.5])),
- ([0, 1], torch.tensor([-0.5, 0.5])),
- (torch.tensor([0, 1]), torch.tensor([-0.5, 1])),
- (torch.tensor([0, 1]), torch.tensor([-1, 0.5])),
- (torch.tensor([0, 1]), [-0.5, 0.5]),
- ],
- )
- def test_invalid_param_combinations(self, thresholds, additions, device, dtype):
- with pytest.raises(Exception):
- random_solarize_generator(
- batch_size=batch_size, # noqa: F821 raises NameError
- thresholds=thresholds.to(device=device, dtype=dtype),
- additions=additions.to(device=device, dtype=dtype),
- )
-
- def test_random_gen(self, device, dtype):
- torch.manual_seed(42)
- batch_size = 8
- res = random_solarize_generator(
- batch_size=batch_size,
- thresholds=torch.tensor([0, 1], device=device, dtype=dtype),
- additions=torch.tensor([-0.5, 0.5], device=device, dtype=dtype),
- same_on_batch=False,
- )
- expected = dict(
- thresholds_factor=torch.tensor(
- [0.8823, 0.9150, 0.3829, 0.9593, 0.3904, 0.6009, 0.2566, 0.7936], device=device, dtype=dtype
- ),
- additions_factor=torch.tensor(
- [0.4408, -0.3668, 0.4346, 0.0936, 0.3694, 0.0677, 0.2411, -0.0706], device=device, dtype=dtype
- ),
- )
- assert res.keys() == expected.keys()
- assert_close(res['thresholds_factor'], expected['thresholds_factor'], rtol=1e-4, atol=1e-4)
- assert_close(res['additions_factor'], expected['additions_factor'], rtol=1e-4, atol=1e-4)
-
- def test_same_on_batch(self, device, dtype):
- torch.manual_seed(42)
- batch_size = 8
- res = random_solarize_generator(
- batch_size=batch_size,
- thresholds=torch.tensor([0, 1], device=device, dtype=dtype),
- additions=torch.tensor([-0.5, 0.5], device=device, dtype=dtype),
- same_on_batch=True,
- )
- expected = dict(
- thresholds_factor=torch.tensor(
- [0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823], device=device, dtype=dtype
- ),
- additions_factor=torch.tensor(
- [0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150], device=device, dtype=dtype
- ),
- )
- assert res.keys() == expected.keys()
- assert_close(res['thresholds_factor'], expected['thresholds_factor'], rtol=1e-4, atol=1e-4)
- assert_close(res['additions_factor'], expected['additions_factor'], rtol=1e-4, atol=1e-4)
-
-
class TestRandomPosterizeGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('bits', [torch.tensor([0, 8])])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, bits, same_on_batch, device, dtype):
- random_posterize_generator(
- batch_size=batch_size, bits=bits.to(device=device, dtype=dtype), same_on_batch=same_on_batch
- )
+ PosterizeGenerator(bits)(torch.Size([batch_size]), same_on_batch)
- @pytest.mark.parametrize('bits', [(torch.tensor([-1, 1])), (torch.tensor([0, 9])), (torch.tensor([3])), ([0, 8])])
+ @pytest.mark.parametrize('bits', [(torch.tensor([-1, 1])), (torch.tensor([0, 9])), (torch.tensor([3])), ([0, 8],)])
def test_invalid_param_combinations(self, bits, device, dtype):
with pytest.raises(Exception):
- random_posterize_generator(
- batch_size=batch_size, # noqa: F821 raises NameError
- bits=bits.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch, # noqa: F821 raises NameError
- )
+ if isinstance(bits, torch.Tensor):
+ PosterizeGenerator(bits.to(device=device, dtype=dtype))(torch.Size([3]))
+ else:
+ PosterizeGenerator(bits)(torch.Size([3]))
def test_random_gen(self, device, dtype):
torch.manual_seed(9)
batch_size = 8
- res = random_posterize_generator(
- batch_size=batch_size, bits=torch.tensor([0, 8], device=device, dtype=dtype), same_on_batch=False
- )
+ res = PosterizeGenerator(bits=torch.tensor([0, 8], device=device, dtype=dtype))(torch.Size([batch_size]))
expected = dict(bits_factor=torch.tensor([5, 2, 3, 6, 7, 7, 2, 7], device=device, dtype=torch.int32))
assert res.keys() == expected.keys()
assert_close(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)
@@ -934,38 +776,37 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(9)
batch_size = 8
- res = random_posterize_generator(
- batch_size=batch_size, bits=torch.tensor([0, 8], device=device, dtype=dtype), same_on_batch=True
- )
+ res = PosterizeGenerator(
+ bits=torch.tensor([0, 8], device=device, dtype=dtype))(torch.Size([batch_size]), same_on_batch=True)
expected = dict(bits_factor=torch.tensor([5, 5, 5, 5, 5, 5, 5, 5], device=device, dtype=torch.int32))
assert res.keys() == expected.keys()
assert_close(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)
-class TestRandomSharpnessGen(RandomGeneratorBaseTests):
+class TestPlainUniformGenerator(RandomGeneratorBaseTests):
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('sharpness', [torch.tensor([0.0, 1.0])])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, sharpness, same_on_batch, device, dtype):
- random_sharpness_generator(
- batch_size=batch_size, sharpness=sharpness.to(device=device, dtype=dtype), same_on_batch=same_on_batch
- )
+ PlainUniformGenerator(
+ (sharpness.to(device=device, dtype=dtype), "sharpness", None, None),
+ (sharpness.to(device=device, dtype=dtype), "sharpness_xx", 0., (0., 1.)),
+ )(torch.Size([batch_size, 1]), same_on_batch)
@pytest.mark.parametrize('sharpness', [(torch.tensor([-1, 5])), (torch.tensor([3])), ([0, 1.0])])
def test_invalid_param_combinations(self, sharpness, device, dtype):
with pytest.raises(Exception):
- random_sharpness_generator(
- batch_size=batch_size, # noqa: F821 raises NameError
- sharpness=sharpness.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch, # noqa: F821 raises NameError
- )
+ PlainUniformGenerator(
+ (sharpness.to(device=device, dtype=dtype), "sharpness", None, None),
+ (sharpness.to(device=device, dtype=dtype), "sharpness", 0., (0., 1.)),
+ )(torch.Size([8, 1]))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 8
- res = random_sharpness_generator(
- batch_size=batch_size, sharpness=torch.tensor([0.0, 1.0], device=device, dtype=dtype), same_on_batch=False
- )
+ res = PlainUniformGenerator(
+ (torch.tensor([0.0, 1.0], device=device, dtype=dtype), "sharpness_factor", None, None),
+ )(torch.Size([batch_size, 1]))
expected = dict(
sharpness_factor=torch.tensor(
[0.8823, 0.9150, 0.3829, 0.9593, 0.3904, 0.6009, 0.2566, 0.7936], device=device, dtype=dtype
@@ -977,9 +818,9 @@ class TestRandomSharpnessGen(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
batch_size = 8
- res = random_sharpness_generator(
- batch_size=batch_size, sharpness=torch.tensor([0.0, 1.0], device=device, dtype=dtype), same_on_batch=True
- )
+ res = PlainUniformGenerator(
+ (torch.tensor([0.0, 1.0], device=device, dtype=dtype), "sharpness_factor", None, None),
+ )(torch.Size([batch_size, 1]), True)
expected = dict(
sharpness_factor=torch.tensor(
[0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823], device=device, dtype=dtype