π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Added VideoSequential for video augmentations (#817)
shijianjian32e4721ac88a
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rstindex 5d5d339d3..adccc47d8 100644--- a/docs/source/augmentation.rst+++ b/docs/source/augmentation.rst@@ -161,6 +161,8 @@ Transforms3DSet of operators to perform data augmentation on 3D image tensors and volumetric data.+.. autoclass:: Denormalize3D+.. autoclass:: Normalize3D.. autoclass:: RandomDepthicalFlip3D.. autoclass:: RandomHorizontalFlip3D.. autoclass:: RandomVerticalFlip3Ddiff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 8df934b79..6d1cac50a 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -19,7 +19,9 @@ from .augmentation import (RandomPosterize,RandomSharpness,RandomEqualize,- RandomMotionBlur+ RandomMotionBlur,+ Normalize,+ Denormalize,)from .augmentation3d import (RandomHorizontalFlip3D,@@ -31,15 +33,14 @@ from .augmentation3d import (RandomCrop3D,CenterCrop3D,RandomEqualize3D,- RandomPerspective3D+ RandomPerspective3D,)from .mix_augmentation import (RandomMixUp,RandomCutMix)-from kornia.enhance.normalize import (- Normalize,- Denormalize+from .container import (+ VideoSequential)__all__ = [@@ -66,6 +67,8 @@ __all__ = ["RandomMixUp","RandomCutMix","AugmentationBase3D",+ "Normalize3D",+ "Denormalize3D","RandomDepthicalFlip3D","RandomVerticalFlip3D","RandomHorizontalFlip3D",@@ -76,4 +79,5 @@ __all__ = ["RandomCrop3D","CenterCrop3D","RandomEqualize3D",+ "VideoSequential",]diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex 75d6049d2..a8292c7e0 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -9,6 +9,7 @@ from kornia.constants import Resample, BorderType, SamplePaddingfrom kornia.augmentation import AugmentationBase2Dfrom kornia.filters import GaussianBlur2dfrom kornia.utils import _extract_device_dtype+from kornia.enhance.normalize import normalize, denormalizefrom . import functional as Ffrom . import random_generator as rg@@ -883,6 +884,98 @@ class RandomResizedCrop(AugmentationBase2D):return F.apply_crop(input, params, self.flags)+class Normalize(AugmentationBase2D):+ r"""Normalize tensor images with mean and standard deviation.++ .. math::+ \text{input[channel] = (input[channel] - mean[channel]) / std[channel]}++ Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,++ Args:+ mean (torch.Tensor): Mean for each channel.+ std (torch.Tensor): Standard deviations for each channel.++ Return:+ torch.Tensor: Normalised tensor with same size as input :math:`(*, C, H, W)`.++ Examples:++ >>> norm = Normalize(mean=torch.zeros(1, 4), std=torch.ones(1, 4))+ >>> x = torch.rand(1, 4, 3, 3)+ >>> out = norm(x)+ >>> out.shape+ torch.Size([1, 4, 3, 3])+ """+ def __init__(+ self, mean: torch.Tensor, std: torch.Tensor,+ return_transform: bool = False, p: float = 1., keepdim: bool = False+ ) -> None:+ super(Normalize, self).__init__(p=p, return_transform=return_transform, same_on_batch=True,+ keepdim=keepdim)+ self.mean = mean+ self.std = std++ def __repr__(self) -> str:+ repr = f"mean={self.mean}, std={self.std}"+ return self.__class__.__name__ + f"({repr}, {super().__repr__()})"++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return dict()++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_intensity_transformation(input)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return normalize(input, self.mean, self.std)+++class Denormalize(AugmentationBase2D):+ r"""Denormalize tensor images with mean and standard deviation.++ .. math::+ \text{input[channel] = (input[channel] * mean[channel]) + std[channel]}++ Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,++ Args:+ mean (torch.Tensor): Mean for each channel.+ std (torch.Tensor): Standard deviations for each channel.++ Return:+ torch.Tensor: Denormalised tensor with same size as input :math:`(*, C, H, W)`.++ Examples:++ >>> norm = Denormalize(mean=torch.zeros(1, 4), std=torch.ones(1, 4))+ >>> x = torch.rand(1, 4, 3, 3)+ >>> out = norm(x)+ >>> out.shape+ torch.Size([1, 4, 3, 3])+ """+ def __init__(+ self, mean: torch.Tensor, std: torch.Tensor,+ return_transform: bool = False, p: float = 1., keepdim: bool = False+ ) -> None:+ super(Denormalize, self).__init__(p=p, return_transform=return_transform, same_on_batch=True,+ keepdim=keepdim)+ self.mean = mean+ self.std = std++ def __repr__(self) -> str:+ repr = f"mean={self.mean}, std={self.std}"+ return self.__class__.__name__ + f"({repr}, {super().__repr__()})"++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return dict()++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_intensity_transformation(input)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return denormalize(input, self.mean, self.std)++class RandomMotionBlur(AugmentationBase2D):r"""Perform motion blur on 2D images (4D tensor).diff --git a/kornia/augmentation/container/__init__.py b/kornia/augmentation/container/__init__.pynew file mode 100644index 000000000..8fd46ab1d--- /dev/null+++ b/kornia/augmentation/container/__init__.py@@ -0,0 +1 @@+from .video import VideoSequentialdiff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pynew file mode 100644index 000000000..f9a9d6074--- /dev/null+++ b/kornia/augmentation/container/video.py@@ -0,0 +1,132 @@+from typing import List, Tuple, Union, cast++import torch+import torch.nn as nn++import kornia+from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase+from kornia.augmentation import ColorJitter+++class VideoSequential(nn.Sequential):+ r"""VideoSequential for processing 5-dim video data like (B, T, C, H, W) and (B, C, T, H, W).++ `VideoSequential` is used to replace `nn.Sequential` for processing video data augmentations.+ By default, `VideoSequential` enabled `same_on_frame` to make sure the same augmentations happen+ across temporal dimension. Meanwhile, it will not affect other augmentation behaviours like the+ settings on `same_on_batch`, etc.++ Args:+ *args (_AugmentationBase): a list of augmentation module.+ data_format (str): only BCTHW and BTCHW are supported. Default: BTCHW.+ same_on_frame (bool): apply the same transformation across the channel per frame. Default: True.++ Example:+ If set `same_on_frame` to True, we would expect the same augmentation has been applied to each+ timeframe.++ >>> input = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1)+ >>> aug_list = VideoSequential(+ ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.RandomAffine(360, p=1.0),+ ... data_format="BCTHW",+ ... same_on_frame=True)+ >>> output = aug_list(input)+ >>> (output[0, :, 0] == output[0, :, 1]).all()+ tensor(True)+ >>> (output[0, :, 1] == output[0, :, 2]).all()+ tensor(True)+ >>> (output[0, :, 2] == output[0, :, 3]).all()+ tensor(True)++ If set `same_on_frame` to False:++ >>> aug_list = VideoSequential(+ ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.RandomAffine(360, p=1.0),+ ... data_format="BCTHW",+ ... same_on_frame=False)+ >>> output = aug_list(input)+ >>> output.shape+ torch.Size([2, 3, 4, 5, 6])+ >>> (output[0, :, 0] == output[0, :, 1]).all()+ tensor(False)+ """++ def __init__(self, *args: _AugmentationBase, data_format="BTCHW", same_on_frame: bool = True) -> None:+ super(VideoSequential, self).__init__(*args)+ self.same_on_frame = same_on_frame+ for aug in args:+ if isinstance(aug, MixAugmentationBase):+ raise NotImplementedError(f"MixAugmentations are not supported at this moment. Got {aug}.")+ self.data_format = data_format.upper()+ assert self.data_format in ["BCTHW", "BTCHW"], \+ f"Only `BCTHW` and `BTCHW` are supported. Got `{data_format}`."+ self._temporal_channel: int+ if self.data_format == "BCTHW":+ self._temporal_channel = 2+ elif self.data_format == "BTCHW":+ self._temporal_channel = 1++ def __infer_channel_exclusive_batch_shape__(self, input: torch.Tensor) -> torch.Size:+ batch_shape: torch.Size = input.shape+ # Fix mypy complains: error: Incompatible return value type (got "Tuple[int, ...]", expected "Size")+ return cast(torch.Size, batch_shape[:self._temporal_channel] + batch_shape[self._temporal_channel + 1:])++ def __repeat_param_across_channels__(self, param: torch.Tensor, frame_num: int) -> torch.Tensor:+ """Repeat parameters across channels.++ The input is shaped as (B, ...), while to output (B * same_on_frame, ...), which+ to guarentee that the same transformation would happen for each frame.++ (B1, B2, ..., Bn) => (B1, ... B1, B2, ..., B2, ..., Bn, ..., Bn)+ | ch_size | | ch_size | ..., | ch_size |+ """+ repeated = param[:, None, ...].repeat(1, frame_num, *([1] * len(param.shape[1:])))+ return repeated.reshape(-1, *list(param.shape[1:])) # type: ignore++ def _input_shape_convert_in(self, input: torch.Tensor) -> torch.Tensor:+ # Convert any shape to (B, T, C, H, W)+ if self.data_format == "BCTHW":+ # Convert (B, C, T, H, W) to (B, T, C, H, W)+ input = input.transpose(1, 2)+ if self.data_format == "BTCHW":+ pass+ return input++ def _input_shape_convert_back(self, input: torch.Tensor, frame_num: int) -> torch.Tensor:+ input = input.view(-1, frame_num, *input.shape[1:])+ if self.data_format == "BCTHW":+ input = input.transpose(1, 2)+ if self.data_format == "BTCHW":+ pass+ return input++ def forward(self, input: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:+ assert len(input.shape) == 5, f"Input must be a 5-dim tensor. Got {input.shape}."+ # Size of T+ frame_num = input.size(self._temporal_channel)+ # Got param generation shape to (B, C, H, W). Ignoring T.+ batch_shape = self.__infer_channel_exclusive_batch_shape__(input)+ input = self._input_shape_convert_in(input)+ _original_shape = input.shape+ input = input.reshape(-1, *batch_shape[1:])+ if not self.same_on_frame:+ # Overwrite param generation shape to (B * T, C, H, W).+ batch_shape = input.shape+ for aug in self.children():+ aug = cast(_AugmentationBase, aug)+ param = aug.__forward_parameters__(batch_shape, aug.p, aug.p_batch, aug.same_on_batch)+ if self.same_on_frame:+ for k, v in param.items():+ # TODO: revise colorjitter order param in the future to align the standard.+ if not (k == "order" and isinstance(aug, ColorJitter)):+ param.update({k: self.__repeat_param_across_channels__(v, frame_num)})+ input = aug(input, params=param)++ if isinstance(input, (tuple, list)):+ input[0] = self._input_shape_convert_back(input[0], frame_num)+ else:+ input = self._input_shape_convert_back(input, frame_num)++ return inputdiff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex 2418be824..41024e24b 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -28,8 +28,8 @@ class Normalize(nn.Module):std (Union[torch.Tensor, float]): Standard deviations for each channel.Shape:- - Input: Image tensor of size :math:`(*, C, H, W)`.- - Output: Normalised tensor with same size as input :math:`(*, C, H, W)`.+ - Input: Image tensor of size :math:`(*, C, ...)`.+ - Output: Normalised tensor with same size as input :math:`(*, C, ...)`.Examples:>>> x = torch.rand(1, 4, 3, 3)@@ -71,12 +71,12 @@ def normalize(Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,Args:- data (torch.Tensor): Image tensor of size :math:`(*, C, H, W)`.+ data (torch.Tensor): Image tensor of size :math:`(*, C, ...)`.mean (Union[torch.Tensor, float]): Mean for each channel.std (Union[torch.Tensor, float]): Standard deviations for each channel.Return:- torch.Tensor: Normalised tensor with same size as input :math:`(*, C, H, W)`.+ torch.Tensor: Normalised tensor with same size as input :math:`(*, C, ...)`.Examples:>>> x = torch.rand(1, 4, 3, 3)@@ -91,11 +91,13 @@ def normalize(>>> out.shapetorch.Size([1, 4, 3, 3])"""+ shape = data.shape+if isinstance(mean, float):- mean = torch.tensor([mean]) # prevent 0 sized tensors+ mean = torch.tensor([mean] * shape[1], device=data.device, dtype=data.dtype)if isinstance(std, float):- std = torch.tensor([std]) # prevent 0 sized tensors+ std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype)if not isinstance(data, torch.Tensor):raise TypeError("data should be a tensor. Got {}".format(type(data)))@@ -109,22 +111,24 @@ def normalize(# Allow broadcast on channel dimensionif mean.shape and mean.shape[0] != 1:if mean.shape[0] != data.shape[-3] and mean.shape[:2] != data.shape[:2]:- raise ValueError("mean length and number of channels do not match")+ raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")# Allow broadcast on channel dimensionif std.shape and std.shape[0] != 1:if std.shape[0] != data.shape[-3] and std.shape[:2] != data.shape[:2]:- raise ValueError("std length and number of channels do not match")+ raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")- if mean.shape:- mean = mean[..., :, None, None].to(data.device)+ mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)+ std = torch.as_tensor(std, device=data.device, dtype=data.dtype)+ if mean.shape:+ mean = mean[..., :, None]if std.shape:- std = std[..., :, None, None].to(data.device)+ std = std[..., :, None]- out: torch.Tensor = (data - mean) / std+ out: torch.Tensor = (data.view(shape[0], shape[1], -1) - mean) / std- return out+ return out.view(shape)class Denormalize(nn.Module):@@ -140,8 +144,8 @@ class Denormalize(nn.Module):std (Union[torch.Tensor, float]): Standard deviations for each channel.Shape:- - Input: Image tensor of size :math:`(*, C, H, W)`.- - Output: Denormalised tensor with same size as input :math:`(*, C, H, W)`.+ - Input: Image tensor of size :math:`(*, C, ...)`.+ - Output: Denormalised tensor with same size as input :math:`(*, C, ...)`.Examples:>>> x = torch.rand(1, 4, 3, 3)@@ -149,12 +153,12 @@ class Denormalize(nn.Module):>>> out.shapetorch.Size([1, 4, 3, 3])- >>> x = torch.rand(1, 4, 3, 3)+ >>> x = torch.rand(1, 4, 3, 3, 3)>>> mean = torch.zeros(1, 4)>>> std = 255. * torch.ones(1, 4)>>> out = Denormalize(mean, std)(x)>>> out.shape- torch.Size([1, 4, 3, 3])+ torch.Size([1, 4, 3, 3, 3])"""def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:@@ -183,12 +187,12 @@ def denormalize(Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,Args:- input (torch.Tensor): Image tensor of size :math:`(*, C, H, W)`.+ input (torch.Tensor): Image tensor of size :math:`(*, C, ...)`.mean (Union[torch.Tensor, float]): Mean for each channel.std (Union[torch.Tensor, float]): Standard deviations for each channel.Return:- torch.Tensor: Denormalised tensor with same size as input :math:`(*, C, H, W)`.+ torch.Tensor: Denormalised tensor with same size as input :math:`(*, C, ...)`.Examples:>>> x = torch.rand(1, 4, 3, 3)@@ -196,19 +200,20 @@ def denormalize(>>> out.shapetorch.Size([1, 4, 3, 3])- >>> x = torch.rand(1, 4, 3, 3)+ >>> x = torch.rand(1, 4, 3, 3, 3)>>> mean = torch.zeros(1, 4)>>> std = 255. * torch.ones(1, 4)>>> out = denormalize(x, mean, std)>>> out.shape- torch.Size([1, 4, 3, 3])+ torch.Size([1, 4, 3, 3, 3])"""+ shape = data.shapeif isinstance(mean, float):- mean = torch.tensor([mean]) # prevent 0 sized tensors+ mean = torch.tensor([mean] * shape[1], device=data.device, dtype=data.dtype)if isinstance(std, float):- std = torch.tensor([std]) # prevent 0 sized tensors+ std = torch.tensor([std] * shape[1], device=data.device, dtype=data.dtype)if not isinstance(data, torch.Tensor):raise TypeError("data should be a tensor. Got {}".format(type(data)))@@ -222,21 +227,24 @@ def denormalize(# Allow broadcast on channel dimensionif mean.shape and mean.shape[0] != 1:if mean.shape[0] != data.shape[-3] and mean.shape[:2] != data.shape[:2]:- raise ValueError("mean length and number of channels do not match")+ raise ValueError(f"mean length and number of channels do not match. Got {mean.shape} and {data.shape}.")# Allow broadcast on channel dimensionif std.shape and std.shape[0] != 1:if std.shape[0] != data.shape[-3] and std.shape[:2] != data.shape[:2]:- raise ValueError("std length and number of channels do not match")+ raise ValueError(f"std length and number of channels do not match. Got {std.shape} and {data.shape}.")++ mean = torch.as_tensor(mean, device=data.device, dtype=data.dtype)+ std = torch.as_tensor(std, device=data.device, dtype=data.dtype)if mean.shape:- mean = mean[..., :, None, None].to(data.device)+ mean = mean[..., :, None]if std.shape:- std = std[..., :, None, None].to(data.device)+ std = std[..., :, None]- out: torch.Tensor = (data * std) + mean+ out: torch.Tensor = (data.view(shape[0], shape[1], -1) * std) + mean- return out+ return out.view(shape)def normalize_min_max(x: torch.Tensor, min_val: float = 0., max_val: float = 1., eps: float = 1e-6) -> torch.Tensor:@@ -250,13 +258,13 @@ def normalize_min_max(x: torch.Tensor, min_val: float = 0., max_val: float = 1.,where :math:`a` is :math:`\text{min_val}` and :math:`b` is :math:`\text{max_val}`.Args:- x (torch.Tensor): The image tensor to be normalised with shape :math:`(B, C, H, W)`.+ x (torch.Tensor): The image tensor to be normalised with shape :math:`(B, C, ...)`.min_val (float): The minimum value for the new range. Default: 0.max_val (float): The maximum value for the new range. Default: 1.eps (float): Float number to avoid zero division. Default: 1e-6.Returns:- torch.Tensor: The normalised image tensor with same shape as input :math:`(B, C, H, W)`.+ torch.Tensor: The normalised image tensor with same shape as input :math:`(B, C, ...)`.Example:>>> x = torch.rand(1, 5, 3, 3)@@ -275,15 +283,16 @@ def normalize_min_max(x: torch.Tensor, min_val: float = 0., max_val: float = 1.,if not isinstance(max_val, float):raise TypeError(f"'b' should be a float. Got: {type(max_val)}.")- if len(x.shape) != 4:- raise ValueError(f"Input shape must be a 4d tensor. Got: {x.shape}.")+ if len(x.shape) < 3:+ raise ValueError(f"Input shape must be at least a 3d tensor. Got: {x.shape}.")- B, C, H, W = x.shape+ shape = x.shape+ B, C = shape[0], shape[1]- x_min: torch.Tensor = x.view(B, C, -1).min(-1)[0].view(B, C, 1, 1)- x_max: torch.Tensor = x.view(B, C, -1).max(-1)[0].view(B, C, 1, 1)+ x_min: torch.Tensor = x.view(B, C, -1).min(-1)[0].view(B, C, 1)+ x_max: torch.Tensor = x.view(B, C, -1).max(-1)[0].view(B, C, 1)x_out: torch.Tensor = (- (max_val - min_val) * (x - x_min) / (x_max - x_min + eps) + min_val+ (max_val - min_val) * (x.view(B, C, -1) - x_min) / (x_max - x_min + eps) + min_val)- return x_out.expand_as(x)+ return x_out.view(shape)diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex 88b387aee..d65bbd3f4 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -22,7 +22,9 @@ from kornia.augmentation import (RandomGrayscale,RandomRotation,RandomCrop,- RandomResizedCrop+ RandomResizedCrop,+ Normalize,+ Denormalize)@@ -2284,3 +2286,119 @@ class TestGaussianBlur:f = GaussianBlur((3, 3), (0.1, 2.0), p=1.)repr = "GaussianBlur(p=1.0, p_batch=1.0, same_on_batch=False, return_transform=False)"assert str(f) == repr+++class TestNormalize:+ # TODO: improve and implement more meaningful smoke tests e.g check for a consistent+ # return values such a torch.Tensor variable.+ @pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")+ def test_smoke(self, device, dtype):+ f = Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]))+ repr = ("Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, "+ "same_on_batch=False, return_transform=False)")+ assert str(f) == repr++ def test_random_normalize(self, device, dtype):+ f = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1., return_transform=True)+ f1 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0., return_transform=True)+ f2 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1.)+ f3 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0.)++ inputs = torch.arange(0., 16., step=1, device=device, dtype=dtype).reshape(1, 4, 4)++ expected = (inputs - 1) * 2++ identity = kornia.eye_like(3, expected)++ assert_allclose(f(inputs)[0], expected, rtol=1e-4, atol=1e-4)+ assert_allclose(f(inputs)[1], identity, rtol=1e-4, atol=1e-4)+ assert_allclose(f1(inputs)[0], inputs, rtol=1e-4, atol=1e-4)+ assert_allclose(f1(inputs)[1], identity, rtol=1e-4, atol=1e-4)+ assert_allclose(f2(inputs), expected, rtol=1e-4, atol=1e-4)+ assert_allclose(f3(inputs), inputs, rtol=1e-4, atol=1e-4)++ def test_batch_random_normalize(self, device, dtype):+ f = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1., return_transform=True)+ f1 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0., return_transform=True)+ f2 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1.)+ f3 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0.)++ inputs = torch.arange(0., 16. * 2, step=1, device=device, dtype=dtype).reshape(2, 1, 4, 4)++ expected = (inputs - 1) * 2++ identity = kornia.eye_like(3, expected)++ assert_allclose(f(inputs)[0], expected, rtol=1e-4, atol=1e-4)+ assert_allclose(f(inputs)[1], identity, rtol=1e-4, atol=1e-4)+ assert_allclose(f1(inputs)[0], inputs, rtol=1e-4, atol=1e-4)+ assert_allclose(f1(inputs)[1], identity, rtol=1e-4, atol=1e-4)+ assert_allclose(f2(inputs), expected, rtol=1e-4, atol=1e-4)+ assert_allclose(f3(inputs), inputs, rtol=1e-4, atol=1e-4)++ def test_gradcheck(self, device, dtype):++ torch.manual_seed(0) # for random reproductibility++ input = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3+ input = utils.tensor_to_gradcheck_var(input) # to var+ assert gradcheck(+ Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1.), (input,), raise_exception=True)+++class TestDenormalize:+ # TODO: improve and implement more meaningful smoke tests e.g check for a consistent+ # return values such a torch.Tensor variable.+ @pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")+ def test_smoke(self, device, dtype):+ f = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]))+ repr = ("Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, "+ "same_on_batch=False, return_transform=False)")+ assert str(f) == repr++ def test_random_denormalize(self, device, dtype):+ f = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1., return_transform=True)+ f1 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0., return_transform=True)+ f2 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1.)+ f3 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0.)++ inputs = torch.arange(0., 16., step=1, device=device, dtype=dtype).reshape(1, 4, 4)++ expected = inputs / 2 + 1++ identity = kornia.eye_like(3, expected)++ assert_allclose(f(inputs)[0], expected, rtol=1e-4, atol=1e-4)+ assert_allclose(f(inputs)[1], identity, rtol=1e-4, atol=1e-4)+ assert_allclose(f1(inputs)[0], inputs, rtol=1e-4, atol=1e-4)+ assert_allclose(f1(inputs)[1], identity, rtol=1e-4, atol=1e-4)+ assert_allclose(f2(inputs), expected, rtol=1e-4, atol=1e-4)+ assert_allclose(f3(inputs), inputs, rtol=1e-4, atol=1e-4)++ def test_batch_random_denormalize(self, device, dtype):+ f = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1., return_transform=True)+ f1 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0., return_transform=True)+ f2 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1.)+ f3 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0.)++ inputs = torch.arange(0., 16. * 2, step=1, device=device, dtype=dtype).reshape(2, 1, 4, 4)++ expected = inputs / 2 + 1++ identity = kornia.eye_like(3, expected)++ assert_allclose(f(inputs)[0], expected, rtol=1e-4, atol=1e-4)+ assert_allclose(f(inputs)[1], identity, rtol=1e-4, atol=1e-4)+ assert_allclose(f1(inputs)[0], inputs, rtol=1e-4, atol=1e-4)+ assert_allclose(f1(inputs)[1], identity, rtol=1e-4, atol=1e-4)+ assert_allclose(f2(inputs), expected, rtol=1e-4, atol=1e-4)+ assert_allclose(f3(inputs), inputs, rtol=1e-4, atol=1e-4)++ def test_gradcheck(self, device, dtype):++ torch.manual_seed(0) # for random reproductibility++ input = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3+ input = utils.tensor_to_gradcheck_var(input) # to var+ assert gradcheck(+ Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1.), (input,), raise_exception=True)diff --git a/test/augmentation/test_augmentation_3d.py b/test/augmentation/test_augmentation_3d.pyindex 26e9f8aca..65c0ba854 100644--- a/test/augmentation/test_augmentation_3d.py+++ b/test/augmentation/test_augmentation_3d.py@@ -18,7 +18,7 @@ from kornia.augmentation import (RandomRotation3D,RandomCrop3D,CenterCrop3D,- RandomEqualize3D+ RandomEqualize3D,)diff --git a/test/augmentation/test_backward.py b/test/augmentation/test_backward.pyindex f991e80e2..175950cf8 100644--- a/test/augmentation/test_backward.py+++ b/test/augmentation/test_backward.py@@ -78,7 +78,7 @@ class TestRandomAffineBackward:[0.1, 0.2], [0.1, 0.2, 0.3, 0.4], torch.tensor([0.1, 0.2]), torch.tensor([0.1, 0.2, 0.3, 0.4])])@pytest.mark.parametrize("shear", [[10., 20.], [10., 20., 30., 40.], torch.tensor([10, 20]), torch.tensor([10, 20, 30, 40])])- @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.@pytest.mark.parametrize("align_corners", [True, False])@pytest.mark.parametrize("return_transform", [True, False])@pytest.mark.parametrize("same_on_batch", [True, False])@@ -165,7 +165,7 @@ class TestRandomAffineBackward:class TestRandomRotationBackward:@pytest.mark.parametrize("degrees", [10, [10., 20.], (10, 20), torch.tensor(10.), torch.tensor([10, 20])])- @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.@pytest.mark.parametrize("align_corners", [True, False])@pytest.mark.parametrize("return_transform", [True, False])@pytest.mark.parametrize("same_on_batch", [True, False])@@ -209,7 +209,7 @@ class TestRandomRotationBackward:class TestRandomPerspectiveBackward:@pytest.mark.parametrize("distortion_scale", [0.5, torch.tensor(0.5)])- @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.@pytest.mark.parametrize("align_corners", [True, False])@pytest.mark.parametrize("return_transform", [True, False])@pytest.mark.parametrize("same_on_batch", [True, False])@@ -255,7 +255,7 @@ class TestRandomMotionBlurBackward:@pytest.mark.parametrize("angle", [20., torch.tensor([-20., 20.])])@pytest.mark.parametrize("direction", [[-0.5, 0.5], torch.tensor([-0.5, 0.5])])@pytest.mark.parametrize("border_type", ['constant', 'reflect', 'replicate', 'circular'])- @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.@pytest.mark.parametrize("return_transform", [True, False])@pytest.mark.parametrize("same_on_batch", [True, False])def test_param(self, angle, direction, border_type, resample, return_transform, same_on_batch, device, dtype):@@ -343,7 +343,7 @@ class TestRandomResizedCropBackward:@pytest.mark.skip("Param gen is probably breaking grads.")@pytest.mark.parametrize("scale", [[0.08, 1.], torch.tensor([0.08, 1.])])@pytest.mark.parametrize("ratio", [[3. / 4., 4. / 3.], torch.tensor([3. / 4., 4. / 3.])])- @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.@pytest.mark.parametrize("align_corners", [True, False])@pytest.mark.parametrize("return_transform", [True, False])@pytest.mark.parametrize("same_on_batch", [True, False])diff --git a/test/augmentation/test_backward_3d.py b/test/augmentation/test_backward_3d.pyindex 5c4aecabc..967c7880c 100644--- a/test/augmentation/test_backward_3d.py+++ b/test/augmentation/test_backward_3d.py@@ -27,7 +27,7 @@ class TestRandomAffine3DBackward:[(-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.)],torch.tensor(10), torch.tensor([10, 20]), torch.tensor([10., 20., 30., 40., 50., 60.]),torch.tensor([(-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.)])])- @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.@pytest.mark.parametrize("align_corners", [True, False])@pytest.mark.parametrize("return_transform", [True, False])@pytest.mark.parametrize("same_on_batch", [True, False])@@ -117,7 +117,7 @@ class TestRandomRotation3DBackward:10, [10., 20.], [10., 20., 30.], [(10, 20), (10, 20), (10, 20)],torch.tensor(10.), torch.tensor([10., 20.]), torch.tensor([10, 20, 30]),torch.tensor([(10, 20), (10, 20), (10, 20)])])- @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.@pytest.mark.parametrize("align_corners", [True, False])@pytest.mark.parametrize("return_transform", [True, False])@pytest.mark.parametrize("same_on_batch", [True, False])@@ -161,7 +161,7 @@ class TestRandomRotation3DBackward:class TestRandomPerspective3DBackward:@pytest.mark.parametrize("distortion_scale", [0.5, torch.tensor(0.5)])- @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.@pytest.mark.parametrize("align_corners", [True, False])@pytest.mark.parametrize("return_transform", [True, False])@pytest.mark.parametrize("same_on_batch", [True, False])@@ -208,7 +208,7 @@ class TestRandomMotionBlur3DBackward:@pytest.mark.parametrize("direction", [[-0.5, 0.5], torch.tensor([-0.5, 0.5])])# 'reflect' is not implemented by torch.@pytest.mark.parametrize("border_type", ['constant', 'replicate', 'circular'])- @pytest.mark.parametrize("resample", ['bilinear', 'nearest'])+ @pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.@pytest.mark.parametrize("return_transform", [True, False])@pytest.mark.parametrize("same_on_batch", [True, False])def test_param(self, angle, direction, border_type, resample, return_transform, same_on_batch, device, dtype):diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.pynew file mode 100644index 000000000..02015af12--- /dev/null+++ b/test/augmentation/test_container.py@@ -0,0 +1,127 @@+import torch+import pytest++import kornia.augmentation as K+++class TestVideoSequential:++ @pytest.mark.parametrize('shape', [(3, 4), (2, 3, 4), (2, 3, 5, 6), (2, 3, 4, 5, 6, 7)])+ @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])+ def test_exception(self, shape, data_format, device, dtype):+ aug_list = K.VideoSequential(+ K.ColorJitter(0.1, 0.1, 0.1, 0.1), data_format=data_format, same_on_frame=True)+ with pytest.raises(AssertionError):+ input = torch.randn(*shape, device=device, dtype=dtype)+ output = aug_list(input)++ @pytest.mark.parametrize('augmentation', [+ K.RandomAffine(360, p=1.),+ K.CenterCrop((3, 3), p=1.),+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.),+ K.RandomCrop((5, 5), p=1.),+ K.RandomErasing(p=1.),+ K.RandomGrayscale(p=1.),+ K.RandomHorizontalFlip(p=1.),+ K.RandomVerticalFlip(p=1.),+ K.RandomPerspective(p=1.),+ K.RandomResizedCrop((5, 5), p=1.),+ K.RandomRotation(360., p=1.),+ K.RandomSolarize(p=1.),+ K.RandomPosterize(p=1.),+ K.RandomSharpness(p=1.),+ K.RandomEqualize(p=1.),+ K.RandomMotionBlur(3, 35., 0.5, p=1.),+ K.Normalize(torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]), p=1.),+ K.Denormalize(torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]), p=1.),+ ])+ @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])+ def test_augmentation(self, augmentation, data_format, device, dtype):+ input = torch.randint(255, (1, 3, 3, 5, 6), device=device, dtype=dtype).repeat(2, 1, 1, 1, 1) / 255.+ torch.manual_seed(21)+ aug_list = K.VideoSequential(augmentation, data_format=data_format, same_on_frame=True)+ output = aug_list(input)++ @pytest.mark.parametrize('augmentations', [+ [+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=.5),+ K.RandomAffine(360, p=.5),+ ]+ ])+ @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])+ def test_p_half(self, augmentations, data_format, device, dtype):+ input = torch.randn(1, 3, 3, 5, 6, device=device, dtype=dtype).repeat(2, 1, 1, 1, 1)+ torch.manual_seed(21)+ aug_list = K.VideoSequential(*augmentations, data_format=data_format, same_on_frame=True)+ output = aug_list(input)++ assert not (output[0] == input[0]).all()+ assert (output[1] == input[1]).all()++ @pytest.mark.parametrize('augmentations', [+ [+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.),+ K.RandomAffine(360, p=1.),+ ],+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)],+ [K.RandomAffine(360, p=1.)],+ [+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.),+ K.RandomAffine(360, p=0.),+ ],+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.)],+ [K.RandomAffine(360, p=0.)],+ ])+ @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])+ def test_same_on_frame(self, augmentations, data_format, device, dtype):+ aug_list = K.VideoSequential(*augmentations, data_format=data_format, same_on_frame=True)++ if data_format == 'BCTHW':+ input = torch.randn(2, 3, 1, 5, 6, device=device, dtype=dtype).repeat(1, 1, 4, 1, 1)+ output = aug_list(input)+ assert (output[:, :, 0] == output[:, :, 1]).all()+ assert (output[:, :, 1] == output[:, :, 2]).all()+ assert (output[:, :, 2] == output[:, :, 3]).all()+ if data_format == 'BTCHW':+ input = torch.randn(2, 1, 3, 5, 6, device=device, dtype=dtype).repeat(1, 4, 1, 1, 1)+ output = aug_list(input)+ assert (output[:, 0] == output[:, 1]).all()+ assert (output[:, 1] == output[:, 2]).all()+ assert (output[:, 2] == output[:, 3]).all()++ @pytest.mark.parametrize('augmentations', [+ [K.RandomAffine(360, p=1.)],+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)]+ ])+ @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])+ def test_against_sequential(self, augmentations, data_format, device, dtype):+ aug_list_1 = K.VideoSequential(*augmentations, data_format=data_format, same_on_frame=False)+ aug_list_2 = torch.nn.Sequential(*augmentations)++ if data_format == 'BCTHW':+ input = torch.randn(2, 3, 1, 5, 6, device=device, dtype=dtype).repeat(1, 1, 4, 1, 1)+ if data_format == 'BTCHW':+ input = torch.randn(2, 1, 3, 5, 6, device=device, dtype=dtype).repeat(1, 4, 1, 1, 1)++ torch.manual_seed(0)+ output_1 = aug_list_1(input)+ param_1 = list(aug_list_1.children())[0]._params++ torch.manual_seed(0)+ if data_format == 'BCTHW':+ input = input.transpose(1, 2)+ output_2 = aug_list_2(input.reshape(-1, 3, 5, 6))+ param_2 = list(aug_list_2.children())[0]._params+ output_2 = output_2.view(2, 4, 3, 5, 6)+ if data_format == 'BCTHW':+ output_2 = output_2.transpose(1, 2)+ assert (output_1 == output_2).all()++ @pytest.mark.jit+ @pytest.mark.skip(reason="turn off due to Union Type")+ def test_jit(self, device, dtype):+ B, C, D, H, W = 2, 3, 5, 4, 4+ img = torch.ones(B, C, D, H, W, device=device, dtype=dtype)+ op = K.VideoSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1), same_on_frame=True)+ op_jit = torch.jit.script(op)+ assert_allclose(op(img), op_jit(img))diff --git a/test/enhance/test_normalize.py b/test/enhance/test_normalize.pyindex 54718aac2..246636323 100644--- a/test/enhance/test_normalize.py+++ b/test/enhance/test_normalize.py@@ -247,9 +247,6 @@ class TestNormalizeMinMax(BaseTester):with pytest.raises(TypeError):assert kornia.normalize_min_max(0.)- with pytest.raises(ValueError):- assert kornia.normalize_min_max(x[0])-with pytest.raises(TypeError):assert kornia.normalize_min_max(x, '', '')