🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Remove deprecated code in `kornia.augmentation` (#2028)
João Gustavo A. Amorim30bb10d7f1e8
diff --git a/docs/generate_example_images.py b/docs/generate_example_images.pyindex 3bc8a62ae..bcee28883 100644--- a/docs/generate_example_images.py+++ b/docs/generate_example_images.py@@ -109,10 +109,7 @@ def main():print(f"Generated image example for {aug_name}. {sig}")mod = importlib.import_module("kornia.augmentation")- mix_augmentations_list: dict = {- "RandomMixUp": (((0.3, 0.4),), 2, 20),- "RandomCutMix": ((img1.shape[-2], img1.shape[-1]), 2, 2019),- }+ mix_augmentations_list: dict = {"RandomMixUpV2": ((), 2, 20), "RandomCutMixV2": ((), 2, 2019)}# ITERATE OVER THE TRANSFORMSfor aug_name, (args, num_samples, seed) in mix_augmentations_list.items():img_in = torch.cat([img1, img2])@@ -122,10 +119,11 @@ def main():# set seedtorch.manual_seed(seed)# apply the augmentation to the image and concat- out, _ = aug(img_in, torch.tensor([0, 1]))- out = torch.cat([img_in[0], img_in[1], *(out[i] for i in range(out.size(0)))], dim=-1)+ img_aug, _ = aug(img_in, torch.tensor([0, 1]))++ output = torch.cat([img_in[0], img_in[1], img_aug], dim=-1)# save the output image- out_np = K.utils.tensor_to_image((out * 255.0).byte())+ out_np = K.utils.tensor_to_image((output * 255.0).byte())cv2.imwrite(str(OUTPUT_PATH / f"{aug_name}.png"), out_np)sig = f"{aug_name}({', '.join([str(a) for a in args])}, p=1.0)"print(f"Generated image example for {aug_name}. {sig}")diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex e46f4abbd..27633d1ee 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -30,7 +30,7 @@ Intensity.. autoclass:: RandomMotionBlur.. autoclass:: RandomPosterize.. autoclass:: RandomRGBShift-.. autoclass:: RnadomSaturation+.. autoclass:: RandomSaturation.. autoclass:: RandomSharpness.. autoclass:: RandomSolarizediff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.pyindex 853db9f07..41682eb10 100644--- a/kornia/augmentation/_2d/geometric/elastic_transform.py+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py@@ -1,4 +1,3 @@-import warningsfrom typing import Any, Dict, Optional, Tuple, Unionimport torch@@ -54,7 +53,6 @@ class RandomElasticTransform(GeometricAugmentationBase2D):alpha: Tuple[float, float] = (1.0, 1.0),align_corners: bool = False,resample: Union[str, int, Resample] = Resample.BILINEAR.name,- mode: Optional[str] = None,padding_mode: str = "zeros",same_on_batch: bool = False,p: float = 0.5,@@ -64,14 +62,6 @@ class RandomElasticTransform(GeometricAugmentationBase2D):super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)- if mode is not None:- resample = mode- if not torch.jit.is_scripting():- warnings.warn(- "`mode` argument has been deprecated. Please use the `resample` argument instead",- DeprecationWarning,- stacklevel=2,- )self.flags = dict(kernel_size=kernel_size,diff --git a/kornia/augmentation/_2d/mix/__init__.py b/kornia/augmentation/_2d/mix/__init__.pyindex c28e46dcc..5e6b2e75a 100644--- a/kornia/augmentation/_2d/mix/__init__.py+++ b/kornia/augmentation/_2d/mix/__init__.py@@ -1,4 +1,4 @@-from kornia.augmentation._2d.mix.cutmix import RandomCutMix, RandomCutMixV2+from kornia.augmentation._2d.mix.cutmix import RandomCutMixV2from kornia.augmentation._2d.mix.jigsaw import RandomJigsaw-from kornia.augmentation._2d.mix.mixup import RandomMixUp, RandomMixUpV2+from kornia.augmentation._2d.mix.mixup import RandomMixUpV2from kornia.augmentation._2d.mix.mosaic import RandomMosaicdiff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.pyindex a921c55d5..f3733f212 100644--- a/kornia/augmentation/_2d/mix/base.py+++ b/kornia/augmentation/_2d/mix/base.py@@ -1,9 +1,8 @@-import warnings-from typing import Any, Dict, List, Optional, Tuple, Union+from typing import Any, Dict, List, Optional, Unionimport torch-from kornia.augmentation.base import TensorWithTransformMat, _BasicAugmentationBase+from kornia.augmentation.base import _BasicAugmentationBasefrom kornia.augmentation.utils import _transform_input, _transform_output_shape, _validate_input_dtypefrom kornia.constants import DataKey, DTypefrom kornia.core import Tensor@@ -11,107 +10,6 @@ from kornia.geometry.boxes import Boxesfrom kornia.testing import KORNIA_UNWRAP-class MixAugmentationBase(_BasicAugmentationBase):- r"""MixAugmentationBase base class for customized mix augmentation implementations.-- For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required.- "apply_transform" will need to handle the probabilities internally.-- Args:- p: probability for applying an augmentation. This param controls if to apply the augmentation for the batch.- p_batch: probability for applying an augmentation to a batch. This param controls the augmentation- probabilities batch-wise.- same_on_batch: apply the same transformation across the batch.- keepdim: whether to keep the output shape the same as input ``True`` or broadcast it- to the batch form ``False``.- """-- def __init__(self, p: float, p_batch: float, same_on_batch: bool = False, keepdim: bool = False) -> None:- super().__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)- warnings.warn("`MixAugmentationBase` is deprecated. Please use `MixAugmentationBaseV2` instead.")-- def __check_batching__(self, input: TensorWithTransformMat):- if isinstance(input, tuple):- inp, mat = input- if len(inp.shape) == 4:- if len(mat.shape) != 3:- raise AssertionError('Input tensor is in batch mode ' 'but transformation matrix is not')- if mat.shape[0] != inp.shape[0]:- raise AssertionError(- f"In batch dimension, input has {inp.shape[0]} but transformation matrix has {mat.shape[0]}"- )- elif len(inp.shape) in (2, 3):- if len(mat.shape) != 2:- raise AssertionError("Input tensor is in non-batch mode but transformation matrix is not")- else:- raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')-- def __unpack_input__( # type: ignore- self, input: TensorWithTransformMat- ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:- if isinstance(input, tuple):- in_tensor = input[0]- in_transformation = input[1]- return in_tensor, in_transformation- in_tensor = input- return in_tensor, None-- def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:- """Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])- return _transform_input(input)-- def apply_transform( # type: ignore- self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]- ) -> Tuple[torch.Tensor, torch.Tensor]:- raise NotImplementedError-- def apply_func( # type: ignore- self, in_tensor: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]- ) -> Tuple[torch.Tensor, torch.Tensor]:- to_apply = params['batch_prob']-- # if no augmentation needed- if torch.sum(to_apply) == 0:- output = in_tensor- # if all data needs to be augmented- elif torch.sum(to_apply) == len(to_apply):- output, label = self.apply_transform(in_tensor, label, params)- else:- raise ValueError(- "Mix augmentations must be performed batch-wisely. Element-wise augmentation is not supported."- )-- return output, label-- def forward( # type: ignore- self,- input: TensorWithTransformMat,- label: Optional[torch.Tensor] = None,- params: Optional[Dict[str, torch.Tensor]] = None,- ) -> Tuple[TensorWithTransformMat, torch.Tensor]:- in_tensor, in_trans = self.__unpack_input__(input)- ori_shape = in_tensor.shape- in_tensor = self.transform_tensor(in_tensor)- # If label is not provided, it would output the indices instead.- if label is None:- if isinstance(input, (tuple, list)):- device = input[0].device- else:- device = input.device- label = torch.arange(0, in_tensor.size(0), device=device, dtype=torch.long)- if params is None:- batch_shape = in_tensor.shape- params = self.forward_parameters(batch_shape)- self._params = params-- output, lab = self.apply_func(in_tensor, label, self._params)- output = _transform_output_shape(output, ori_shape) if self.keepdim else output- if in_trans is not None:- return (output, in_trans), lab- return output, lab--class MixAugmentationBaseV2(_BasicAugmentationBase):r"""MixAugmentationBase base class for customized mix augmentation implementations.diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.pyindex bbc6b3c78..9fe147f0a 100644--- a/kornia/augmentation/_2d/mix/cutmix.py+++ b/kornia/augmentation/_2d/mix/cutmix.py@@ -1,139 +1,12 @@-import warningsfrom typing import Any, Dict, List, Optional, Tuple, Unionfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.mix.base import MixAugmentationBase, MixAugmentationBaseV2-from kornia.augmentation.utils import _shape_validation+from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2from kornia.constants import DataKey, DTypefrom kornia.core import Tensor, stack, zerosfrom kornia.geometry.bbox import bbox_to_mask, infer_bbox_shape-class RandomCutMix(MixAugmentationBase):- r"""Apply CutMix augmentation to a batch of tensor images.-- .. image:: _static/img/RandomCutMix.png-- Implementation for `CutMix: Regularization Strategy to Train Strong Classifiers with- Localizable Features` :cite:`yun2019cutmix`.-- The function returns (inputs, labels), in which the inputs is the tensor that contains the mixup images- while the labels is a :math:`(\text{num_mixes}, B, 3)` tensor that contains (label_permuted_batch, lambda)- for each cutmix.-- The implementation referred to the following repository: `https://github.com/clovaai/CutMix-PyTorch- <https://github.com/clovaai/CutMix-PyTorch>`_.-- The onehot label may be computed as:-- .. code-block:: python-- def onehot(size, target):- vec = torch.zeros(size, dtype=torch.float32)- vec[target] = 1.- return vec-- .. code-block:: python-- def cutmix_label(labels, out_labels, size):- lb_onehot = onehot(size, labels)- for out_label in out_labels:- label_permuted_batch, lam = out_label[:, 0], out_label[:, 1]- label_permuted_onehot = onehot(size, label_permuted_batch)- lb_onehot = lb_onehot * lam + label_permuted_onehot * (1. - lam)- return lb_onehot-- Args:- height: the width of the input image.- width: the width of the input image.- p: probability for applying an augmentation to a batch. This param controls the augmentation- probabilities batch-wisely.- num_mix: cut mix times. Default is 1.- beta: hyperparameter for generating cut size from beta distribution.- Beta cannot be set to 0 after torch 1.8.0. If None, it will be set to 1.- cut_size: controlling the minimum and maximum cut ratio from [0, 1].- If None, it will be set to [0, 1], which means no restriction.- same_on_batch: apply the same transformation across the batch.- This flag will not maintain permutation order. Default: False.- keepdim: whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False-- Inputs:- - Input image tensors, shape of :math:`(B, C, H, W)`.- - Raw labels, shape of :math:`(B)`.-- Returns:- Tuple[Tensor, Tensor]:- - Adjusted image, shape of :math:`(B, C, H, W)`.- - Raw labels, permuted labels and lambdas for each mix, shape of :math:`(B, num_mix, 3)`.-- Note:- This implementation would randomly cutmix images in a batch. Ideally, the larger batch size would be preferred.-- Examples:- >>> rng = torch.manual_seed(3)- >>> input = torch.rand(2, 1, 3, 3)- >>> input[0] = torch.ones((1, 3, 3))- >>> label = torch.tensor([0, 1])- >>> cutmix = RandomCutMix()- >>> cutmix(input, label)- (tensor([[[[0.8879, 0.4510, 1.0000],- [0.1498, 0.4015, 1.0000],- [1.0000, 1.0000, 1.0000]]],- <BLANKLINE>- <BLANKLINE>- [[[1.0000, 1.0000, 0.7995],- [1.0000, 1.0000, 0.0542],- [0.4594, 0.1756, 0.9492]]]]), tensor([[[0.0000, 1.0000, 0.4444],- [1.0000, 0.0000, 0.4444]]]))- """-- def __init__(- self,- height: Optional[int] = None,- width: Optional[int] = None,- num_mix: int = 1,- cut_size: Optional[Union[Tensor, Tuple[float, float]]] = None,- beta: Optional[Union[Tensor, float]] = None,- same_on_batch: bool = False,- p: float = 1.0,- keepdim: bool = False,- ) -> None:- super().__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)- 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,- )- self._param_generator: rg.CutmixGenerator = rg.CutmixGenerator(cut_size, beta, num_mix, p=p)- warnings.warn("`RandomCutMix` is deprecated. Please use `RandomCutMixV2` instead.")-- def apply_transform( # type: ignore- self, input: Tensor, label: Tensor, params: Dict[str, Tensor]- ) -> Tuple[Tensor, Tensor]:- height, width = input.size(2), input.size(3)- 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")-- out_inputs = input.clone()- out_labels = []- 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)- lam = w.to(input.dtype) * h.to(input.dtype) / (width * height) # width_beta * height_beta- # compute mask to match input shape- mask = bbox_to_mask(crop, width, height).bool().unsqueeze(dim=1).repeat(1, input.size(1), 1, 1)- out_inputs[mask] = input_permute[mask]- out_labels.append(stack([label.to(input.dtype), labels_permute.to(input.dtype), lam.to(label.device)], 1))-- return out_inputs, stack(out_labels, 0)--class RandomCutMixV2(MixAugmentationBaseV2):r"""Apply CutMix augmentation to a batch of tensor images.diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.pyindex c85030c10..e1bd21fdd 100644--- a/kornia/augmentation/_2d/mix/mixup.py+++ b/kornia/augmentation/_2d/mix/mixup.py@@ -1,111 +1,11 @@-import warningsfrom typing import Any, Dict, List, Optional, Tuple, Unionfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.mix.base import MixAugmentationBase, MixAugmentationBaseV2+from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2from kornia.constants import DataKey, DTypefrom kornia.core import Tensor, stack, zeros-class RandomMixUp(MixAugmentationBase):- r"""Apply MixUp augmentation to a batch of tensor images.-- .. image:: _static/img/RandomMixUp.png-- Implementation for `mixup: BEYOND EMPIRICAL RISK MINIMIZATION` :cite:`zhang2018mixup`.-- The function returns (inputs, labels), in which the inputs is the tensor that contains the mixup images- while the labels is a :math:`(B, 3)` tensor that contains (label_batch, label_permuted_batch, lambda) for- each image.-- The implementation is on top of the following repository:- `https://github.com/hongyi-zhang/mixup/blob/master/cifar/utils.py- <https://github.com/hongyi-zhang/mixup/blob/master/cifar/utils.py>`_.-- The loss and accuracy are computed as:-- .. code-block:: python-- def loss_mixup(y, logits):- criterion = F.cross_entropy- loss_a = criterion(logits, y[:, 0].long(), reduction='none')- loss_b = criterion(logits, y[:, 1].long(), reduction='none')- return ((1 - y[:, 2]) * loss_a + y[:, 2] * loss_b).mean()-- .. code-block:: python-- def acc_mixup(y, logits):- pred = torch.argmax(logits, dim=1).to(y.device)- return (1 - y[:, 2]) * pred.eq(y[:, 0]).float() + y[:, 2] * pred.eq(y[:, 1]).float()-- Args:- p: probability for applying an augmentation to a batch. This param controls the augmentation- probabilities batch-wisely.- lambda_val: min-max value of mixup strength. Default is 0-1.- same_on_batch: apply the same transformation across the batch.- This flag will not maintain permutation order. Default: False.- keepdim: whether to keep the output shape the same as input (True) or broadcast it- to the batch form (False). Default: False-- Inputs:- - Input image tensors, shape of :math:`(B, C, H, W)`.- - Label: raw labels, shape of :math:`(B)`.-- Returns:- Tuple[Tensor, Tensor]:- - Adjusted image, shape of :math:`(B, C, H, W)`.- - Raw labels, permuted labels and lambdas for each mix, shape of :math:`(B, 3)`.-- Note:- This implementation would randomly mixup images in a batch. Ideally, the larger batch size would be preferred.-- Examples:- >>> rng = torch.manual_seed(1)- >>> input = torch.rand(2, 1, 3, 3)- >>> label = torch.tensor([0, 1])- >>> mixup = RandomMixUp()- >>> mixup(input, label)- (tensor([[[[0.7576, 0.2793, 0.4031],- [0.7347, 0.0293, 0.7999],- [0.3971, 0.7544, 0.5695]]],- <BLANKLINE>- <BLANKLINE>- [[[0.4388, 0.6387, 0.5247],- [0.6826, 0.3051, 0.4635],- [0.4550, 0.5725, 0.4980]]]]), tensor([[0.0000, 0.0000, 0.1980],- [1.0000, 1.0000, 0.4162]]))- """-- def __init__(- self,- lambda_val: Optional[Union[Tensor, Tuple[float, float]]] = None,- same_on_batch: bool = False,- p: float = 1.0,- keepdim: bool = False,- ) -> None:- super().__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)- self._param_generator = rg.MixupGenerator(lambda_val, p=p)- warnings.warn("`RandomMixUp` is deprecated. Please use `RandomMixUpV2` instead.")-- def apply_transform( # type: ignore- self, input: Tensor, label: Tensor, params: Dict[str, Tensor]- ) -> Tuple[Tensor, 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))-- lam = params["mixup_lambdas"].view(-1, 1, 1, 1).expand_as(input).to(label.device)- inputs = input * (1 - lam) + input_permute * lam- out_labels = stack(- [- label.to(input.dtype),- labels_permute.to(input.dtype),- params["mixup_lambdas"].to(label.device, input.dtype),- ],- -1,- ).to(label.device)- return inputs, out_labels--class RandomMixUpV2(MixAugmentationBaseV2):r"""Apply MixUp augmentation to a batch of tensor images.diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 7a173dd42..1a3733f98 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -12,7 +12,6 @@ from kornia.augmentation._2d import (RandomChannelShuffle,RandomContrast,RandomCrop,- RandomCutMix,RandomCutMixV2,RandomElasticTransform,RandomEqualize,@@ -26,7 +25,6 @@ from kornia.augmentation._2d import (RandomHue,RandomInvert,RandomJigsaw,- RandomMixUp,RandomMixUpV2,RandomMosaic,RandomMotionBlur,@@ -50,7 +48,7 @@ from kornia.augmentation._2d import (from kornia.augmentation._2d.base import AugmentationBase2Dfrom kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2Dfrom kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D-from kornia.augmentation._2d.mix.base import MixAugmentationBase+from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2from kornia.augmentation._3d import (CenterCrop3D,RandomAffine3D,@@ -77,7 +75,7 @@ __all__ = ["AugmentationBase2D","GeometricAugmentationBase2D","IntensityAugmentationBase2D",- "MixAugmentationBase",+ "MixAugmentationBaseV2","CenterCrop","ColorJiggle","ColorJitter",diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex e2f218a00..27c36af05 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -143,7 +143,6 @@ class AugmentationSequential(ImageSequential):*args: Union[_AugmentationBase, ImageSequential],data_keys: List[Union[str, int, DataKey]] = [DataKey.INPUT],same_on_batch: Optional[bool] = None,- return_transform: Optional[bool] = None,keepdim: Optional[bool] = None,random_apply: Union[int, bool, Tuple[int, int]] = False,random_apply_weights: Optional[List[float]] = None,@@ -152,7 +151,6 @@ class AugmentationSequential(ImageSequential):super().__init__(*args,same_on_batch=same_on_batch,- return_transform=return_transform,keepdim=keepdim,random_apply=random_apply,random_apply_weights=random_apply_weights,diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.pyindex ef3ca41aa..ab79062ca 100644--- a/kornia/augmentation/container/base.py+++ b/kornia/augmentation/container/base.py@@ -4,8 +4,7 @@ from typing import Any, Iterator, List, NamedTuple, Optional, Tuple, Unionimport torchimport torch.nn as nn-from kornia.augmentation import MixAugmentationBase-from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2+from kornia.augmentation import MixAugmentationBaseV2from kornia.augmentation.base import _AugmentationBase__all__ = ["SequentialBase", "ParamItem"]@@ -29,13 +28,7 @@ class SequentialBase(nn.Sequential):to the batch form (False). If None, it will not overwrite the function-wise settings."""- def __init__(- self,- *args: nn.Module,- same_on_batch: Optional[bool] = None,- return_transform: Optional[bool] = None,- keepdim: Optional[bool] = None,- ) -> None:+ def __init__(self, *args: nn.Module, same_on_batch: Optional[bool] = None, keepdim: Optional[bool] = None) -> None:# To name the modules properly_args = OrderedDict()for idx, mod in enumerate(args):@@ -44,10 +37,9 @@ class SequentialBase(nn.Sequential):_args.update({f"{mod.__class__.__name__}_{idx}": mod})super().__init__(_args)self._same_on_batch = same_on_batch- self._return_transform = return_transformself._keepdim = keepdimself._params: Optional[List[ParamItem]] = None- self.update_attribute(same_on_batch, return_transform, keepdim)+ self.update_attribute(same_on_batch, keepdim)def update_attribute(self,@@ -57,7 +49,7 @@ class SequentialBase(nn.Sequential):) -> None:for mod in self.children():# MixAugmentation does not have return transform- if isinstance(mod, (_AugmentationBase, MixAugmentationBase, MixAugmentationBaseV2)):+ if isinstance(mod, (_AugmentationBase, MixAugmentationBaseV2)):if same_on_batch is not None:mod.same_on_batch = same_on_batchif keepdim is not None:@@ -115,15 +107,6 @@ class SequentialBase(nn.Sequential):self._same_on_batch = same_on_batchself.update_attribute(same_on_batch=same_on_batch)- @property- def return_transform(self) -> Optional[bool]:- return self._return_transform-- @return_transform.setter- def return_transform(self, return_transform: Optional[bool]) -> None:- self._return_transform = return_transform- self.update_attribute(return_transform=return_transform)-@propertydef keepdim(self) -> Optional[bool]:return self._keepdimdiff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 39dc78142..a718286a7 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -7,10 +7,9 @@ import korniafrom kornia.augmentation import (GeometricAugmentationBase2D,IntensityAugmentationBase2D,- MixAugmentationBase,+ MixAugmentationBaseV2,RandomCrop,)-from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2from kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.container.base import ParamItem, SequentialBasefrom kornia.augmentation.container.utils import ApplyInverseInterface, InputApplyInverse@@ -53,14 +52,13 @@ class ImageSequential(SequentialBase):... kornia.filters.MedianBlur((3, 3)),... kornia.augmentation.RandomAffine(360, p=1.0),... kornia.enhance.Invert(),- ... kornia.augmentation.RandomMixUp(p=1.0),+ ... kornia.augmentation.RandomMixUpV2(p=1.0),... same_on_batch=True,... random_apply=10,... )>>> out, lab = aug_list(input, label=label)>>> lab- tensor([[0.0000, 1.0000, 0.1214],- [1.0000, 0.0000, 0.1214]])+ tensor([0, 1])>>> out.shapetorch.Size([2, 3, 5, 6])@@ -90,18 +88,12 @@ class ImageSequential(SequentialBase):self,*args: Module,same_on_batch: Optional[bool] = None,- return_transform: Optional[bool] = None,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",) -> None:- if return_transform is not None:- raise ValueError(- "`return_transform` is deprecated. Please access"- " `.transform_matrix` in `AugmentationSequential` instead."- )- super().__init__(*args, same_on_batch=same_on_batch, return_transform=return_transform, keepdim=keepdim)+ super().__init__(*args, same_on_batch=same_on_batch, keepdim=keepdim)self.random_apply: Union[Tuple[int, int], bool] = self._read_random_apply(random_apply, len(args))if random_apply_weights is not None and len(random_apply_weights) != len(self):@@ -178,11 +170,8 @@ class ImageSequential(SequentialBase):Special operations needed for label-involved augmentations."""- indices = []- for idx, (_, child) in enumerate(named_modules):- if isinstance(child, (MixAugmentationBase,)): # NOTE: MixV2 will not be a special op in the future.- indices.append(idx)- return indices+ # NOTE: MixV2 will not be a special op in the future.+ return [idx for idx, (_, child) in enumerate(named_modules) if isinstance(child, MixAugmentationBaseV2)]def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:if params is None:@@ -223,7 +212,7 @@ class ImageSequential(SequentialBase):if isinstance(module, RandomCrop):mod_param = module.forward_parameters_precrop(batch_shape)param = ParamItem(name, mod_param)- elif isinstance(module, (_AugmentationBase, MixAugmentationBase, MixAugmentationBaseV2, ImageSequential)):+ elif isinstance(module, (_AugmentationBase, MixAugmentationBaseV2, ImageSequential)):mod_param = module.forward_parameters(batch_shape)param = ParamItem(name, mod_param)else:@@ -271,9 +260,7 @@ class ImageSequential(SequentialBase):# Define as 1 for broadcastingres_mat: Optional[Tensor] = Nonefor (_, module), param in zip(named_modules, params if params is not None else []):- if isinstance(module, (_AugmentationBase,)) and not isinstance(- module, (MixAugmentationBase, MixAugmentationBaseV2)- ):+ if isinstance(module, (_AugmentationBase,)) and not isinstance(module, MixAugmentationBaseV2):pdata = cast(Dict[str, Tensor], param.data)to_apply = pdata['batch_prob']ori_shape = input.shape@@ -382,7 +369,7 @@ class ImageSequential(SequentialBase):for param in params:module = self.get_submodule(param.name)input, label = self.apply_to_input(input, label, module, param=param, extra_args=extra_args)- if isinstance(module, (_AugmentationBase, MixAugmentationBase, MixAugmentationBaseV2, SequentialBase)):+ if isinstance(module, (_AugmentationBase, MixAugmentationBaseV2, SequentialBase)):param = ParamItem(param.name, module._params)else:param = ParamItem(param.name, None)diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.pyindex 74e54f86a..767afc8b8 100644--- a/kornia/augmentation/container/patch.py+++ b/kornia/augmentation/container/patch.py@@ -4,8 +4,7 @@ from typing import Iterator, List, NamedTuple, Optional, Tuple, Unionimport torchimport torch.nn as nn-from kornia.augmentation import MixAugmentationBase-from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2+from kornia.augmentation import MixAugmentationBaseV2from kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.container.base import SequentialBasefrom kornia.augmentation.container.image import ImageSequential, ParamItem@@ -277,26 +276,20 @@ class PatchSequential(ImageSequential):seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix)with_mix = mix_addedfor s in seq:- if isinstance(- s[1], (_AugmentationBase, MixAugmentationBase, SequentialBase, MixAugmentationBaseV2)- ):+ if isinstance(s[1], (_AugmentationBase, SequentialBase, MixAugmentationBaseV2)):yield ParamItem(s[0], s[1].forward_parameters(torch.Size(batch_shape[1:]))), ielse:yield ParamItem(s[0], None), ielif not self.same_on_batch and not self.random_apply:for i, nchild in enumerate(self.named_children()):- if isinstance(- nchild[1], (_AugmentationBase, MixAugmentationBase, SequentialBase, MixAugmentationBaseV2)- ):+ if isinstance(nchild[1], (_AugmentationBase, SequentialBase, MixAugmentationBaseV2)):yield ParamItem(nchild[0], nchild[1].forward_parameters(torch.Size(batch_shape[1:]))), ielse:yield ParamItem(nchild[0], None), ielif not self.random_apply:# same_on_batch + not random_apply => location-wise augmentationfor i, nchild in enumerate(islice(cycle(self.named_children()), batch_shape[0])):- if isinstance(- nchild[1], (_AugmentationBase, MixAugmentationBase, SequentialBase, MixAugmentationBaseV2)- ):+ if isinstance(nchild[1], (_AugmentationBase, SequentialBase, MixAugmentationBaseV2)):yield ParamItem(nchild[0], nchild[1].forward_parameters(torch.Size(batch_shape[1:]))), ielse:yield ParamItem(nchild[0], None), i@@ -307,9 +300,7 @@ class PatchSequential(ImageSequential):seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix)with_mix = mix_addedfor s in seq:- if isinstance(- s[1], (_AugmentationBase, MixAugmentationBase, SequentialBase, MixAugmentationBaseV2)- ):+ if isinstance(s[1], (_AugmentationBase, SequentialBase, MixAugmentationBaseV2)):yield ParamItem(s[0], s[1].forward_parameters(torch.Size(batch_shape[1:]))), ielse:yield ParamItem(s[0], None), i@@ -330,7 +321,7 @@ class PatchSequential(ImageSequential):module = self.get_submodule(params.param.name)output, out_label = self.apply_to_input(_input, _label, module, params.param, extra_args={})- if isinstance(module, (_AugmentationBase, MixAugmentationBase, SequentialBase, MixAugmentationBaseV2)):+ if isinstance(module, (_AugmentationBase, SequentialBase, MixAugmentationBaseV2)):out_param = ParamItem(params.param.name, module._params)else:out_param = ParamItem(params.param.name, None)diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.pyindex 1f3e9be10..d5a9eb74d 100644--- a/kornia/augmentation/container/utils.py+++ b/kornia/augmentation/container/utils.py@@ -6,8 +6,7 @@ from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Type, Uimport torchimport kornia # lazy loading for circular dependencies-from kornia.augmentation import GeometricAugmentationBase2D, MixAugmentationBase, RandomCrop, RandomErasing-from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2+from kornia.augmentation import GeometricAugmentationBase2D, MixAugmentationBaseV2, RandomCrop, RandomErasingfrom kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.container.base import ParamItemfrom kornia.augmentation.utils import override_parameters@@ -171,9 +170,7 @@ class InputApplyInverse(ApplyInverseImpl):to apply transformations.param: the corresponding parameters to the module."""- if isinstance(module, (MixAugmentationBase,)):- input, label = module(input, label=label, params=param.data)- elif isinstance(module, (_AugmentationBase, MixAugmentationBaseV2)):+ if isinstance(module, (_AugmentationBase, MixAugmentationBaseV2)):input = module(input, params=param.data, **extra_args)elif isinstance(module, kornia.augmentation.ImageSequential):temp = module.apply_inverse_funcdiff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex 09ffed40b..ad1a1b920 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -3,8 +3,7 @@ from typing import Any, Dict, List, Optional, Tuple, Union, castimport torchimport kornia-from kornia.augmentation import RandomCrop-from kornia.augmentation._2d.mix.base import MixAugmentationBase, MixAugmentationBaseV2+from kornia.augmentation import MixAugmentationBaseV2, RandomCropfrom kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.container.base import SequentialBasefrom kornia.augmentation.container.image import ImageSequential, ParamItem, _get_new_batch_shape@@ -62,12 +61,12 @@ class VideoSequential(ImageSequential):>>> aug_list = VideoSequential(... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),... kornia.augmentation.RandomAffine(360, p=1.0),- ... kornia.augmentation.RandomMixUp(p=1.0),+ ... kornia.augmentation.RandomMixUpV2(p=1.0),... data_format="BCTHW",... same_on_frame=False)>>> output, lab = aug_list(input)>>> output.shape, lab.shape- (torch.Size([2, 3, 4, 5, 6]), torch.Size([2, 4, 3]))+ (torch.Size([3, 4, 5, 6]), torch.Size([3, 4, 5, 6]))>>> (output[0, :, 0] == output[0, :, 1]).all()tensor(False)@@ -83,7 +82,7 @@ class VideoSequential(ImageSequential):>>> aug_list = VideoSequential(... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),... kornia.augmentation.RandomAffine(360, p=1.0),- ... kornia.augmentation.RandomMixUp(p=1.0),+ ... kornia.augmentation.RandomMixUpV2(p=1.0),... data_format="BCTHW",... same_on_frame=False,... random_apply=1,@@ -195,7 +194,7 @@ class VideoSequential(ImageSequential):if self.same_on_frame:raise ValueError("Sequential is currently unsupported for ``same_on_frame``.")param = ParamItem(name, seq_param)- elif isinstance(module, (_AugmentationBase, MixAugmentationBase, MixAugmentationBaseV2)):+ elif isinstance(module, (_AugmentationBase, MixAugmentationBaseV2)):mod_param = module.forward_parameters(batch_shape)if self.same_on_frame:for k, v in mod_param.items():diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.pyindex 359016eaa..752703dd3 100644--- a/kornia/augmentation/random_generator/_2d/__init__.py+++ b/kornia/augmentation/random_generator/_2d/__init__.py@@ -3,7 +3,6 @@ from kornia.augmentation.random_generator._2d.color_jiggle import *from kornia.augmentation.random_generator._2d.color_jitter import *from kornia.augmentation.random_generator._2d.crop import *from kornia.augmentation.random_generator._2d.cutmix import *-from kornia.augmentation.random_generator._2d.func import *from kornia.augmentation.random_generator._2d.jigsaw import *from kornia.augmentation.random_generator._2d.mixup import *from kornia.augmentation.random_generator._2d.mosaic import *diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.pyindex 128d4cf25..92fdd6268 100644--- a/kornia/augmentation/random_generator/_2d/affine.py+++ b/kornia/augmentation/random_generator/_2d/affine.py@@ -4,15 +4,9 @@ import torchfrom torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBase-from kornia.augmentation.utils import (- _adapted_rsampling,- _adapted_uniform,- _common_param_check,- _joint_range_check,- _range_bound,-)-from kornia.core import Device, Tensor, as_tensor, concatenate, stack, tensor, zeros-from kornia.utils.helpers import _deprecated, _extract_device_dtype+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound+from kornia.core import Tensor, as_tensor, concatenate, stack, tensor, zeros+from kornia.utils.helpers import _extract_device_dtypeclass AffineGenerator(RandomGeneratorBase):@@ -184,106 +178,3 @@ class AffineGenerator(RandomGeneratorBase):sx = sy = tensor([0] * batch_size, device=_device, dtype=_dtype)return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)---@_deprecated(replace_with=AffineGenerator.__name__)-def random_affine_generator(- batch_size: int,- height: int,- width: int,- degrees: Tensor,- translate: Optional[Tensor] = None,- scale: Optional[Tensor] = None,- shear: Optional[Tensor] = None,- same_on_batch: bool = False,- device: Device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, Tensor]:- r"""Get parameters for ``affine`` for a random affine transform.-- Args:- batch_size (int): the tensor batch size.- height (int) : height of the image.- width (int): width of the image.- degrees (Tensor): Range of degrees to select from like (min, max).- translate (tensor, optional): tuple of maximum absolute fraction for horizontal- and vertical translations. For example translate=(a, b), then horizontal shift- is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is- randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.- scale (tensor, optional): scaling factor interval, e.g (a, b), then scale is- randomly sampled from the range a <= scale <= b. Will keep original scale by default.- shear (tensor, optional): Range of degrees to select from.- 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.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- device (Device): the device on which the random numbers will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.-- Returns:- params Dict[str, Tensor]: parameters to be passed for transformation.- - translations (Tensor): element-wise translations with a shape of (B, 2).- - center (Tensor): element-wise center with a shape of (B, 2).- - scale (Tensor): element-wise scales with a shape of (B, 2).- - angle (Tensor): element-wise rotation angles with a shape of (B,).- - sx (Tensor): element-wise x-axis shears with a shape of (B,).- - sy (Tensor): element-wise y-axis shears with a shape of (B,).-- Note:- The generated random numbers are not reproducible across different devices and dtypes.- """- _common_param_check(batch_size, same_on_batch)- _joint_range_check(degrees, "degrees")- 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}.")-- _device, _dtype = _extract_device_dtype([degrees, translate, scale, shear])- degrees = degrees.to(device=device, dtype=dtype)- angle = _adapted_uniform((batch_size,), degrees[0], degrees[1], same_on_batch)- angle = angle.to(device=_device, dtype=_dtype)-- # compute tensor ranges- if scale is not None:- scale = scale.to(device=device, dtype=dtype)- if not (len(scale.shape) == 1 and len(scale) in (2, 4)):- raise AssertionError(f"`scale` shall have 2 or 4 elements. Got {scale}.")- _joint_range_check(scale[:2], "scale")- _scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch).unsqueeze(1).repeat(1, 2)- if len(scale) == 4:- _joint_range_check(scale[2:], "scale_y")- _scale[:, 1] = _adapted_uniform((batch_size,), scale[2], scale[3], same_on_batch)- _scale = _scale.to(device=_device, dtype=_dtype)- else:- _scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)-- if translate is not None:- translate = translate.to(device=device, dtype=dtype)- if not (0.0 <= translate[0] <= 1.0 and 0.0 <= translate[1] <= 1.0 and translate.shape == torch.Size([2])):- raise AssertionError(f"Expect translate contains two elements and ranges are in [0, 1]. Got {translate}.")- max_dx: Tensor = translate[0] * width- max_dy: Tensor = translate[1] * height- translations = stack(- [- _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),- _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),- ],- dim=-1,- )- translations = translations.to(device=_device, dtype=_dtype)- else:- translations = zeros((batch_size, 2), device=_device, dtype=_dtype)-- center: Tensor = tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5- center = center.expand(batch_size, -1)-- if shear is not None:- shear = shear.to(device=device, dtype=dtype)- _joint_range_check(shear[0], "shear")- _joint_range_check(shear[1], "shear")- sx = _adapted_uniform((batch_size,), shear[0][0], shear[0][1], same_on_batch)- sy = _adapted_uniform((batch_size,), shear[1][0], shear[1][1], same_on_batch)- sx = sx.to(device=_device, dtype=_dtype)- sy = sy.to(device=_device, dtype=_dtype)- else:- sx = sy = tensor([0] * batch_size, device=_device, dtype=_dtype)-- return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.pyindex fb7ad855e..5ba0015a2 100644--- a/kornia/augmentation/random_generator/_2d/crop.py+++ b/kornia/augmentation/random_generator/_2d/crop.py@@ -4,10 +4,10 @@ import torchfrom torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBase-from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _joint_range_check+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_checkfrom kornia.core import Device, Tensor, tensor, where, zerosfrom kornia.geometry.bbox import bbox_generator-from kornia.utils.helpers import _deprecated, _extract_device_dtype+from kornia.utils.helpers import _extract_device_dtypeclass CropGenerator(RandomGeneratorBase):@@ -145,10 +145,22 @@ class ResizedCropGenerator(CropGenerator):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.]])}+ >>> rcg = ResizedCropGenerator((30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))+ >>> out = rcg(torch.Size([1, 3, 3]))+ >>> out["src"]+ tensor([[[0., 0.],+ [2., 0.],+ [2., 2.],+ [0., 2.]]])+ >>> out["dst"]+ tensor([[[ 0., 0.],+ [29., 0.],+ [29., 29.],+ [ 0., 29.]]])+ >>> out["input_size"]+ tensor([[3, 3]])+ >>> out["output_size"]+ tensor([[30, 30]])"""def __init__(@@ -236,225 +248,6 @@ class ResizedCropGenerator(CropGenerator):return super().forward(batch_shape, same_on_batch)-@_deprecated(replace_with=CropGenerator.__name__)-def random_crop_generator(- batch_size: int,- input_size: Tuple[int, int],- size: Union[Tuple[int, int], Tensor],- resize_to: Optional[Tuple[int, int]] = None,- same_on_batch: bool = False,- device: Device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, Tensor]:- r"""Get parameters for ```crop``` transformation for crop transform.-- Args:- batch_size (int): the tensor batch size.- input_size (tuple): Input image shape, like (h, w).- 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.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- device (Device): the device on which the random numbers will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.-- Returns:- params Dict[str, Tensor]: parameters to be passed for transformation.- - src (Tensor): cropping bounding boxes with a shape of (B, 4, 2).- - dst (Tensor): output bounding boxes with a shape (B, 4, 2).-- Note:- The generated random numbers are not reproducible across different devices and dtypes.-- Example:- >>> _ = torch.manual_seed(0)- >>> crop_size = torch.tensor([[25, 28], [27, 29], [26, 28]])- >>> random_crop_generator(3, (30, 30), size=crop_size, same_on_batch=False)- {'src': tensor([[[ 1., 0.],- [28., 0.],- [28., 24.],- [ 1., 24.]],- <BLANKLINE>- [[ 1., 1.],- [29., 1.],- [29., 27.],- [ 1., 27.]],- <BLANKLINE>- [[ 0., 3.],- [27., 3.],- [27., 28.],- [ 0., 28.]]]), 'dst': tensor([[[ 0., 0.],- [27., 0.],- [27., 24.],- [ 0., 24.]],- <BLANKLINE>- [[ 0., 0.],- [28., 0.],- [28., 26.],- [ 0., 26.]],- <BLANKLINE>- [[ 0., 0.],- [27., 0.],- [27., 25.],- [ 0., 25.]]]), 'input_size': tensor([[30, 30],- [30, 30],- [30, 30]])}- """- _common_param_check(batch_size, same_on_batch)- _device, _dtype = _extract_device_dtype([size if isinstance(size, Tensor) else None])- # Use float point instead- _dtype = _dtype if _dtype in [torch.float16, torch.float32, torch.float64] else dtype- if not isinstance(size, Tensor):- size = tensor(size, device=_device, dtype=_dtype).repeat(batch_size, 1)- else:- size = 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 batch_size == 0:- return dict(- src=zeros([0, 4, 2], device=_device, dtype=_dtype), dst=zeros([0, 4, 2], device=_device, dtype=_dtype)- )-- if same_on_batch:- # If same_on_batch, select the first then repeat.- x_start = _adapted_uniform((batch_size,), 0, x_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()- y_start = _adapted_uniform((batch_size,), 0, y_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()- else:- x_start = _adapted_uniform((1,), 0, x_diff.to(device=device, dtype=dtype), same_on_batch).floor()- y_start = _adapted_uniform((1,), 0, y_diff.to(device=device, dtype=dtype), same_on_batch).floor()- crop_src = bbox_generator(- x_start.view(-1).to(device=_device, dtype=_dtype),- y_start.view(-1).to(device=_device, dtype=_dtype),- where(size[:, 1] == 0, tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),- where(size[:, 0] == 0, tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),- )-- if resize_to is None:- crop_dst = bbox_generator(- tensor([0] * batch_size, device=_device, dtype=_dtype),- tensor([0] * batch_size, device=_device, dtype=_dtype),- size[:, 1],- size[:, 0],- )- else:- if not (- len(resize_to) == 2- and isinstance(resize_to[0], (int,))- and isinstance(resize_to[1], (int,))- and resize_to[0] > 0- and resize_to[1] > 0- ):- raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {resize_to}.")- crop_dst = tensor(- [[[0, 0], [resize_to[1] - 1, 0], [resize_to[1] - 1, resize_to[0] - 1], [0, resize_to[0] - 1]]],- device=_device,- dtype=_dtype,- ).repeat(batch_size, 1, 1)-- _input_size = tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)-- 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],- scale: Tensor,- ratio: Tensor,- same_on_batch: bool = False,- device: Device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, Tensor]:- r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.-- Args:- batch_size (int): the tensor batch size.- size (Tuple[int, int]): expected output size of each edge.- scale (Tensor): range of size of the origin size cropped with (2,) shape.- ratio (Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- device (Device): the device on which the random numbers will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.-- Returns:- params Dict[str, Tensor]: parameters to be passed for transformation.- - size (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.]])}- """- _common_param_check(batch_size, same_on_batch)- _joint_range_check(scale, "scale")- _joint_range_check(ratio, "ratio")- if not (len(size) == 2 and type(size[0]) is int and size[1] > 0 and type(size[1]) is int and size[1] > 0):- raise AssertionError(f"'height' and 'width' must be integers. Got {size}.")-- _device, _dtype = _extract_device_dtype([scale, ratio])-- if batch_size == 0:- return dict(size=zeros([0, 2], device=_device, dtype=_dtype))-- scale = scale.to(device=device, dtype=dtype)- ratio = ratio.to(device=device, dtype=dtype)- # 10 trails for each element- area = _adapted_uniform((batch_size, 10), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)- log_ratio = _adapted_uniform((batch_size, 10), torch.log(ratio[0]), torch.log(ratio[1]), same_on_batch)- 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])- if in_ratio < ratio.min():- h_ct = tensor(size[0], device=device, dtype=dtype)- w_ct = torch.round(h_ct / ratio.min())- elif in_ratio > ratio.min():- w_ct = tensor(size[1], device=device, dtype=dtype)- h_ct = torch.round(w_ct * ratio.min())- else: # whole image- h_ct = tensor(size[0], device=device, dtype=dtype)- w_ct = 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)-- return dict(size=torch.stack([h_out, w_out], dim=1).to(device=_device, dtype=_dtype))--def center_crop_generator(batch_size: int, height: int, width: int, size: Tuple[int, int], device: Device = torch.device('cpu')) -> Dict[str, Tensor]:diff --git a/kornia/augmentation/random_generator/_2d/func.py b/kornia/augmentation/random_generator/_2d/func.pydeleted file mode 100644index 0596903cd..000000000--- a/kornia/augmentation/random_generator/_2d/func.py+++ /dev/null@@ -1,138 +0,0 @@-from typing import Dict--import torch--from kornia.augmentation.utils import _adapted_uniform, _common_param_check, _joint_range_check-from kornia.utils.helpers import _deprecated, _extract_device_dtype---@_deprecated()-def random_rotation_generator(- batch_size: int,- degrees: torch.Tensor,- same_on_batch: bool = False,- device: torch.device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, torch.Tensor]:- r"""Get parameters for ``rotate`` for a random rotate transform.-- Args:- batch_size (int): the tensor batch size.- degrees (torch.Tensor): range of degrees with shape (2) to select from.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- device (torch.device): the device on which the random numbers will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.-- Returns:- params Dict[str, torch.Tensor]: parameters to be passed for transformation.- - degrees (torch.Tensor): element-wise rotation degrees with a shape of (B,).-- Note:- The generated random numbers are not reproducible across different devices and dtypes.- """- _common_param_check(batch_size, same_on_batch)- _joint_range_check(degrees, "degrees")-- _degrees = _adapted_uniform(- (batch_size,),- degrees[0].to(device=device, dtype=dtype),- degrees[1].to(device=device, dtype=dtype),- same_on_batch,- )- _degrees = _degrees.to(device=degrees.device, dtype=degrees.dtype)-- return dict(degrees=_degrees)---@_deprecated()-def random_solarize_generator(- batch_size: int,- thresholds: torch.Tensor = torch.tensor([0.4, 0.6]),- additions: torch.Tensor = torch.tensor([-0.1, 0.1]),- same_on_batch: bool = False,- device: torch.device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, torch.Tensor]:- r"""Generate random solarize parameters for a batch of images.-- For each pixel in the image less than threshold, we add 'addition' amount to it and then clip the pixel value- to be between 0 and 1.0-- Args:- batch_size (int): the number of images.- thresholds (torch.Tensor): Pixels less than threshold will selected. Otherwise, subtract 1.0 from the pixel.- Takes in a range tensor of (0, 1). Default value will be sampled from [0.4, 0.6].- additions (torch.Tensor): The value is between -0.5 and 0.5. Default value will be sampled from [-0.1, 0.1]- same_on_batch (bool): apply the same transformation across the batch. Default: False.- device (torch.device): the device on which the random numbers will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.-- Returns:- params Dict[str, torch.Tensor]: parameters to be passed for transformation.- - thresholds_factor (torch.Tensor): element-wise thresholds factors with a shape of (B,).- - additions_factor (torch.Tensor): element-wise additions factors with a shape of (B,).-- Note:- The generated random numbers are not reproducible across different devices and dtypes.- """- _common_param_check(batch_size, same_on_batch)- _joint_range_check(thresholds, 'thresholds', (0, 1))- _joint_range_check(additions, 'additions', (-0.5, 0.5))-- _device, _dtype = _extract_device_dtype([thresholds, additions])-- thresholds_factor = _adapted_uniform(- (batch_size,),- thresholds[0].to(device=device, dtype=dtype),- thresholds[1].to(device=device, dtype=dtype),- same_on_batch,- )-- additions_factor = _adapted_uniform(- (batch_size,),- additions[0].to(device=device, dtype=dtype),- additions[1].to(device=device, dtype=dtype),- same_on_batch,- )-- return dict(- thresholds_factor=thresholds_factor.to(device=_device, dtype=_dtype),- additions_factor=additions_factor.to(device=_device, dtype=_dtype),- )---@_deprecated()-def random_sharpness_generator(- batch_size: int,- sharpness: torch.Tensor = torch.tensor([0, 1.0]),- same_on_batch: bool = False,- device: torch.device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, torch.Tensor]:- r"""Generate random sharpness parameters for a batch of images.-- Args:- batch_size (int): the number of images.- sharpness (torch.Tensor): Must be above 0. Default value is sampled from (0, 1).- same_on_batch (bool): apply the same transformation across the batch. Default: False.- device (torch.device): the device on which the random numbers will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.-- Returns:- params Dict[str, torch.Tensor]: parameters to be passed for transformation.- - sharpness_factor (torch.Tensor): element-wise sharpness factors with a shape of (B,).-- Note:- The generated random numbers are not reproducible across different devices and dtypes.- """- _common_param_check(batch_size, same_on_batch)- _joint_range_check(sharpness, 'sharpness', bounds=(0, float('inf')))-- sharpness_factor = _adapted_uniform(- (batch_size,),- sharpness[0].to(device=device, dtype=dtype),- sharpness[1].to(device=device, dtype=dtype),- same_on_batch,- )-- return dict(sharpness_factor=sharpness_factor.to(device=sharpness.device, dtype=sharpness.dtype))diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.pyindex 5d013c112..c7d1744b7 100644--- a/kornia/augmentation/random_generator/_2d/motion_blur.py+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py@@ -4,15 +4,9 @@ import torchfrom torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBase-from kornia.augmentation.utils import (- _adapted_rsampling,- _adapted_uniform,- _common_param_check,- _joint_range_check,- _range_bound,-)-from kornia.core import Tensor, tensor-from kornia.utils.helpers import _deprecated, _extract_device_dtype+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound+from kornia.core import Tensor+from kornia.utils.helpers import _extract_device_dtypeclass MotionBlurGenerator(RandomGeneratorBase):@@ -90,74 +84,3 @@ class MotionBlurGenerator(RandomGeneratorBase):angle_factor=angle_factor.to(device=_device, dtype=_dtype),direction_factor=direction_factor.to(device=_device, dtype=_dtype),)---@_deprecated(replace_with=MotionBlurGenerator.__name__)-def random_motion_blur_generator(- batch_size: int,- kernel_size: Union[int, Tuple[int, int]],- angle: Tensor,- direction: Tensor,- same_on_batch: bool = False,- device: torch.device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, Tensor]:- r"""Get parameters for motion blur.-- Args:- batch_size (int): the tensor batch size.- kernel_size (int or (int, int)): motion kernel size (odd and positive) or range.- angle (Tensor): angle of the motion blur in degrees (anti-clockwise rotation).- direction (Tensor): 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.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- device (torch.device): the device on which the random numbers will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.-- Returns:- params Dict[str, Tensor]: parameters to be passed for transformation.- - ksize_factor (Tensor): element-wise kernel size factors with a shape of (B,).- - angle_factor (Tensor): element-wise angle factors with a shape of (B,).- - direction_factor (Tensor): element-wise direction factors with a shape of (B,).-- Note:- The generated random numbers are not reproducible across different devices and dtypes.- """- _common_param_check(batch_size, same_on_batch)- _joint_range_check(angle, 'angle')- _joint_range_check(direction, 'direction', (-1, 1))-- _device, _dtype = _extract_device_dtype([angle, direction])-- if isinstance(kernel_size, int):- if not (kernel_size >= 3 and kernel_size % 2 == 1):- raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {kernel_size}.")- ksize_factor = tensor([kernel_size] * batch_size, device=device, dtype=dtype)- elif isinstance(kernel_size, tuple):- # kernel_size is fixed across the batch- if len(kernel_size) != 2:- raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {kernel_size}.")- ksize_factor = (- _adapted_uniform((batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1- )- else:- raise TypeError(f"Unsupported type: {type(kernel_size)}")-- angle_factor = _adapted_uniform(- (batch_size,), angle[0].to(device=device, dtype=dtype), angle[1].to(device=device, dtype=dtype), same_on_batch- )-- direction_factor = _adapted_uniform(- (batch_size,),- direction[0].to(device=device, dtype=dtype),- direction[1].to(device=device, dtype=dtype),- same_on_batch,- )-- 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),- )diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.pyindex 29841e6b6..dbb67edbd 100644--- a/kornia/augmentation/random_generator/_2d/perspective.py+++ b/kornia/augmentation/random_generator/_2d/perspective.py@@ -4,9 +4,9 @@ import torchfrom torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBase-from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check+from kornia.augmentation.utils import _adapted_rsampling, _common_param_checkfrom kornia.core import Tensor, tensor-from kornia.utils.helpers import _deprecated, _extract_device_dtype+from kornia.utils.helpers import _extract_device_dtypeclass PerspectiveGenerator(RandomGeneratorBase):@@ -82,63 +82,3 @@ class PerspectiveGenerator(RandomGeneratorBase):end_points = start_points + offsetreturn dict(start_points=start_points, end_points=end_points)---@_deprecated(replace_with=PerspectiveGenerator.__name__)-def random_perspective_generator(- batch_size: int,- height: int,- width: int,- distortion_scale: Tensor,- same_on_batch: bool = False,- device: torch.device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, Tensor]:- r"""Get parameters for ``perspective`` for a random perspective transform.-- Args:- batch_size (int): the tensor batch size.- height (int) : height of the image.- width (int): width of the image.- distortion_scale (Tensor): it controls the degree of distortion and ranges from 0 to 1.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- device (torch.device): the device on which the random numbers will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.-- Returns:- params Dict[str, Tensor]: parameters to be passed for transformation.- - start_points (Tensor): element-wise perspective source areas with a shape of (B, 4, 2).- - end_points (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.- """- _common_param_check(batch_size, same_on_batch)- if not (distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1):- raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}.")- 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: Tensor = tensor(- [[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],- device=distortion_scale.device,- dtype=distortion_scale.dtype,- ).expand(batch_size, -1, -1)-- # generate random offset not larger than half of the image- fx = distortion_scale * width / 2- fy = distortion_scale * height / 2-- factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2)-- # TODO: This line somehow breaks the gradcheck- rand_val: Tensor = _adapted_uniform(- start_points.shape, tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), same_on_batch- ).to(device=distortion_scale.device, dtype=distortion_scale.dtype)-- pts_norm = tensor(- [[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=distortion_scale.device, dtype=distortion_scale.dtype- )- end_points = start_points + factor * rand_val * pts_norm-- return dict(start_points=start_points, end_points=end_points)diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.pyindex 8a3e037e0..0f076831b 100644--- a/kornia/augmentation/random_generator/_2d/posterize.py+++ b/kornia/augmentation/random_generator/_2d/posterize.py@@ -4,9 +4,9 @@ import torchfrom torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBase-from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _joint_range_check-from kornia.core import Tensor, as_tensor, tensor-from kornia.utils.helpers import _deprecated, _extract_device_dtype+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check+from kornia.core import Tensor, as_tensor+from kornia.utils.helpers import _extract_device_dtypeclass PosterizeGenerator(RandomGeneratorBase):@@ -51,36 +51,3 @@ class PosterizeGenerator(RandomGeneratorBase):_device, _ = _extract_device_dtype([self.bits if isinstance(self.bits, 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))---@_deprecated()-def random_posterize_generator(- batch_size: int,- bits: Tensor = tensor([3, 5]),- same_on_batch: bool = False,- device: torch.device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, Tensor]:- r"""Generate random posterize parameters for a batch of images.-- Args:- batch_size (int): the number of images.- bits (int or tuple): Takes in an integer tuple tensor that ranged from 0 ~ 8. Default value is [3, 5].- same_on_batch (bool): apply the same transformation across the batch. Default: False.- device (torch.device): the device on which the random numbers will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.-- Returns:- params Dict[str, Tensor]: parameters to be passed for transformation.- - bits_factor (Tensor): element-wise bit factors with a shape of (B,).-- Note:- The generated random numbers are not reproducible across different devices and dtypes.- """- _common_param_check(batch_size, same_on_batch)- _joint_range_check(bits, 'bits', (0, 8))- bits_factor = _adapted_uniform(- (batch_size,), bits[0].to(device=device, dtype=dtype), bits[1].to(device=device, dtype=dtype), same_on_batch- ).int()-- return dict(bits_factor=bits_factor.to(device=bits.device, dtype=torch.int32))diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.pyindex 988544220..85bd5d4d6 100644--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py@@ -4,9 +4,9 @@ import torchfrom torch.distributions import Uniformfrom kornia.augmentation.random_generator.base import RandomGeneratorBase-from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _joint_range_check+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_checkfrom kornia.core import Tensor, as_tensor, tensor, where-from kornia.utils.helpers import _deprecated, _extract_device_dtype+from kornia.utils.helpers import _extract_device_dtypeclass RectangleEraseGenerator(RandomGeneratorBase):@@ -131,123 +131,3 @@ class RectangleEraseGenerator(RandomGeneratorBase):ys=ys.floor(),values=tensor([self.value] * batch_size, device=_device, dtype=_dtype),)---@_deprecated(replace_with=RectangleEraseGenerator.__name__)-def random_rectangles_params_generator(- batch_size: int,- height: int,- width: int,- scale: Tensor,- ratio: Tensor,- value: float = 0.0,- same_on_batch: bool = False,- device: torch.device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, Tensor]:- r"""Get parameters for ```erasing``` transformation for erasing transform.-- Args:- batch_size (int): the tensor batch size.- height (int) : height of the image.- width (int): width of the image.- scale (Tensor): range of size of the origin size cropped. Shape (2).- ratio (Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).- value (float): value to be filled in the erased area.- same_on_batch (bool): apply the same transformation across the batch. Default: False.- device (torch.device): the device on which the random numbers will be generated. Default: cpu.- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.-- Returns:- params Dict[str, Tensor]: parameters to be passed for transformation.- - widths (Tensor): element-wise erasing widths with a shape of (B,).- - heights (Tensor): element-wise erasing heights with a shape of (B,).- - xs (Tensor): element-wise erasing x coordinates with a shape of (B,).- - ys (Tensor): element-wise erasing y coordinates with a shape of (B,).- - values (Tensor): element-wise filling values with a shape of (B,).-- Note:- The generated random numbers are not reproducible across different devices and dtypes.- """- _common_param_check(batch_size, same_on_batch)- _device, _dtype = _extract_device_dtype([ratio, scale])- 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}.")- if not (isinstance(value, (int, float)) and value >= 0 and value <= 1):- raise AssertionError(f"'value' must be a number between 0 - 1. Got {value}.")- _joint_range_check(scale, 'scale', bounds=(0, float('inf')))- _joint_range_check(ratio, 'ratio', bounds=(0, float('inf')))-- images_area = height * width- target_areas = (- _adapted_uniform(- (batch_size,),- scale[0].to(device=device, dtype=dtype),- scale[1].to(device=device, dtype=dtype),- same_on_batch,- )- * images_area- )-- if ratio[0] < 1.0 and ratio[1] > 1.0:- aspect_ratios1 = _adapted_uniform((batch_size,), ratio[0].to(device=device, dtype=dtype), 1, same_on_batch)- aspect_ratios2 = _adapted_uniform((batch_size,), 1, ratio[1].to(device=device, dtype=dtype), same_on_batch)- if same_on_batch:- rand_idxs = (- torch.round(- _adapted_uniform(- (1,),- tensor(0, device=device, dtype=dtype),- tensor(1, device=device, dtype=dtype),- same_on_batch,- )- )- .repeat(batch_size)- .bool()- )- else:- rand_idxs = torch.round(- _adapted_uniform(- (batch_size,),- tensor(0, device=device, dtype=dtype),- tensor(1, device=device, dtype=dtype),- same_on_batch,- )- ).bool()- aspect_ratios = where(rand_idxs, aspect_ratios1, aspect_ratios2)- else:- aspect_ratios = _adapted_uniform(- (batch_size,),- ratio[0].to(device=device, dtype=dtype),- ratio[1].to(device=device, dtype=dtype),- same_on_batch,- )-- # based on target areas and aspect ratios, rectangle params are computed- heights = torch.min(- torch.max(torch.round((target_areas * aspect_ratios) ** (1 / 2)), tensor(1.0, device=device, dtype=dtype)),- tensor(height, device=device, dtype=dtype),- )-- widths = torch.min(- torch.max(torch.round((target_areas / aspect_ratios) ** (1 / 2)), tensor(1.0, device=device, dtype=dtype)),- tensor(width, device=device, dtype=dtype),- )-- xs_ratio = _adapted_uniform(- (batch_size,), tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), same_on_batch- )- ys_ratio = _adapted_uniform(- (batch_size,), tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), same_on_batch- )-- xs = xs_ratio * (tensor(width, device=device, dtype=dtype) - widths + 1)- ys = ys_ratio * (tensor(height, device=device, dtype=dtype) - heights + 1)-- return dict(- widths=widths.floor().to(device=_device, dtype=_dtype),- heights=heights.floor().to(device=_device, dtype=_dtype),- xs=xs.floor().to(device=_device, dtype=_dtype),- ys=ys.floor().to(device=_device, dtype=_dtype),- values=tensor([value] * batch_size, device=_device, dtype=_dtype),- )