π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Init 3D augmentations (#592)
shijianjian685d7970c79a
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 5166984c5..83766b70a 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -1,4 +1,26 @@-from .augmentation import *+from .augmentation import (+ RandomAffine,+ RandomCrop,+ RandomErasing,+ RandomGrayscale,+ RandomHorizontalFlip,+ RandomVerticalFlip,+ RandomPerspective,+ RandomResizedCrop,+ RandomRotation,+ CenterCrop,+ ColorJitter,+ RandomSolarize,+ RandomPosterize,+ RandomSharpness,+ RandomEqualize,+ RandomMotionBlur+)+from .augmentation3d import (+ RandomHorizontalFlip3D,+ RandomVerticalFlip3D,+ RandomDepthicalFlip3D+)from kornia.color.normalize import (Normalize,Denormalize@@ -10,7 +32,10 @@ __all__ = ["RandomErasing","RandomGrayscale","RandomHorizontalFlip",+ "RandomHorizontalFlip3D","RandomVerticalFlip",+ "RandomVerticalFlip3D",+ "RandomDepthicalFlip3D","RandomPerspective","RandomResizedCrop","RandomRotation",@@ -20,6 +45,7 @@ __all__ = ["RandomPosterize","RandomSharpness","RandomEqualize",+ "RandomMotionBlur","Normalize",- "Denormalize"+ "Denormalize",]diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex c249e36a3..454f9fc6f 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -11,13 +11,6 @@ from .utils import (_adapted_uniform,_infer_batch_shape)-from .types import (- TupleFloat,- UnionFloat,- UnionType,- FloatUnionType,- BoarderUnionType-)class AugmentationBase(nn.Module):@@ -35,7 +28,7 @@ class AugmentationBase(nn.Module):super(AugmentationBase, self).__init__()self.return_transform = return_transform- def infer_batch_shape(self, input: UnionType) -> torch.Size:+ def infer_batch_shape(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:return _infer_batch_shape(input)def generate_parameters(self, input_shape: torch.Size) -> Dict[str, torch.Tensor]:@@ -47,8 +40,10 @@ class AugmentationBase(nn.Module):def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:raise NotImplementedError- def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None, # type: ignore- return_transform: Optional[bool] = None) -> UnionType: # type: ignore+ def forward(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],+ params: Optional[Dict[str, torch.Tensor]] = None, # type: ignore+ return_transform: Optional[bool] = None+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignoreif return_transform is None:return_transform = self.return_transformif params is None:@@ -207,14 +202,17 @@ class ColorJitter(AugmentationBase):"""def __init__(- self, brightness: FloatUnionType = 0., contrast: FloatUnionType = 0., saturation: FloatUnionType = 0.,- hue: FloatUnionType = 0., return_transform: bool = False, same_on_batch: bool = False+ self, brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,+ return_transform: bool = False, same_on_batch: bool = False) -> None:super(ColorJitter, self).__init__(return_transform)- self.brightness: FloatUnionType = brightness- self.contrast: FloatUnionType = contrast- self.saturation: FloatUnionType = saturation- self.hue: FloatUnionType = hue+ self.brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = brightness+ self.contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = contrast+ self.saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = saturation+ self.hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = hueself.same_on_batch = same_on_batchdef __repr__(self) -> str:@@ -422,10 +420,10 @@ class RandomAffine(AugmentationBase):"""def __init__(- self, degrees: UnionFloat, translate: Optional[TupleFloat] = None, scale: Optional[TupleFloat] = None,- shear: Optional[UnionFloat] = None, resample: Union[str, int, Resample] = Resample.BILINEAR.name,- return_transform: bool = False, same_on_batch: bool = False,- align_corners: bool = False+ self, degrees: Union[float, Tuple[float, float]], translate: Optional[Tuple[float, float]] = None,+ scale: Optional[Tuple[float, float]] = None, shear: Optional[Union[float, Tuple[float, float]]] = None,+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,+ return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False) -> None:super(RandomAffine, self).__init__(return_transform)self.degrees = degrees@@ -534,7 +532,8 @@ class RandomRotation(AugmentationBase):# Note: Extra params, center=None, fill=0 in TorchVisiondef __init__(- self, degrees: FloatUnionType, interpolation: Union[str, int, Resample] = Resample.BILINEAR.name,+ self, degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],+ interpolation: Union[str, int, Resample] = Resample.BILINEAR.name,return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False) -> None:super(RandomRotation, self).__init__(return_transform)@@ -591,9 +590,9 @@ class RandomCrop(AugmentationBase):"""def __init__(- self, size: Tuple[int, int], padding: Optional[BoarderUnionType] = None, pad_if_needed: Optional[bool] = False,- fill: int = 0, padding_mode: str = 'constant', return_transform: bool = False, same_on_batch: bool = False,- align_corners: bool = False+ self, size: Tuple[int, int], padding: Optional[Union[int, Tuple[int, int], Tuple[int, int, int, int]]] = None,+ pad_if_needed: Optional[bool] = False, fill: int = 0, padding_mode: str = 'constant',+ return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False) -> None:super(RandomCrop, self).__init__(return_transform)self.size = size@@ -640,8 +639,9 @@ class RandomCrop(AugmentationBase):def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.apply_crop(input, params)- def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None, # type: ignore- return_transform: Optional[bool] = None) -> UnionType: # type: ignore+ def forward(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],+ params: Optional[Dict[str, torch.Tensor]] = None, return_transform: Optional[bool] = None+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignoreif type(input) == tuple:input = (self.precrop_padding(input[0]), input[1])else:@@ -803,7 +803,8 @@ class RandomSolarize(AugmentationBase):"""def __init__(- self, thresholds: FloatUnionType = 0.1, additions: FloatUnionType = 0.1,+ self, thresholds: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,+ additions: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,same_on_batch: bool = False, return_transform: bool = False) -> None:super(RandomSolarize, self).__init__(return_transform)diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.pynew file mode 100644index 000000000..8b0d19adb--- /dev/null+++ b/kornia/augmentation/augmentation3d.py@@ -0,0 +1,188 @@+from typing import Callable, Tuple, Union, List, Optional, Dict, cast++import torch+import torch.nn as nn+from torch.nn.functional import pad++from kornia.constants import Resample, BorderType+from .augmentation import AugmentationBase+from . import functional3d as F+from . import random_generator as rg+from .utils import (+ _infer_batch_shape3d+)+++class AugmentationBase3D(AugmentationBase):+ def __init__(self, return_transform: bool = False) -> None:+ super(AugmentationBase3D, self).__init__(return_transform=return_transform)++ def infer_batch_shape(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:+ return _infer_batch_shape3d(input)+++class RandomHorizontalFlip3D(AugmentationBase3D):++ r"""Horizontally flip a tensor image or a batch of tensor images randomly with a given probability.+ Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`.+ If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,+ the corresponding transformation matrix that has been applied to them. In this case the module+ will Horizontally flip the tensors and concatenate the corresponding transformation matrix to the+ previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.++ Args:+ p (float): probability of the image being flipped. Default value is 0.5+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation+ wont be concatenated+ same_on_batch (bool): apply the same transformation across the batch. Default: False++ Examples:+ >>> x = torch.eye(3).repeat(3, 1, 1)+ >>> seq = RandomHorizontalFlip3D(p=1.0, return_transform=True)+ >>> seq(x)+ (tensor([[[[[0., 0., 1.],+ [0., 1., 0.],+ [1., 0., 0.]],+ <BLANKLINE>+ [[0., 0., 1.],+ [0., 1., 0.],+ [1., 0., 0.]],+ <BLANKLINE>+ [[0., 0., 1.],+ [0., 1., 0.],+ [1., 0., 0.]]]]]), tensor([[[-1., 0., 0., 3.],+ [ 0., 1., 0., 0.],+ [ 0., 0., 1., 0.],+ [ 0., 0., 0., 1.]]]))++ """++ def __init__(self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False) -> None:+ super(RandomHorizontalFlip3D, self).__init__(return_transform)+ self.p: float = p+ self.same_on_batch = same_on_batch++ def __repr__(self) -> str:+ repr = f"(p={self.p}, return_transform={self.return_transform}, same_on_batch={self.same_on_batch})"+ return self.__class__.__name__ + repr++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return rg.random_prob_generator(batch_shape[0], self.p, self.same_on_batch)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_hflip_transformation3d(input, params)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.apply_hflip3d(input, params)+++class RandomVerticalFlip3D(AugmentationBase3D):++ r"""Vertically flip a tensor image or a batch of tensor images randomly with a given probability.+ Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`.+ If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,+ the corresponding transformation matrix that has been applied to them. In this case the module+ will Vertically flip the tensors and concatenate the corresponding transformation matrix to the+ previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.++ Args:+ p (float): probability of the image being flipped. Default value is 0.5+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation+ wont be concatenated+ same_on_batch (bool): apply the same transformation across the batch. Default: False++ Examples:+ >>> x = torch.eye(3).repeat(3, 1, 1)+ >>> seq = RandomVerticalFlip3D(p=1.0, return_transform=True)+ >>> seq(x)+ (tensor([[[[[0., 0., 1.],+ [0., 1., 0.],+ [1., 0., 0.]],+ <BLANKLINE>+ [[0., 0., 1.],+ [0., 1., 0.],+ [1., 0., 0.]],+ <BLANKLINE>+ [[0., 0., 1.],+ [0., 1., 0.],+ [1., 0., 0.]]]]]), tensor([[[ 1., 0., 0., 0.],+ [ 0., -1., 0., 3.],+ [ 0., 0., 1., 0.],+ [ 0., 0., 0., 1.]]]))+ """++ def __init__(self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False) -> None:+ super(RandomVerticalFlip3D, self).__init__(return_transform)+ self.p: float = p+ self.same_on_batch = same_on_batch++ def __repr__(self) -> str:+ repr = f"(p={self.p}, return_transform={self.return_transform}, same_on_batch={self.same_on_batch})"+ return self.__class__.__name__ + repr++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return rg.random_prob_generator(batch_shape[0], self.p, self.same_on_batch)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_vflip_transformation3d(input, params)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.apply_vflip3d(input, params)+++class RandomDepthicalFlip3D(AugmentationBase3D):++ r"""Depthically flip a tensor image or a batch of tensor images randomly with a given probability.+ Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`.+ If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,+ the corresponding transformation matrix that has been applied to them. In this case the module+ will Depthically flip the tensors and concatenate the corresponding transformation matrix to the+ previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.++ Args:+ p (float): probability of the image being flipped. Default value is 0.5+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation+ wont be concatenated+ same_on_batch (bool): apply the same transformation across the batch. Default: False++ Examples:+ >>> x = torch.eye(3).repeat(3, 1, 1)+ >>> seq = RandomDepthicalFlip3D(p=1.0, return_transform=True)+ >>> seq(x)+ (tensor([[[[[1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.]],+ <BLANKLINE>+ [[1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.]],+ <BLANKLINE>+ [[1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.]]]]]), tensor([[[ 1., 0., 0., 0.],+ [ 0., 1., 0., 0.],+ [ 0., 0., -1., 3.],+ [ 0., 0., 0., 1.]]]))++ """++ def __init__(self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False) -> None:+ super(RandomDepthicalFlip3D, self).__init__(return_transform)+ self.p: float = p+ self.same_on_batch = same_on_batch++ def __repr__(self) -> str:+ repr = f"(p={self.p}, return_transform={self.return_transform}, same_on_batch={self.same_on_batch})"+ return self.__class__.__name__ + repr++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return rg.random_prob_generator(batch_shape[0], self.p, self.same_on_batch)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_dflip_transformation3d(input, params)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.apply_dflip3d(input, params)diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.pyindex 9ee5dabc6..823567f19 100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@ -33,15 +33,10 @@ from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _computefrom . import random_generator as rgfrom .utils import _transform_input, _validate_input_shape, _validate_input_dtype-from .types import (- TupleFloat,- UnionFloat,- UnionType,- FloatUnionType-)-def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False) -> UnionType:+def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:r"""Generate params and apply operation on input tensor.See :func:`~kornia.augmentation.random_generator.random_prob_generator` for details.@@ -56,7 +51,8 @@ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = Freturn output-def random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False) -> UnionType:+def random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:r"""Generate params and apply operation on input tensor.See :func:`~kornia.augmentation.random_generator.random_prob_generator` for details.@@ -71,9 +67,11 @@ def random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = Freturn output-def color_jitter(input: torch.Tensor, brightness: FloatUnionType = 0.,- contrast: FloatUnionType = 0., saturation: FloatUnionType = 0.,- hue: FloatUnionType = 0., return_transform: bool = False) -> UnionType:+def color_jitter(input: torch.Tensor, brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0., return_transform: bool = False+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:r"""Generate params and apply operation on input tensor.See :func:`~kornia.augmentation.random_generator.random_color_jitter_generator` for details.@@ -107,7 +105,7 @@ def random_grayscale(input: torch.Tensor, p: float = 0.5, return_transform: booldef random_perspective(input: torch.Tensor,distortion_scale: float = 0.5,p: float = 0.5,- return_transform: bool = False) -> UnionType:+ return_transform: bool = False) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:r"""Generate params and apply operation on input tensor.See :func:`~kornia.augmentation.random_generator.random_perspective_generator` for details.@@ -126,12 +124,12 @@ def random_perspective(input: torch.Tensor,def random_affine(input: torch.Tensor,- degrees: UnionFloat,- translate: Optional[TupleFloat] = None,- scale: Optional[TupleFloat] = None,- shear: Optional[UnionFloat] = None,+ degrees: Union[float, Tuple[float, float]],+ translate: Optional[Tuple[float, float]] = None,+ scale: Optional[Tuple[float, float]] = None,+ shear: Optional[Union[float, Tuple[float, float]]] = None,resample: Union[str, int, Resample] = Resample.BILINEAR.name,- return_transform: bool = False) -> UnionType:+ return_transform: bool = False) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:r"""Generate params and apply operation on input tensor.See :func:`~kornia.augmentation.random_generator.random_affine_generator` for details.@@ -155,7 +153,7 @@ def random_rectangle_erase(scale: Tuple[float, float] = (0.02, 0.33),ratio: Tuple[float, float] = (0.3, 3.3),return_transform: bool = False-) -> UnionType:+) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:r"""Function that erases a random selected rectangle for each image in the batch, puttingthe value to zero.@@ -182,7 +180,8 @@ def random_rectangle_erase(return output-def random_rotation(input: torch.Tensor, degrees: FloatUnionType, return_transform: bool = False) -> UnionType:+def random_rotation(input: torch.Tensor, degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],+ return_transform: bool = False) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:r"""Generate params and apply operation on input tensor.See :func:`~kornia.augmentation.random_generator.random_rotation_generator` for details.diff --git a/kornia/augmentation/functional3d.py b/kornia/augmentation/functional3d.pynew file mode 100644index 000000000..f63034622--- /dev/null+++ b/kornia/augmentation/functional3d.py@@ -0,0 +1,224 @@+from typing import Tuple, List, Union, Dict, cast, Optional++import torch++from . import random_generator as rg+from .utils import _transform_input3d, _validate_input_dtype+++def random_hflip3d(input: torch.Tensor, p: float = 0.5, return_transform: bool = False+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:+ r"""Generate params and apply operation on input tensor.++ See :func:`~kornia.augmentation.random_generator.random_prob_generator` for details.+ See :func:`~kornia.augmentation.functional.apply_hflip3d` for details.+ """+ input = _transform_input3d(input)+ batch_size, _, d, h, w = input.size()+ params = rg.random_prob_generator(batch_size, p=p)+ output = apply_hflip3d(input, params)+ if return_transform:+ raise NotImplementedError+ return output+++def random_vflip3d(input: torch.Tensor, p: float = 0.5, return_transform: bool = False+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:+ r"""Generate params and apply operation on input tensor.++ See :func:`~kornia.augmentation.random_generator.random_prob_generator` for details.+ See :func:`~kornia.augmentation.functional3d.apply_vflip3d` for details.+ """+ input = _transform_input3d(input)+ batch_size, _, d, h, w = input.size()+ params = rg.random_prob_generator(batch_size, p=p)+ output = apply_vflip3d(input, params)+ if return_transform:+ raise NotImplementedError+ return output+++def random_dflip3d(input: torch.Tensor, p: float = 0.5, return_transform: bool = False+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:+ r"""Generate params and apply operation on input tensor.++ See :func:`~kornia.augmentation.random_generator.random_prob_generator` for details.+ See :func:`~kornia.augmentation.functional3d.apply_dflip3d` for details.+ """+ input = _transform_input3d(input)+ batch_size, _, d, h, w = input.size()+ params = rg.random_prob_generator(batch_size, p=p)+ output = apply_dflip3d(input, params)+ if return_transform:+ raise NotImplementedError+ return output+++def apply_hflip3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Apply horizontal flip on a 3D tensor volume or a batch of tensors volumes with given random parameters.+ Input should be a tensor of shape :math:`(D, H, W)`, :math:`(C, D, H, W)` or :math:`(*, C, D, H, W)`.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape :math:`(D, H, W)`, :math:`(C, D, H, W)`,+ :math:`(*, C, D, H, W)`.+ params (Dict[str, torch.Tensor]):+ - params['batch_prob']: A boolean tensor that indicating whether if to transform an image in a batch.+ Example: With input batchsize of 4, only the first two tensors will be transformed if+ batch_prob is [True, True, False, False].++ Returns:+ torch.Tensor: The horizontal flipped input+ """+ # TODO: params validation++ input = _transform_input3d(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])++ flipped: torch.Tensor = input.clone()++ to_flip = params['batch_prob'].to(input.device)+ flipped[to_flip] = torch.flip(input[to_flip], [-1])++ return flipped+++def compute_hflip_transformation3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Compute the applied transformation matrix :math: `(*, 4, 4)`.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape :math:`(D, H, W)`, :math:`(C, D, H, W)`,+ :math:`(*, C, D, H, W)`.+ params (Dict[str, torch.Tensor]):+ - params['batch_prob']: A boolean tensor that indicating whether if to transform an image in a batch.+ Example: With input batchsize of 4, only the first two tensors will be transformed if+ batch_prob is [True, True, False, False].++ Returns:+ torch.Tensor: The applied transformation matrix :math: `(*, 4, 4)`+ """+ input = _transform_input3d(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+ to_flip = params['batch_prob'].to(input.device)+ trans_mat: torch.Tensor = torch.eye(4, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)+ w: int = input.shape[-1]+ flip_mat: torch.Tensor = torch.tensor([[-1, 0, 0, w],+ [0, 1, 0, 0],+ [0, 0, 1, 0],+ [0, 0, 0, 1]])+ trans_mat[to_flip] = flip_mat.type_as(input)++ return trans_mat+++def apply_vflip3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Apply vertical flip on a 3D tensor volume or a batch of tensors volumes with given random parameters.+ Input should be a tensor of shape :math:`(D, H, W)`, :math:`(C, D, H, W)` or :math:`(*, C, D, H, W)`.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape :math:`(D, H, W)`, :math:`(C, D, H, W)`,+ :math:`(*, C, D, H, W)`.+ params (Dict[str, torch.Tensor]):+ - params['batch_prob']: A boolean tensor that indicating whether if to transform an image in a batch.+ Example: With input batchsize of 4, only the first two tensors will be transformed if+ batch_prob is [True, True, False, False].++ Returns:+ torch.Tensor: The vertical flipped input+ """+ # TODO: params validation++ input = _transform_input3d(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])++ flipped: torch.Tensor = input.clone()+ to_flip = params['batch_prob'].to(input.device)+ flipped[to_flip] = torch.flip(input[to_flip], [-2])++ return flipped+++def compute_vflip_transformation3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Compute the applied transformation matrix :math: `(*, 4, 4)`.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape :math:`(D, H, W)`, :math:`(C, D, H, W)`,+ :math:`(*, C, D, H, W)`.+ params (Dict[str, torch.Tensor]):+ - params['batch_prob']: A boolean tensor that indicating whether if to transform an image in a batch.+ Example: With input batchsize of 4, only the first two tensors will be transformed if+ batch_prob is [True, True, False, False].++ Returns:+ torch.Tensor: The applied transformation matrix :math: `(*, 4, 4)`+ """+ input = _transform_input3d(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+ to_flip = params['batch_prob'].to(input.device)+ trans_mat: torch.Tensor = torch.eye(4, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)++ h: int = input.shape[-2]+ flip_mat: torch.Tensor = torch.tensor([[1, 0, 0, 0],+ [0, -1, 0, h],+ [0, 0, 1, 0],+ [0, 0, 0, 1]])++ trans_mat[to_flip] = flip_mat.type_as(input)++ return trans_mat+++def apply_dflip3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Apply depthical flip on a 3D tensor volume or a batch of tensors volumes with given random parameters.+ Input should be a tensor of shape :math:`(D, H, W)`, :math:`(C, D, H, W)` or :math:`(*, C, D, H, W)`.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape :math:`(D, H, W)`, :math:`(C, D, H, W)`,+ :math:`(*, C, D, H, W)`.+ params (Dict[str, torch.Tensor]):+ - params['batch_prob']: A boolean tensor that indicating whether if to transform an image in a batch.+ Example: With input batchsize of 4, only the first two tensors will be transformed if+ batch_prob is [True, True, False, False].++ Returns:+ torch.Tensor: The depthical flipped input.+ """+ # TODO: params validation++ input = _transform_input3d(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])++ flipped: torch.Tensor = input.clone()+ to_flip = params['batch_prob'].to(input.device)+ flipped[to_flip] = torch.flip(input[to_flip], [-3])++ return flipped+++def compute_dflip_transformation3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Compute the applied transformation matrix :math: `(*, 4, 4)`.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape :math:`(D, H, W)`, :math:`(C, D, H, W)`,+ :math:`(*, C, D, H, W)`.+ params (Dict[str, torch.Tensor]):+ - params['batch_prob']: A boolean tensor that indicating whether if to transform an image in a batch.+ Example: With input batchsize of 4, only the first two tensors will be transformed if+ batch_prob is [True, True, False, False].++ Returns:+ torch.Tensor: The applied transformation matrix :math: `(*, 4, 4)`+ """+ input = _transform_input3d(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+ to_flip = params['batch_prob'].to(input.device)+ trans_mat: torch.Tensor = torch.eye(4, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)++ d: int = input.shape[-3]+ flip_mat: torch.Tensor = torch.tensor([[1, 0, 0, 0],+ [0, 1, 0, 0],+ [0, 0, -1, d],+ [0, 0, 0, 1]])++ trans_mat[to_flip] = flip_mat.type_as(input)++ return trans_matdiff --git a/kornia/augmentation/random_generator.py b/kornia/augmentation/random_generator.pyindex abe5aef15..f37ae17bf 100644--- a/kornia/augmentation/random_generator.py+++ b/kornia/augmentation/random_generator.py@@ -5,25 +5,18 @@ import mathimport torchfrom kornia.constants import Resample, BorderType-from kornia.augmentation.utils import (+from .utils import (_adapted_uniform,_check_and_bound)-from .types import (- TupleFloat,- UnionFloat,- UnionType,- FloatUnionType-)-def random_color_jitter_generator(batch_size: int,- brightness: FloatUnionType = 0.,- contrast: FloatUnionType = 0.,- saturation: FloatUnionType = 0.,- hue: FloatUnionType = 0.,+ brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,same_on_batch: bool = False) -> Dict[str, torch.Tensor]:r"""Generator random color jiter parameters for a batch of images.@@ -167,10 +160,10 @@ def random_affine_generator(batch_size: int,height: int,width: int,- degrees: UnionFloat,- translate: Optional[TupleFloat] = None,- scale: Optional[TupleFloat] = None,- shear: Optional[UnionFloat] = None,+ degrees: Union[float, Tuple[float, float]],+ translate: Optional[Tuple[float, float]] = None,+ scale: Optional[Tuple[float, float]] = None,+ shear: Optional[Union[float, Tuple[float, float]]] = None,resample: Union[str, int, Resample] = Resample.BILINEAR.name,same_on_batch: bool = False,align_corners: bool = False@@ -205,7 +198,7 @@ def random_affine_generator(params Dict[str, torch.Tensor]: parameters to be passed for transformation."""# check angle ranges- degrees_tmp: TupleFloat+ degrees_tmp: Tuple[float, float]if isinstance(degrees, (float, int,)):if degrees < 0.:raise ValueError("If degrees is a single number, it must be positive.")@@ -232,7 +225,7 @@ def random_affine_generator(raise ValueError("scale values should be positive")# check shear range- shear_tmp: Optional[TupleFloat]+ shear_tmp: Optional[Tuple[float, float]]if shear is not None:if isinstance(shear, float):if shear < 0:@@ -251,7 +244,7 @@ def random_affine_generator(def random_rotation_generator(batch_size: int,- degrees: FloatUnionType,+ degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],interpolation: Union[str, int, Resample] = Resample.BILINEAR.name,same_on_batch: bool = False,align_corners: bool = False@@ -298,10 +291,10 @@ def _get_random_affine_params(batch_size: int,height: int,width: int,- degrees: TupleFloat,- translate: Optional[TupleFloat],- scales: Optional[TupleFloat],- shears: Optional[TupleFloat],+ degrees: Tuple[float, float],+ translate: Optional[Tuple[float, float]],+ scales: Optional[Tuple[float, float]],+ shears: Optional[Tuple[float, float]],resample: Union[str, int, Resample] = Resample.BILINEAR.name,same_on_batch: bool = False,align_corners: bool = False@@ -592,8 +585,8 @@ def center_crop_params_generator(def random_motion_blur_generator(batch_size: int,kernel_size: Union[int, Tuple[int, int]],- angle: UnionFloat,- direction: UnionFloat,+ angle: Union[float, Tuple[float, float]],+ direction: Union[float, Tuple[float, float]],border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,same_on_batch: bool = True) -> Dict[str, torch.Tensor]:@@ -624,8 +617,8 @@ def random_motion_blur_generator(def random_solarize_generator(batch_size: int,- thresholds: FloatUnionType = 0.1,- additions: FloatUnionType = 0.1,+ thresholds: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,+ additions: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,same_on_batch: bool = False) -> Dict[str, torch.Tensor]:r"""Generator random solarize parameters for a batch of images. For each pixel in the image less than threshold,diff --git a/kornia/augmentation/types.py b/kornia/augmentation/types.pydeleted file mode 100644index 2608d9bf8..000000000--- a/kornia/augmentation/types.py+++ /dev/null@@ -1,12 +0,0 @@-from typing import Callable, Tuple, Union, List, Optional, Dict, cast--import torch--TupleFloat = Tuple[float, float]-UnionFloat = Union[float, TupleFloat]-UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]-UnionShape = Union[Tuple, torch.Size]--FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]-IntUnionType = Union[torch.Tensor, int, Tuple[int, int], List[int]]-BoarderUnionType = Union[int, Tuple[int, int], Tuple[int, int, int, int]]diff --git a/kornia/augmentation/utils.py b/kornia/augmentation/utils.pyindex b726bc0f6..3e0e45bef 100644--- a/kornia/augmentation/utils.py+++ b/kornia/augmentation/utils.py@@ -3,15 +3,8 @@ from typing import Tuple, Union, Listimport torchfrom torch.distributions import Uniform-from kornia.utils.image import _to_bchw-from .types import (- FloatUnionType,- UnionType,- UnionShape-)--def _infer_batch_shape(input: UnionType) -> torch.Size:+def _infer_batch_shape(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:r"""Infer input shape. Input may be either (tensor,) or (tensor, transform_matrix)"""if isinstance(input, tuple):@@ -21,6 +14,16 @@ def _infer_batch_shape(input: UnionType) -> torch.Size:return tensor.shape+def _infer_batch_shape3d(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:+ r"""Infer input shape. Input may be either (tensor,) or (tensor, transform_matrix)+ """+ if isinstance(input, tuple):+ tensor = _transform_input3d(input[0])+ else:+ tensor = _transform_input3d(input)+ return tensor.shape++def _transform_input(input: torch.Tensor) -> torch.Tensor:r"""Reshape an input tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).Args:@@ -29,8 +32,44 @@ def _transform_input(input: torch.Tensor) -> torch.Tensor:Returns:torch.Tensor"""+ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if len(input.shape) not in [2, 3, 4]:+ raise ValueError(+ f"Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}")++ if len(input.shape) == 2:+ input = input.unsqueeze(0)++ if len(input.shape) == 3:+ input = input.unsqueeze(0)++ return input+++def _transform_input3d(input: torch.Tensor) -> torch.Tensor:+ r"""Reshape an input tensor to be (*, C, D, H, W). Accept either (D, H, W), (C, D, H, W) or (*, C, D, H, W).+ Args:+ input: torch.Tensor++ Returns:+ torch.Tensor+ """+ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if len(input.shape) not in [3, 4, 5]:+ raise ValueError(+ f"Input size must have a shape of either (D, H, W), (C, D, H, W) or (*, C, D, H, W). Got {input.shape}")++ if len(input.shape) == 3:+ input = input.unsqueeze(0)++ if len(input.shape) == 4:+ input = input.unsqueeze(0)- return _to_bchw(input)+ return inputdef _validate_input_dtype(input: torch.Tensor, accepted_dtypes: List) -> None:@@ -43,7 +82,7 @@ def _validate_input_dtype(input: torch.Tensor, accepted_dtypes: List) -> None:raise TypeError(f"Expected input of {accepted_dtypes}. Got {input.dtype}")-def _validate_shape(shape: UnionShape, required_shapes: List[str] = ["BCHW"]) -> None:+def _validate_shape(shape: Union[Tuple, torch.Size], required_shapes: List[str] = ["BCHW"]) -> None:r"""Check if the dtype of the input tensor is in the range of accepted_dtypesArgs:input: torch.Tensor@@ -88,8 +127,8 @@ def _adapted_uniform(shape: Union[Tuple, torch.Size], low, high, same_on_batch=Freturn dist.rsample(shape)-def _check_and_bound(factor: FloatUnionType, name: str, center: float = 0.,- bounds: Tuple[float, float] = (0, float('inf'))) -> torch.Tensor:+def _check_and_bound(factor: Union[torch.Tensor, float, Tuple[float, float], List[float]], name: str,+ center: float = 0., bounds: Tuple[float, float] = (0, float('inf'))) -> torch.Tensor:r"""Check inputs and compute the corresponding factor bounds"""factor_bound: torch.Tensor