🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add pillow_like option for ColorJitter to match torchvision. (#1611)
Julien DENIZEa308e1621e64
diff --git a/docs/generate_example_images.py b/docs/generate_example_images.pyindex 4aa9aadd4..197efd4ca 100644--- a/docs/generate_example_images.py+++ b/docs/generate_example_images.py@@ -55,7 +55,7 @@ def main():mod = importlib.import_module("kornia.augmentation")augmentations_list: dict = {"CenterCrop": ((184, 184), 1, 2018),- "ColorJitter": ((0.3, 0.3, 0.3, 0.3), 2, 2018),+ "ColorJiggle": ((0.3, 0.3, 0.3, 0.3), 2, 2018),"RandomAffine": (((-15.0, 20.0), (0.1, 0.1), (0.7, 1.3), 20), 2, 2019),"RandomBoxBlur": (((7, 7),), 1, 2020),"RandomCrop": ((img1.shape[-2:], (50, 50)), 2, 2020),diff --git a/docs/source/applications/image_augmentations.rst b/docs/source/applications/image_augmentations.rstindex 458006b5a..326c096c1 100644--- a/docs/source/applications/image_augmentations.rst+++ b/docs/source/applications/image_augmentations.rst@@ -34,7 +34,7 @@ However, we provide the following guide to migrate kornia <-> torchvision. Pleastransform = nn.Sequential(K.RandomAffine(360),- K.ColorJitter(0.2, 0.3, 0.2, 0.3)+ K.ColorJiggle(0.2, 0.3, 0.2, 0.3))@@ -51,7 +51,7 @@ for automating the processing of masks, bounding boxes, and keypoints.import kornia.augmentation as Kaug = K.AugmentationSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomAffine(360, [0.1, 0.1], [0.7, 1.2], [30., 50.], p=1.0),K.RandomPerspective(0.5, p=1.0),data_keys=["input", "bbox", "keypoints", "mask"], # Just to define the future input here.@@ -109,7 +109,7 @@ To enable those behaviour, you may simply set the flags to True.self.aff = K.RandomAffine(360, return_transform=True, same_on_batch=True)- self.jit = K.ColorJitter(0.2, 0.3, 0.2, 0.3, same_on_batch=True)+ self.jit = K.ColorJiggle(0.2, 0.3, 0.2, 0.3, same_on_batch=True)def forward(self, input):input, transform = self.aff(input)@@ -126,7 +126,7 @@ Example for semantic segmentation using low-level randomness control:def __init__(self) -> None:super(MyAugmentationPipeline, self).__init__()self.aff = K.RandomAffine(360)- self.jit = K.ColorJitter(0.2, 0.3, 0.2, 0.3)+ self.jit = K.ColorJiggle(0.2, 0.3, 0.2, 0.3)def forward(self, input, mask):assert input.shape == mask.shape,diff --git a/docs/source/augmentation.container.rst b/docs/source/augmentation.container.rstindex c16cef033..228418aaa 100644--- a/docs/source/augmentation.container.rst+++ b/docs/source/augmentation.container.rst@@ -56,7 +56,7 @@ Currently, `VideoSequential` supports data format like :math:`(B, C, T, H, W)` atransform = K.VideoSequential(K.RandomAffine(360),- K.ColorJitter(0.2, 0.3, 0.2, 0.3),+ K.ColorJiggle(0.2, 0.3, 0.2, 0.3),data_format="BCTHW",same_on_frame=True)diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex 8362c1767..476cbe662 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -12,6 +12,7 @@ Intensity~~~~~~~~~.. autoclass:: RandomPlanckianJitter+.. autoclass:: ColorJiggle.. autoclass:: ColorJitter.. autoclass:: RandomBoxBlur.. autoclass:: RandomChannelShufflediff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rstindex 6708bb7a9..b2c47b1a9 100644--- a/docs/source/augmentation.rst+++ b/docs/source/augmentation.rst@@ -29,7 +29,7 @@ Benchmark+================================+=================+=================+=================+=================+=================+| RandomPerspective | 4.88±1.82 | 4.68±3.60 | 4.74±2.84 | 0.37±2.67 | 0.20±27.00 |+--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+- | ColorJitter | 4.40±2.88 | 3.58±3.66 | 4.14±3.85 | 0.90±24.68 | 0.83±12.96 |+ | ColorJiggle | 4.40±2.88 | 3.58±3.66 | 4.14±3.85 | 0.90±24.68 | 0.83±12.96 |+--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+| RandomAffine | 3.12±5.80 | 2.43±7.11 | 3.01±7.80 | 0.30±4.39 | 0.18±6.30 |+--------------------------------+-----------------+-----------------+-----------------+-----------------+-----------------+diff --git a/docs/source/get-started/training.rst b/docs/source/get-started/training.rstindex 63f756cc0..876bf9eda 100644--- a/docs/source/get-started/training.rst+++ b/docs/source/get-started/training.rst@@ -190,7 +190,7 @@ the debugging and experimentation experience.K.augmentation.RandomVerticalFlip(p=0.75),K.augmentation.RandomAffine(degrees=10.),K.augmentation.PatchSequential(- K.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.8),+ K.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.8),grid_size=(2, 2), # cifar-10 is 32x32 and vit is patch 16patchwise_apply=False,),diff --git a/kornia/augmentation/README.md b/kornia/augmentation/README.mdindex 93d2eb6a8..1a633652f 100644--- a/kornia/augmentation/README.md+++ b/kornia/augmentation/README.md@@ -29,7 +29,7 @@| | 2D | 3D || ------------ | ----------- | ------------ |-| ColorJitter | ✅ | ❌ |+| ColorJiggle | ✅ | ❌ || RandomGrayscale | ✅ | ❌ || RandomSolarize | ✅ | ❌ || RandomPosterize | ✅ | ❌ |diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.pyindex 6be83be13..fee4ddf03 100644--- a/kornia/augmentation/_2d/intensity/__init__.py+++ b/kornia/augmentation/_2d/intensity/__init__.py@@ -1,5 +1,6 @@from kornia.augmentation._2d.intensity.box_blur import RandomBoxBlurfrom kornia.augmentation._2d.intensity.channel_shuffle import RandomChannelShuffle+from kornia.augmentation._2d.intensity.color_jiggle import ColorJigglefrom kornia.augmentation._2d.intensity.color_jitter import ColorJitterfrom kornia.augmentation._2d.intensity.denormalize import Denormalizefrom kornia.augmentation._2d.intensity.equalize import RandomEqualizediff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.pynew file mode 100644index 000000000..f95c7b962--- /dev/null+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py@@ -0,0 +1,95 @@+from typing import Dict, List, Optional, Tuple, Union, cast++from torch import Tensor++from kornia.augmentation import random_generator as rg+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.constants import pi+from kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation+++class ColorJiggle(IntensityAugmentationBase2D):+ r"""Apply a random transformation to the brightness, contrast, saturation and hue of a tensor image.++ .. image:: _static/img/ColorJiggle.png++ Args:+ p: probability of applying the transformation.+ brightness: The brightness factor to apply.+ contrast: The contrast factor to apply.+ saturation: The saturation factor to apply.+ hue: The hue factor to apply.+ 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).+ Shape:+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`+ - Output: :math:`(B, C, H, W)`++ .. note::+ This function internally uses :func:`kornia.enhance.adjust_brightness`,+ :func:`kornia.enhance.adjust_contrast`. :func:`kornia.enhance.adjust_saturation`,+ :func:`kornia.enhance.adjust_hue`.++ Examples:+ >>> rng = torch.manual_seed(0)+ >>> inputs = torch.ones(1, 3, 3, 3)+ >>> aug = ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.)+ >>> aug(inputs)+ tensor([[[[0.9993, 0.9993, 0.9993],+ [0.9993, 0.9993, 0.9993],+ [0.9993, 0.9993, 0.9993]],+ <BLANKLINE>+ [[0.9993, 0.9993, 0.9993],+ [0.9993, 0.9993, 0.9993],+ [0.9993, 0.9993, 0.9993]],+ <BLANKLINE>+ [[0.9993, 0.9993, 0.9993],+ [0.9993, 0.9993, 0.9993],+ [0.9993, 0.9993, 0.9993]]]])++ To apply the exact augmenation again, you may take the advantage of the previous parameter state:+ >>> input = torch.randn(1, 3, 32, 32)+ >>> aug = ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.)+ >>> (aug(input) == aug(input, params=aug._params)).all()+ tensor(True)+ """++ def __init__(+ self,+ brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ same_on_batch: bool = False,+ p: float = 1.0,+ keepdim: bool = False,+ return_transform: Optional[bool] = None+ ) -> None:+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)+ self.brightness = brightness+ self.contrast = contrast+ self.saturation = saturation+ self.hue = hue+ self._param_generator = cast(+ rg.ColorJiggleGenerator,+ rg.ColorJiggleGenerator(brightness, contrast, saturation, hue)+ )++ def apply_transform(+ self, input: Tensor, params: Dict[str, Tensor], transform: Optional[Tensor] = None+ ) -> Tensor:++ transforms = [+ lambda img: adjust_brightness(img, params["brightness_factor"] - 1),+ lambda img: adjust_contrast(img, params["contrast_factor"]),+ lambda img: adjust_saturation(img, params["saturation_factor"]),+ lambda img: adjust_hue(img, params["hue_factor"] * 2 * pi),+ ]++ jittered = input+ for idx in params["order"].tolist():+ t = transforms[idx]+ jittered = t(jittered)++ return jittereddiff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.pyindex a9cb877b6..e103f33c6 100644--- a/kornia/augmentation/_2d/intensity/color_jitter.py+++ b/kornia/augmentation/_2d/intensity/color_jitter.py@@ -1,3 +1,4 @@+import warningsfrom typing import Dict, List, Optional, Tuple, Union, castfrom torch import Tensor@@ -5,12 +6,19 @@ from torch import Tensorfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.constants import pi-from kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation+from kornia.enhance import (+ adjust_brightness_accumulative,+ adjust_contrast_with_mean_subtraction,+ adjust_hue,+ adjust_saturation_with_gray_subtraction,+)class ColorJitter(IntensityAugmentationBase2D):r"""Apply a random transformation to the brightness, contrast, saturation and hue of a tensor image.+ This implementation aligns PIL. Hence, the output is close to TorchVision.+.. image:: _static/img/ColorJitter.pngArgs:@@ -19,17 +27,18 @@ class ColorJitter(IntensityAugmentationBase2D):contrast: The contrast factor to apply.saturation: The saturation factor to apply.hue: The hue factor to apply.+ silence_instantiation_warning: if True, silence the warning at instantiation.same_on_batch: apply the same transformation across the batch.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).-Shape:- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`- Output: :math:`(B, C, H, W)`.. note::- This function internally uses :func:`kornia.enhance.adjust_brightness`,- :func:`kornia.enhance.adjust_contrast`. :func:`kornia.enhance.adjust_saturation`,+ This function internally uses :func:`kornia.enhance.adjust_brightness_accumulative`,+ :func:`kornia.enhance.adjust_contrast_with_mean_subtraction`,+ :func:`kornia.enhance.adjust_saturation_with_gray_subtraction`,:func:`kornia.enhance.adjust_hue`.Examples:@@ -66,23 +75,34 @@ class ColorJitter(IntensityAugmentationBase2D):p: float = 1.0,keepdim: bool = False,return_transform: Optional[bool] = None,+ silence_instantiation_warning: bool = False) -> None:super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)++ if not silence_instantiation_warning:+ warnings.warn(+ "`ColorJitter` is now following Torchvision implementation. Old "+ "behavior can be retrieved by instantiating `ColorJiggle`.",+ category=DeprecationWarning+ )+self.brightness = brightnessself.contrast = contrastself.saturation = saturationself.hue = hueself._param_generator = cast(- rg.ColorJitterGenerator, rg.ColorJitterGenerator(brightness, contrast, saturation, hue)+ rg.ColorJitterGenerator,+ rg.ColorJitterGenerator(brightness, contrast, saturation, hue))def apply_transform(self, input: Tensor, params: Dict[str, Tensor], transform: Optional[Tensor] = None) -> Tensor:+transforms = [- lambda img: adjust_brightness(img, params["brightness_factor"] - 1),- lambda img: adjust_contrast(img, params["contrast_factor"]),- lambda img: adjust_saturation(img, params["saturation_factor"]),+ lambda img: adjust_brightness_accumulative(img, params["brightness_factor"]),+ lambda img: adjust_contrast_with_mean_subtraction(img, params["contrast_factor"]),+ lambda img: adjust_saturation_with_gray_subtraction(img, params["saturation_factor"]),lambda img: adjust_hue(img, params["hue_factor"] * 2 * pi),]diff --git a/kornia/augmentation/_2d/intensity/grayscale.py b/kornia/augmentation/_2d/intensity/grayscale.pyindex b22bae86b..3eef00c7d 100644--- a/kornia/augmentation/_2d/intensity/grayscale.py+++ b/kornia/augmentation/_2d/intensity/grayscale.py@@ -13,6 +13,8 @@ class RandomGrayscale(IntensityAugmentationBase2D):.. image:: _static/img/RandomGrayscale.pngArgs:+ rgb_weights: Weights that will be applied on each channel (RGB).+ The sum of the weights should add up to one.p: probability of the image to be transformed to grayscale.same_on_batch: apply the same transformation across the batch.keepdim: whether to keep the output shape the same as input (True) or broadcast itdiff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 20acd8084..2b45466ae 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -1,5 +1,6 @@from kornia.augmentation._2d import (CenterCrop,+ ColorJiggle,ColorJitter,Denormalize,LongestMaxSize,@@ -58,6 +59,7 @@ __all__ = ["IntensityAugmentationBase2D","MixAugmentationBase","CenterCrop",+ "ColorJiggle","ColorJitter","Normalize","Denormalize",diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex b8cec0b17..ce55b85ce 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -65,7 +65,7 @@ class AugmentationSequential(ImageSequential):... ]]).expand(2, -1, -1)>>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1)>>> aug_list = AugmentationSequential(- ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),... kornia.augmentation.RandomAffine(360, p=1.0),... data_keys=["input", "mask", "bbox", "keypoints"],... same_on_batch=False,@@ -96,7 +96,7 @@ class AugmentationSequential(ImageSequential):>>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1)[None]>>> aug_list = AugmentationSequential(... VideoSequential(- ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),... kornia.augmentation.RandomAffine(360, p=1.0),... ),... data_keys=["input", "mask", "bbox", "keypoints"]@@ -121,7 +121,7 @@ class AugmentationSequential(ImageSequential):... kornia.augmentation.RandomAffine(360, p=1.0),... ),... VideoSequential(- ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),... ),... data_keys=["input", "mask", "bbox", "keypoints"],... random_apply=1,diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 392547eeb..18aa11dd4 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -47,7 +47,7 @@ class ImageSequential(SequentialBase):>>> input, label = torch.randn(2, 3, 5, 6), torch.tensor([0, 1])>>> aug_list = ImageSequential(... kornia.color.BgrToRgb(),- ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),... kornia.filters.MedianBlur((3, 3)),... kornia.augmentation.RandomAffine(360, p=1.0),... kornia.enhance.Invert(),@@ -73,7 +73,7 @@ class ImageSequential(SequentialBase):>>> input = torch.randn(2, 3, 5, 6)>>> aug_list = ImageSequential(... kornia.color.BgrToRgb(),- ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),... kornia.filters.MedianBlur((3, 3)),... kornia.augmentation.RandomAffine(360, p=1.0),... random_apply=1,diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.pyindex 534fecfee..44c198ce2 100644--- a/kornia/augmentation/container/patch.py+++ b/kornia/augmentation/container/patch.py@@ -64,13 +64,13 @@ class PatchSequential(ImageSequential):>>> input = torch.randn(2, 3, 224, 224)>>> seq = PatchSequential(... ImageSequential(- ... K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),+ ... K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),... K.RandomPerspective(0.2, p=0.5),... K.RandomSolarize(0.1, 0.1, p=0.5),... ),... K.RandomAffine(360, p=1.0),... ImageSequential(- ... K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),+ ... K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),... K.RandomPerspective(0.2, p=0.5),... K.RandomSolarize(0.1, 0.1, p=0.5),... ),@@ -93,7 +93,7 @@ class PatchSequential(ImageSequential):>>> input = torch.randn(2, 3, 224, 224)>>> seq = PatchSequential(... ImageSequential(- ... K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),+ ... K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),... K.RandomPerspective(0.2, p=0.5),... K.RandomSolarize(0.1, 0.1, p=0.5),... ),@@ -180,7 +180,7 @@ class PatchSequential(ImageSequential):Example:>>> import kornia.augmentation as K- >>> pas = PatchSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), patchwise_apply=False)+ >>> pas = PatchSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), patchwise_apply=False)>>> pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2))tensor([[[[[ 0, 1],[ 4, 5]]],@@ -226,7 +226,7 @@ class PatchSequential(ImageSequential):Example:>>> import kornia.augmentation as K- >>> pas = PatchSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), patchwise_apply=False)+ >>> pas = PatchSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), patchwise_apply=False)>>> out = pas.extract_patches(torch.arange(16).view(1, 1, 4, 4), grid_size=(2, 2))>>> pas.restore_from_patches(out, grid_size=(2, 2))tensor([[[[ 0, 1, 2, 3],diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex 7bfec176e..541295944 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -43,7 +43,7 @@ class VideoSequential(ImageSequential):>>> input, label = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1), torch.tensor([0, 1])>>> aug_list = VideoSequential(- ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),... kornia.color.BgrToRgb(),... kornia.augmentation.RandomAffine(360, p=1.0),... random_apply=10,@@ -60,7 +60,7 @@ class VideoSequential(ImageSequential):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.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),... data_format="BCTHW",@@ -81,7 +81,7 @@ class VideoSequential(ImageSequential):>>> import kornia>>> input, label = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1), torch.tensor([0, 1])>>> aug_list = VideoSequential(- ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... 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),... data_format="BCTHW",@@ -199,8 +199,9 @@ class VideoSequential(ImageSequential):mod_param = module.forward_parameters(batch_shape)if self.same_on_frame:for k, v in mod_param.items():- # TODO: revise colorjitter order param in the future to align the standard.- if not (k == "order" and isinstance(module, kornia.augmentation.ColorJitter)):+ # TODO: revise ColorJiggle and ColorJitter order param in the future to align the standard.+ if not (k == "order" and (isinstance(module, kornia.augmentation.ColorJiggle)+ or isinstance(module, kornia.augmentation.ColorJitter))):mod_param.update({k: self.__repeat_param_across_channels__(v, frame_num)})param = ParamItem(name, mod_param)else:diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.pyindex 1a7a20ec4..3c16c3c13 100644--- a/kornia/augmentation/random_generator/_2d/__init__.py+++ b/kornia/augmentation/random_generator/_2d/__init__.py@@ -1,4 +1,5 @@from kornia.augmentation.random_generator._2d.affine import *+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 *diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.pynew file mode 100644index 000000000..bb494db19--- /dev/null+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py@@ -0,0 +1,90 @@+from functools import partial+from typing import Dict, List, Tuple, Union++import torch+from torch import Tensor+from torch.distributions import Uniform++from kornia.augmentation.random_generator.base import RandomGeneratorBase+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound+from kornia.utils.helpers import _extract_device_dtype+++class ColorJiggleGenerator(RandomGeneratorBase):+ r"""Generate random color jiter parameters for a batch of images following OpenCV.++ Args:+ brightness: The brightness factor to apply.+ contrast: The contrast factor to apply.+ saturation: The saturation factor to apply.+ hue: The hue factor to apply.++ Returns:+ A dict of parameters to be passed for transformation.+ - brightness_factor: element-wise brightness factors with a shape of (B,).+ - contrast_factor: element-wise contrast factors with a shape of (B,).+ - hue_factor: element-wise hue factors with a shape of (B,).+ - saturation_factor: element-wise saturation factors with a shape of (B,).+ - order: applying orders of the color adjustments with a shape of (4). In which,+ 0 is brightness adjustment; 1 is contrast adjustment;+ 2 is saturation adjustment; 3 is hue adjustment.++ Note:+ The generated random numbers are not reproducible across different devices and dtypes. By default,+ the parameters will be generated on CPU in float32. This can be changed by calling+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.+ """++ def __init__(+ self,+ brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ ) -> None:+ super().__init__()+ self.brightness = brightness+ self.contrast = contrast+ self.saturation = saturation+ self.hue = hue++ def __repr__(self) -> str:+ repr = (+ f"brightness={self.brightness}, contrast={self.contrast}, saturation="+ f"{self.saturation}, hue={self.hue}"+ )+ return repr++ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:+ brightness = _range_bound(self.brightness, 'brightness', center=1.0,+ bounds=(0, 2), device=device, dtype=dtype)+ contrast: Tensor = _range_bound(self.contrast, 'contrast', center=1.0, device=device, dtype=dtype)+ saturation: Tensor = _range_bound(self.saturation, 'saturation', center=1.0, device=device, dtype=dtype)+ hue: Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=device, dtype=dtype)++ _joint_range_check(brightness, "brightness", (0, 2))+ _joint_range_check(contrast, "contrast", (0, float('inf')))+ _joint_range_check(hue, "hue", (-0.5, 0.5))+ _joint_range_check(saturation, "saturation", (0, float('inf')))++ self.brightness_sampler = Uniform(brightness[0], brightness[1], validate_args=False)+ self.contrast_sampler = Uniform(contrast[0], contrast[1], validate_args=False)+ self.hue_sampler = Uniform(hue[0], hue[1], validate_args=False)+ self.saturation_sampler = Uniform(saturation[0], saturation[1], validate_args=False)+ self.randperm = partial(torch.randperm, device=device, dtype=dtype)++ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]: # type:ignore+ batch_size = batch_shape[0]+ _common_param_check(batch_size, same_on_batch)+ _device, _dtype = _extract_device_dtype([self.brightness, self.contrast, self.hue, self.saturation])+ brightness_factor = _adapted_rsampling((batch_size,), self.brightness_sampler, same_on_batch)+ contrast_factor = _adapted_rsampling((batch_size,), self.contrast_sampler, same_on_batch)+ hue_factor = _adapted_rsampling((batch_size,), self.hue_sampler, same_on_batch)+ saturation_factor = _adapted_rsampling((batch_size,), self.saturation_sampler, same_on_batch)+ return dict(+ brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),+ contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),+ hue_factor=hue_factor.to(device=_device, dtype=_dtype),+ saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),+ order=self.randperm(4).to(device=_device, dtype=_dtype).long(),+ )diff --git a/kornia/augmentation/random_generator/_2d/color_jitter.py b/kornia/augmentation/random_generator/_2d/color_jitter.pyindex fc588fa42..bf3146a10 100644--- a/kornia/augmentation/random_generator/_2d/color_jitter.py+++ b/kornia/augmentation/random_generator/_2d/color_jitter.py@@ -1,22 +1,17 @@from functools import partial-from typing import Dict, List, Optional, Tuple, Union+from typing import Dict, List, Tuple, Unionimport torch+from torch import Tensorfrom 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.utils.helpers import _deprecated, _extract_device_dtype+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound+from kornia.utils.helpers import _extract_device_dtypeclass ColorJitterGenerator(RandomGeneratorBase):- r"""Generate random color jiter parameters for a batch of images.+ r"""Generate random color jiter parameters for a batch of images following Pil.Args:brightness: The brightness factor to apply.@@ -42,10 +37,10 @@ class ColorJitterGenerator(RandomGeneratorBase):def __init__(self,- brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,- contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,- saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,- hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,+ brightness: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ contrast: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ saturation: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,+ hue: Union[Tensor, float, Tuple[float, float], List[float]] = 0.0,) -> None:super().__init__()self.brightness = brightness@@ -54,18 +49,21 @@ class ColorJitterGenerator(RandomGeneratorBase):self.hue = huedef __repr__(self) -> str:- repr = f"brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}"+ repr = (+ f"brightness={self.brightness}, contrast={self.contrast}, saturation="+ f"{self.saturation}, hue={self.hue}"+ )return reprdef make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:- brightness: torch.Tensor = _range_bound(- self.brightness, 'brightness', center=1.0, bounds=(0, 2), device=device, dtype=dtype+ brightness: Tensor = _range_bound(+ self.brightness, 'brightness', center=1.0, device=device, dtype=dtype)- contrast: torch.Tensor = _range_bound(self.contrast, 'contrast', center=1.0, device=device, dtype=dtype)- saturation: torch.Tensor = _range_bound(self.saturation, 'saturation', center=1.0, device=device, dtype=dtype)- hue: torch.Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=device, dtype=dtype)+ contrast: Tensor = _range_bound(self.contrast, 'contrast', center=1.0, device=device, dtype=dtype)+ saturation: Tensor = _range_bound(self.saturation, 'saturation', center=1.0, device=device, dtype=dtype)+ hue: Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=device, dtype=dtype)- _joint_range_check(brightness, "brightness", (0, 2))+ _joint_range_check(brightness, "brightness", (0, float('inf')))_joint_range_check(contrast, "contrast", (0, float('inf')))_joint_range_check(hue, "hue", (-0.5, 0.5))_joint_range_check(saturation, "saturation", (0, float('inf')))@@ -76,7 +74,7 @@ class ColorJitterGenerator(RandomGeneratorBase):self.saturation_sampler = Uniform(saturation[0], saturation[1], validate_args=False)self.randperm = partial(torch.randperm, device=device, dtype=dtype)- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]: # type:ignorebatch_size = batch_shape[0]_common_param_check(batch_size, same_on_batch)_device, _dtype = _extract_device_dtype([self.brightness, self.contrast, self.hue, self.saturation])@@ -91,69 +89,3 @@ class ColorJitterGenerator(RandomGeneratorBase):saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),order=self.randperm(4).to(device=_device, dtype=_dtype).long(),)---@_deprecated(replace_with=ColorJitterGenerator.__name__)-def random_color_jitter_generator(- batch_size: int,- brightness: Optional[torch.Tensor] = None,- contrast: Optional[torch.Tensor] = None,- saturation: Optional[torch.Tensor] = None,- hue: Optional[torch.Tensor] = None,- same_on_batch: bool = False,- device: torch.device = torch.device('cpu'),- dtype: torch.dtype = torch.float32,-) -> Dict[str, torch.Tensor]:- r"""Generate random color jiter parameters for a batch of images.-- Args:- batch_size (int): the number of images.- brightness (torch.Tensor, optional): Brightness factor tensor of range (a, b).- The provided range must follow 0 <= a <= b <= 2. Default value is [0., 0.].- contrast (torch.Tensor, optional): Contrast factor tensor of range (a, b).- The provided range must follow 0 <= a <= b. Default value is [0., 0.].- saturation (torch.Tensor, optional): Saturation factor tensor of range (a, b).- The provided range must follow 0 <= a <= b. Default value is [0., 0.].- hue (torch.Tensor, optional): Saturation factor tensor of range (a, b).- The provided range must follow -0.5 <= a <= b < 0.5. Default value is [0., 0.].- 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.- - brightness_factor (torch.Tensor): element-wise brightness factors with a shape of (B,).- - contrast_factor (torch.Tensor): element-wise contrast factors with a shape of (B,).- - hue_factor (torch.Tensor): element-wise hue factors with a shape of (B,).- - saturation_factor (torch.Tensor): element-wise saturation factors with a shape of (B,).- - order (torch.Tensor): applying orders of the color adjustments with a shape of (4). In which,- 0 is brightness adjustment; 1 is contrast adjustment;- 2 is saturation adjustment; 3 is hue adjustment.-- Note:- The generated random numbers are not reproducible across different devices and dtypes.- """- _common_param_check(batch_size, same_on_batch)- _device, _dtype = _extract_device_dtype([brightness, contrast, hue, saturation])- brightness = torch.as_tensor([0.0, 0.0] if brightness is None else brightness, device=device, dtype=dtype)- contrast = torch.as_tensor([0.0, 0.0] if contrast is None else contrast, device=device, dtype=dtype)- hue = torch.as_tensor([0.0, 0.0] if hue is None else hue, device=device, dtype=dtype)- saturation = torch.as_tensor([0.0, 0.0] if saturation is None else saturation, device=device, dtype=dtype)-- _joint_range_check(brightness, "brightness", (0, 2))- _joint_range_check(contrast, "contrast", (0, float('inf')))- _joint_range_check(hue, "hue", (-0.5, 0.5))- _joint_range_check(saturation, "saturation", (0, float('inf')))-- brightness_factor = _adapted_uniform((batch_size,), brightness[0], brightness[1], same_on_batch)- contrast_factor = _adapted_uniform((batch_size,), contrast[0], contrast[1], same_on_batch)- hue_factor = _adapted_uniform((batch_size,), hue[0], hue[1], same_on_batch)- saturation_factor = _adapted_uniform((batch_size,), saturation[0], saturation[1], same_on_batch)-- return dict(- brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),- contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),- hue_factor=hue_factor.to(device=_device, dtype=_dtype),- saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),- order=torch.randperm(4, device=_device, dtype=_dtype).long(),- )diff --git a/kornia/enhance/__init__.py b/kornia/enhance/__init__.pyindex 4c95a35a6..bd8ac5eab 100644--- a/kornia/enhance/__init__.py+++ b/kornia/enhance/__init__.py@@ -1,11 +1,15 @@from .adjust import (AdjustBrightness,+ AdjustBrightnessAccumulative,AdjustContrast,+ AdjustContrastWithMeanSubtraction,AdjustGamma,AdjustHue,AdjustSaturation,+ AdjustSaturationWithGraySubtraction,Invert,adjust_brightness,+ adjust_brightness_accumulative,adjust_contrast,adjust_contrast_with_mean_subtraction,adjust_gamma,@@ -13,6 +17,7 @@ from .adjust import (adjust_hue_raw,adjust_saturation,adjust_saturation_raw,+ adjust_saturation_with_gray_subtraction,equalize,equalize3d,invert,@@ -28,11 +33,13 @@ from .zca import ZCAWhitening, linear_transform, zca_mean, zca_whiten__all__ = ["adjust_brightness",+ "adjust_brightness_accumulative","adjust_contrast","adjust_contrast_with_mean_subtraction","adjust_gamma","adjust_hue","adjust_saturation",+ "adjust_saturation_with_gray_subtraction","adjust_hue_raw","adjust_saturation_raw","solarize",@@ -42,10 +49,13 @@ __all__ = ["sharpness","invert","AdjustBrightness",+ "AdjustBrightnessAccumulative","AdjustContrast",+ "AdjustContrastWithMeanSubtraction","AdjustGamma","AdjustHue","AdjustSaturation",+ "AdjustSaturationWithGraySubtraction","Invert","add_weighted","AddWeighted",diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 4f3b0652c..323fe3d21 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -6,37 +6,32 @@ from torch import Tensorfrom torch.nn import Module, Parameterfrom kornia.color import hsv_to_rgb, rgb_to_grayscale, rgb_to_hsv-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_COLOR_OR_GRAY, KORNIA_CHECK_IS_TENSORfrom kornia.utils.helpers import _torch_histc_castfrom kornia.utils.image import perform_keep_shape_image, perform_keep_shape_video-def adjust_saturation_raw(input: Tensor, saturation_factor: Union[float, Tensor]) -> Tensor:- r"""Adjust color saturation of an image. Expecting input to be in hsv format already."""+def adjust_saturation_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor:+ r"""Adjust color saturation of an image. Expecting image to be in hsv format already."""- if not isinstance(input, Tensor):- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")-- if not isinstance(saturation_factor, (float, Tensor)):- raise TypeError(f"The saturation_factor should be a float number or Tensor." f"Got {type(saturation_factor)}")-- if isinstance(saturation_factor, float):- saturation_factor = torch.as_tensor(saturation_factor)-- saturation_factor = saturation_factor.to(input.device).to(input.dtype)+ KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")+ KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")- # TODO: find a proper way to check bound values in batched tensors.- # if (saturation_factor < 0).any():- # raise ValueError(f"Saturation factor must be non-negative. Got {saturation_factor}")+ if isinstance(factor, float):+ # TODO: figure out how to create later a tensor without importing torch+ factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)+ elif isinstance(factor, Tensor):+ factor = factor.to(image.device, image.dtype)- for _ in range(len(input.shape) - len(saturation_factor.shape)):- saturation_factor = torch.unsqueeze(saturation_factor, dim=-1)+ # make factor broadcastable+ while len(factor.shape) != len(image.shape):+ factor = factor[..., None]# unpack the hsv values- h, s, v = torch.chunk(input, chunks=3, dim=-3)+ h, s, v = torch.chunk(image, chunks=3, dim=-3)# transform the hue value and appl module- s_out: Tensor = torch.clamp(s * saturation_factor, min=0, max=1)+ s_out: Tensor = torch.clamp(s * factor, min=0, max=1)# pack back back the corrected hueout: Tensor = torch.cat([h, s_out, v], dim=-3)@@ -44,17 +39,75 @@ def adjust_saturation_raw(input: Tensor, saturation_factor: Union[float, Tensor]return out-def adjust_saturation(input: Tensor, saturation_factor: Union[float, Tensor]) -> Tensor:+def adjust_saturation_with_gray_subtraction(image: Tensor, factor: Union[float, Tensor]) -> Tensor:+ r"""Adjust color saturation of an image by blending the image with its grayscaled version.++ The image is expected to be an RGB image or a gray image in the range of [0, 1].+ If it is an RGB image, returns blending of the image with its grayscaled version.+ If it is a gray image, returns the image.++ .. note::+ this is just a convenience function to have compatibility with Pil++ Args:+ image: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.+ factor: How much to adjust the saturation. 0 will give a black+ and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.++ Return:+ Adjusted image in the shape of :math:`(*, 3, H, W)`.++ Example:+ >>> x = torch.ones(1, 3, 3, 3)+ >>> adjust_saturation_with_gray_subtraction(x, 2.).shape+ torch.Size([1, 3, 3, 3])++ >>> x = torch.ones(2, 3, 3, 3)+ >>> y = torch.tensor([1., 2.])+ >>> adjust_saturation_with_gray_subtraction(x, y).shape+ torch.Size([2, 3, 3, 3])+ """++ KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")+ KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")+ KORNIA_CHECK_IS_COLOR_OR_GRAY(image, "Image should be an RGB or gray image")++ if image.shape[-3] == 1:+ return image++ if isinstance(factor, float):+ # TODO: figure out how to create later a tensor without importing torch+ factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)+ elif isinstance(factor, Tensor):+ factor = factor.to(image.device, image.dtype)++ # make factor broadcastable+ while len(factor.shape) != len(image.shape):+ factor = factor[..., None]++ x_other: Tensor = rgb_to_grayscale(image)++ # blend the image with the grayscaled image+ x_adjusted: Tensor = (1 - factor) * x_other + factor * image++ # clamp the output+ out: Tensor = torch.clamp(x_adjusted, 0.0, 1.0)++ return out+++def adjust_saturation(image: Tensor, factor: Union[float, Tensor]) -> Tensor:r"""Adjust color saturation of an image... image:: _static/img/adjust_saturation.png- The input image is expected to be an RGB image in the range of [0, 1].+ The image is expected to be an RGB image in the range of [0, 1].Args:- input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.- saturation_factor: How much to adjust the saturation. 0 will give a black+ image: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.+ factor: How much to adjust the saturation. 0 will give a blackand white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.+ saturation_mode: The mode to adjust saturation.Return:Adjusted image in the shape of :math:`(*, 3, H, W)`.@@ -75,10 +128,10 @@ def adjust_saturation(input: Tensor, saturation_factor: Union[float, Tensor]) ->"""# convert the rgb image to hsv- x_hsv: Tensor = rgb_to_hsv(input)+ x_hsv: Tensor = rgb_to_hsv(image)# perform the conversion- x_adjusted: Tensor = adjust_saturation_raw(x_hsv, saturation_factor)+ x_adjusted: Tensor = adjust_saturation_raw(x_hsv, factor)# convert back to rgbout: Tensor = hsv_to_rgb(x_adjusted)@@ -86,36 +139,29 @@ def adjust_saturation(input: Tensor, saturation_factor: Union[float, Tensor]) ->return out-def adjust_hue_raw(input: Tensor, hue_factor: Union[float, Tensor]) -> Tensor:- r"""Adjust hue of an image. Expecting input to be in hsv format already."""-- if not isinstance(input, Tensor):- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")+def adjust_hue_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor:+ r"""Adjust hue of an image. Expecting image to be in hsv format already."""- if not isinstance(hue_factor, (float, Tensor)):- raise TypeError(- f"The hue_factor should be a float number or Tensor in the range between"- f" [-PI, PI]. Got {type(hue_factor)}"- )-- if isinstance(hue_factor, float):- hue_factor = torch.as_tensor(hue_factor)+ KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")+ KORNIA_CHECK(isinstance(factor, (float, Tensor)),+ f"The factor should be a float number or Tensor in the range between"+ f" [-PI, PI]. Got {type(factor)}")- hue_factor = hue_factor.to(input.device, input.dtype)+ if isinstance(factor, float):+ factor = torch.as_tensor(factor)- # TODO: find a proper way to check bound values in batched tensors.- # if ((hue_factor < -pi) | (hue_factor > pi)).any():- # raise ValueError(f"Hue-factor must be in the range [-PI, PI]. Got {hue_factor}")+ factor = factor.to(image.device, image.dtype)- for _ in range(len(input.shape) - len(hue_factor.shape)):- hue_factor = torch.unsqueeze(hue_factor, dim=-1)+ # make factor broadcastable+ while len(factor.shape) != len(image.shape):+ factor = factor[..., None]# unpack the hsv values- h, s, v = torch.chunk(input, chunks=3, dim=-3)+ h, s, v = torch.chunk(image, chunks=3, dim=-3)# transform the hue value and appl moduledivisor: float = 2 * pi- h_out: Tensor = torch.fmod(h + hue_factor, divisor)+ h_out: Tensor = torch.fmod(h + factor, divisor)# pack back back the corrected hueout: Tensor = torch.cat([h_out, s, v], dim=-3)@@ -123,16 +169,16 @@ def adjust_hue_raw(input: Tensor, hue_factor: Union[float, Tensor]) -> Tensor:return out-def adjust_hue(input: Tensor, hue_factor: Union[float, Tensor]) -> Tensor:+def adjust_hue(image: Tensor, factor: Union[float, Tensor]) -> Tensor:r"""Adjust hue of an image... image:: _static/img/adjust_hue.png- The input image is expected to be an RGB image in the range of [0, 1].+ The image is expected to be an RGB image in the range of [0, 1].Args:- input: Image to be adjusted in the shape of :math:`(*, 3, H, W)`.- hue_factor: How much to shift the hue channel. Should be in [-PI, PI]. PI+ image: Image to be adjusted in the shape of :math:`(*, 3, H, W)`.+ factor: How much to shift the hue channel. Should be in [-PI, PI]. PIand -PI give complete reversal of hue channel in HSV space in positive and negativedirection respectively. 0 means no shift. Therefore, both -PI and PI will give animage with complementary colors while 0 gives the original image.@@ -156,10 +202,10 @@ def adjust_hue(input: Tensor, hue_factor: Union[float, Tensor]) -> Tensor:"""# convert the rgb image to hsv- x_hsv: Tensor = rgb_to_hsv(input)+ x_hsv: Tensor = rgb_to_hsv(image)# perform the conversion- x_adjusted: Tensor = adjust_hue_raw(x_hsv, hue_factor)+ x_adjusted: Tensor = adjust_hue_raw(x_hsv, factor)# convert back to rgbout: Tensor = hsv_to_rgb(x_adjusted)@@ -313,7 +359,7 @@ def adjust_contrast_with_mean_subtraction(image: Tensor, factor: Union[float, Te.. note::this is just a convenience function to have compatibility with Pil. For exact- definition of image contrast adjustmen consider using :func:`kornia.enhance.adjust_gamma`.+ definition of image contrast adjustment consider using :func:`kornia.enhance.adjust_gamma`.Args:image: Image to be adjusted in the shape of :math:`(*, H, W)`.@@ -358,7 +404,11 @@ def adjust_contrast_with_mean_subtraction(image: Tensor, factor: Union[float, Teimg_mean = image.mean()# Apply contrast factor subtracting the mean- return image * factor + img_mean * (1. - factor)+ img_adjust: Tensor = image * factor + img_mean * (1 - factor)++ img_adjust = img_adjust.clamp(min=0.0, max=1.0)++ return img_adjustdef adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output=True) -> Tensor:@@ -428,6 +478,57 @@ def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output=Treturn img_adjust+def adjust_brightness_accumulative(image: Tensor, factor: Union[float, Tensor], clip_output=True) -> Tensor:+ r"""Adjust the brightness accumulatively of an image tensor.++ This implementation follows PIL convention.++ The input image and factor is expected to be in the range of [0, 1].++ Args:+ image: Image to be adjusted in the shape of :math:`(*, H, W)`.+ factor: Brightness adjust factor per element in the batch. It's recommended to+ bound the factor by [0, 1]. 0 does not modify the input image while any other+ number modify the brightness.++ Return:+ Adjusted tensor in the shape of :math:`(*, H, W)`.++ Example:+ >>> x = torch.ones(1, 1, 2, 2)+ >>> adjust_brightness_accumulative(x, 1.)+ tensor([[[[1., 1.],+ [1., 1.]]]])++ >>> x = torch.ones(2, 5, 3, 3)+ >>> y = torch.tensor([0.25, 0.50])+ >>> adjust_brightness_accumulative(x, y).shape+ torch.Size([2, 5, 3, 3])+ """+ KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")+ KORNIA_CHECK(isinstance(factor, (float, Tensor)), "Factor should be float or Tensor.")++ # convert factor to a tensor+ if isinstance(factor, float):+ # TODO: figure out how to create later a tensor without importing torch+ factor = torch.as_tensor(factor, device=image.device, dtype=image.dtype)+ elif isinstance(factor, Tensor):+ factor = factor.to(image.device, image.dtype)++ # make factor broadcastable+ while len(factor.shape) != len(image.shape):+ factor = factor[..., None]++ # shift pixel values+ img_adjust: Tensor = image * factor++ # truncate between pixel values+ if clip_output:+ img_adjust = img_adjust.clamp(min=0.0, max=1.0)++ return img_adjust++def _solarize(input: Tensor, thresholds: Union[float, Tensor] = 0.5) -> Tensor:r"""For each pixel in the image, select the pixel if the value is less than the threshold.Otherwise, subtract 1.0 from the pixel.@@ -841,6 +942,7 @@ class AdjustSaturation(Module):Args:saturation_factor: How much to adjust the saturation. 0 will give a blackand white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.+ saturation_mode: The mode to adjust saturation.Shape:- Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.@@ -876,9 +978,59 @@ class AdjustSaturation(Module):return adjust_saturation(input, self.saturation_factor)+class AdjustSaturationWithGraySubtraction(Module):+ r"""Adjust color saturation of an image.++ This implementation aligns PIL. Hence, the output is close to TorchVision.+ The input image is expected to be in the range of [0, 1].++ The input image is expected to be an RGB or gray image in the range of [0, 1].++ Args:+ saturation_factor: How much to adjust the saturation. 0 will give a black+ and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2.+ saturation_mode: The mode to adjust saturation.++ Shape:+ - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.+ - Output: Adjusted image in the shape of :math:`(*, 3, H, W)`.++ Example:+ >>> x = torch.ones(1, 3, 3, 3)+ >>> AdjustSaturationWithGraySubtraction(2.)(x)+ tensor([[[[1., 1., 1.],+ [1., 1., 1.],+ [1., 1., 1.]],+ <BLANKLINE>+ [[1., 1., 1.],+ [1., 1., 1.],+ [1., 1., 1.]],+ <BLANKLINE>+ [[1., 1., 1.],+ [1., 1., 1.],+ [1., 1., 1.]]]])++ >>> x = torch.ones(2, 3, 3, 3)+ >>> y = torch.ones(2)+ >>> out = AdjustSaturationWithGraySubtraction(y)(x)+ >>> torch.nn.functional.mse_loss(x, out)+ tensor(0.)+ """++ def __init__(self, saturation_factor: Union[float, Tensor]) -> None:+ super().__init__()+ self.saturation_factor: Union[float, Tensor] = saturation_factor++ def forward(self, input: Tensor) -> Tensor:+ return adjust_saturation_with_gray_subtraction(input, self.saturation_factor)++class AdjustHue(Module):r"""Adjust hue of an image.+ This implementation aligns PIL. Hence, the output is close to TorchVision.+ The input image is expected to be in the range of [0, 1].+The input image is expected to be an RGB image in the range of [0, 1].Args:@@ -987,7 +1139,10 @@ class AdjustContrast(Module):torch.Size([2, 5, 3, 3])"""- def __init__(self, contrast_factor: Union[float, Tensor]) -> None:+ def __init__(+ self,+ contrast_factor: Union[float, Tensor],+ ) -> None:super().__init__()self.contrast_factor: Union[float, Tensor] = contrast_factor@@ -995,6 +1150,47 @@ class AdjustContrast(Module):return adjust_contrast(input, self.contrast_factor)+class AdjustContrastWithMeanSubtraction(Module):+ r"""Adjust Contrast of an image.++ This implementation aligns PIL. Hence, the output is close to TorchVision.+ The input image is expected to be in the range of [0, 1].++ Args:+ contrast_factor: Contrast adjust factor per element+ in the batch by subtracting its mean grayscaled version.+ 0 generates a completely black image, 1 does not modify+ the input image while any other non-negative number modify the+ brightness by this factor.++ Shape:+ - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`.+ - Output: Adjusted image in the shape of :math:`(*, N)`.++ Example:+ >>> x = torch.ones(1, 1, 3, 3)+ >>> AdjustContrastWithMeanSubtraction(0.5)(x)+ tensor([[[[1., 1., 1.],+ [1., 1., 1.],+ [1., 1., 1.]]]])++ >>> x = torch.ones(2, 5, 3, 3)+ >>> y = torch.ones(2)+ >>> AdjustContrastWithMeanSubtraction(y)(x).shape+ torch.Size([2, 5, 3, 3])+ """++ def __init__(+ self,+ contrast_factor: Union[float, Tensor],+ ) -> None:+ super().__init__()+ self.contrast_factor: Union[float, Tensor] = contrast_factor++ def forward(self, input: Tensor) -> Tensor:+ return adjust_contrast_with_mean_subtraction(input, self.contrast_factor)++class AdjustBrightness(Module):r"""Adjust Brightness of an image.@@ -1023,7 +1219,10 @@ class AdjustBrightness(Module):torch.Size([2, 5, 3, 3])"""- def __init__(self, brightness_factor: Union[float, Tensor]) -> None:+ def __init__(+ self,+ brightness_factor: Union[float, Tensor],+ ) -> None:super().__init__()self.brightness_factor: Union[float, Tensor] = brightness_factor@@ -1031,6 +1230,45 @@ class AdjustBrightness(Module):return adjust_brightness(input, self.brightness_factor)+class AdjustBrightnessAccumulative(Module):+ r"""Adjust Brightness of an image accumulatively.++ This implementation aligns PIL. Hence, the output is close to TorchVision.+ The input image is expected to be in the range of [0, 1].++ Args:+ brightness_factor: Brightness adjust factor per element+ in the batch. 0 does not modify the input image while any other number modify the+ brightness.++ Shape:+ - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`.+ - Output: Adjusted image in the shape of :math:`(*, N)`.++ Example:+ >>> x = torch.ones(1, 1, 3, 3)+ >>> AdjustBrightnessAccumulative(1.)(x)+ tensor([[[[1., 1., 1.],+ [1., 1., 1.],+ [1., 1., 1.]]]])++ >>> x = torch.ones(2, 5, 3, 3)+ >>> y = torch.ones(2)+ >>> AdjustBrightnessAccumulative(y)(x).shape+ torch.Size([2, 5, 3, 3])+ """++ def __init__(+ self,+ brightness_factor: Union[float, Tensor],+ ) -> None:+ super().__init__()+ self.brightness_factor: Union[float, Tensor] = brightness_factor++ def forward(self, input: Tensor) -> Tensor:+ return adjust_brightness_accumulative(input, self.brightness_factor)++class Invert(Module):r"""Invert the values of an input tensor by its maximum value.diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex e2bfde586..b155eb318 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -213,3 +213,18 @@ def KORNIA_CHECK(condition, msg: Optional[str] = None):def KORNIA_CHECK_IS_TENSOR(x, msg: Optional[str] = None):if not isinstance(x, Tensor):raise TypeError(f"Not a Tensor type. Got: {type(x)}.\n{msg}")+++def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None):+ if len(x.shape) < 3 or x.shape[-3] != 3:+ raise TypeError(f"Not a color tensor. Got: {type(x)}.\n{msg}")+++def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None):+ if len(x.shape) < 2 or (len(x.shape) >= 3 and x.shape[-3] != 1):+ raise TypeError(f"Not a gray tensor. Got: {type(x)}.\n{msg}")+++def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None):+ if len(x.shape) < 3 or x.shape[-3] not in [1, 3]:+ raise TypeError(f"Not an color or gray tensor. Got: {type(x)}.\n{msg}")diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex 192d3d6bb..f8cd20c0c 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -9,6 +9,7 @@ import kornia.testing as utils # test utilsfrom kornia.augmentation import (AugmentationSequential,CenterCrop,+ ColorJiggle,ColorJitter,Denormalize,LongestMaxSize,@@ -668,7 +669,7 @@ class TestRandomGrayscaleAlternative(CommonTests):class TestRandomHorizontalFlip:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")def test_smoke(self):f = RandomHorizontalFlip(p=0.5)@@ -824,7 +825,7 @@ class TestRandomHorizontalFlip:class TestRandomVerticalFlip:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")def test_smoke(self):f = RandomVerticalFlip(p=0.5)@@ -965,23 +966,23 @@ class TestRandomVerticalFlip:).all()-class TestColorJitter:+class TestColorJiggle:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")def test_smoke(self):- f = ColorJitter(brightness=0.5, contrast=0.3, saturation=[0.2, 1.2], hue=0.1)+ f = ColorJiggle(brightness=0.5, contrast=0.3, saturation=[0.2, 1.2], hue=0.1)repr = (- "ColorJitter(brightness=tensor([0.5000, 1.5000]), contrast=tensor([0.7000, 1.3000]), "+ "ColorJiggle(brightness=tensor([0.5000, 1.5000]), contrast=tensor([0.7000, 1.3000]), ""saturation=tensor([0.2000, 1.2000]), hue=tensor([-0.1000, 0.1000]), ""p=1.0, p_batch=1.0, same_on_batch=False)")assert str(f) == repr- def test_color_jitter(self, device, dtype):+ def test_color_jiggle(self, device, dtype):- f = ColorJitter()+ f = ColorJiggle()input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 3 x 5 x 5expected = input@@ -991,8 +992,8 @@ class TestColorJitter:assert_close(f(input), expected, atol=1e-4, rtol=1e-5)assert_close(f.transform_matrix, expected_transform, atol=1e-4, rtol=1e-4)- def test_color_jitter_batch(self, device, dtype):- f = ColorJitter()+ def test_color_jiggle_batch(self, device, dtype):+ f = ColorJiggle()input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype) # 2 x 3 x 5 x 5expected = input@@ -1003,7 +1004,7 @@ class TestColorJitter:assert_close(f.transform_matrix, expected_transform, atol=1e-4, rtol=1e-4)def test_same_on_batch(self, device, dtype):- f = ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.1, same_on_batch=True)+ f = ColorJiggle(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.1, same_on_batch=True)input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)res = f(input)assert (res[0] == res[1]).all()@@ -1028,7 +1029,7 @@ class TestColorJitter:def test_random_brightness(self, device, dtype):torch.manual_seed(42)- f = ColorJitter(brightness=0.2)+ f = ColorJiggle(brightness=0.2)input = torch.tensor([[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype@@ -1041,7 +1042,7 @@ class TestColorJitter:def test_random_brightness_tuple(self, device, dtype):torch.manual_seed(42)- f = ColorJitter(brightness=(0.8, 1.2))+ f = ColorJiggle(brightness=(0.8, 1.2))input = torch.tensor([[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype@@ -1072,7 +1073,7 @@ class TestColorJitter:def test_random_contrast(self, device, dtype):torch.manual_seed(42)- f = ColorJitter(contrast=0.2)+ f = ColorJiggle(contrast=0.2)input = torch.tensor([[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype@@ -1085,7 +1086,7 @@ class TestColorJitter:def test_random_contrast_list(self, device, dtype):torch.manual_seed(42)- f = ColorJitter(contrast=[0.8, 1.2])+ f = ColorJiggle(contrast=[0.8, 1.2])input = torch.tensor([[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype@@ -1116,7 +1117,7 @@ class TestColorJitter:def test_random_saturation(self, device, dtype):torch.manual_seed(42)- f = ColorJitter(saturation=0.2)+ f = ColorJiggle(saturation=0.2)input = torch.tensor([@@ -1136,7 +1137,7 @@ class TestColorJitter:def test_random_saturation_tensor(self, device, dtype):torch.manual_seed(42)- f = ColorJitter(saturation=torch.tensor(0.2))+ f = ColorJiggle(saturation=torch.tensor(0.2))input = torch.tensor([@@ -1157,7 +1158,7 @@ class TestColorJitter:def test_random_saturation_tuple(self, device, dtype):torch.manual_seed(42)- f = ColorJitter(saturation=(0.8, 1.2))+ f = ColorJiggle(saturation=(0.8, 1.2))input = torch.tensor([@@ -1196,7 +1197,7 @@ class TestColorJitter:def test_random_hue(self, device, dtype):torch.manual_seed(42)- f = ColorJitter(hue=0.1 / pi.item())+ f = ColorJiggle(hue=0.1 / pi.item())input = torch.tensor([@@ -1217,7 +1218,7 @@ class TestColorJitter:def test_random_hue_list(self, device, dtype):torch.manual_seed(42)- f = ColorJitter(hue=[-0.1 / pi, 0.1 / pi])+ f = ColorJiggle(hue=[-0.1 / pi, 0.1 / pi])input = torch.tensor([@@ -1236,9 +1237,290 @@ class TestColorJitter:assert_close(f(input), expected, atol=1e-4, rtol=1e-4)- def test_random_hue_list_batch(self, device, dtype):+ def test_sequential(self, device, dtype):++ f = AugmentationSequential(ColorJiggle(), ColorJiggle())++ input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 1 x 3 x 5 x 5++ expected = input++ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # 3 x 3++ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)+ assert_close(f.transform_matrix, expected_transform, atol=1e-4, rtol=1e-5)++ def test_color_jitter_batch_sequential(self, device, dtype):+ f = AugmentationSequential(ColorJiggle(), ColorJiggle())++ input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype) # 2 x 3 x 5 x 5+ expected = input++ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).expand((2, 3, 3)) # 2 x 3 x 3++ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)+ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)+ assert_close(f.transform_matrix, expected_transform, atol=1e-4, rtol=1e-5)++ def test_gradcheck(self, device, dtype):+ input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3+ input = utils.tensor_to_gradcheck_var(input) # to var+ assert gradcheck(ColorJiggle(p=1.0), (input,), raise_exception=True)+++class TestColorJitter:++ # TODO: improve and implement more meaningful smoke tests e.g check for a consistent+ # return values such a Tensor variable.+ @pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")+ def test_smoke(self):+ f = ColorJitter(brightness=0.5, contrast=0.3, saturation=[0.2, 1.2], hue=0.1)+ repr = (+ "ColorJitter(brightness=tensor([0.5000, 1.5000]), contrast=tensor([0.7000, 1.3000]), "+ "saturation=tensor([0.2000, 1.2000]), hue=tensor([-0.1000, 0.1000]), "+ "p=1.0, p_batch=1.0, same_on_batch=False)"+ )+ assert str(f) == repr++ def test_color_jitter(self, device, dtype):++ f = ColorJitter()++ input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 3 x 5 x 5+ expected = input++ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # 3 x 3++ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)+ assert_close(f.transform_matrix, expected_transform, atol=1e-4, rtol=1e-4)++ def test_color_jitter_batch(self, device, dtype):+ f = ColorJitter()++ input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype) # 2 x 3 x 5 x 5+ expected = input++ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).expand((2, 3, 3)) # 2 x 3 x 3++ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)+ assert_close(f.transform_matrix, expected_transform, atol=1e-4, rtol=1e-4)++ def test_same_on_batch(self, device, dtype):+ f = ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.1, same_on_batch=True)+ input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)+ res = f(input)+ assert (res[0] == res[1]).all()++ def _get_expected_brightness(self, device, dtype):+ return torch.tensor(+ [+ [+ [[0.1153, 0.2306, 0.3459], [0.6917, 0.5764, 0.4612], [0.8070, 0.9223, 1.0000]],+ [[0.1153, 0.2306, 0.3459], [0.6917, 0.5764, 0.4612], [0.8070, 0.9223, 1.0000]],+ [[0.1153, 0.2306, 0.3459], [0.6917, 0.5764, 0.4612], [0.8070, 0.9223, 1.0000]],+ ],+ [+ [[0.1166, 0.2332, 0.3498], [0.6996, 0.5830, 0.4664], [0.8162, 0.9328, 1.0000]],+ [[0.1166, 0.2332, 0.3498], [0.6996, 0.5830, 0.4664], [0.8162, 0.9328, 1.0000]],+ [[0.1166, 0.2332, 0.3498], [0.6996, 0.5830, 0.4664], [0.8162, 0.9328, 1.0000]],+ ],+ ],+ device=device,+ dtype=dtype,+ )++ def test_random_brightness(self, device, dtype):+ torch.manual_seed(42)+ f = ColorJitter(brightness=0.2)++ input = torch.tensor(+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype+ ) # 1 x 1 x 3 x 3+ input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3++ expected = self._get_expected_brightness(device, dtype)++ assert_close(f(input), expected, atol=1e-4, rtol=1e-4)++ def test_random_brightness_tuple(self, device, dtype):torch.manual_seed(42)- f = ColorJitter(hue=[-0.1 / pi.item(), 0.1 / pi.item()])+ f = ColorJitter(brightness=(0.8, 1.2))++ input = torch.tensor(+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype+ ) # 1 x 1 x 3 x 3+ input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3++ expected = self._get_expected_brightness(device, dtype)++ assert_close(f(input), expected, atol=1e-4, rtol=1e-4)++ def _get_expected_contrast(self, device, dtype):+ return torch.tensor(+ [+ [+ [[0.1193, 0.2146, 0.3099], [0.5958, 0.5005, 0.4052], [0.6911, 0.7865, 0.9771]],+ [[0.1193, 0.2146, 0.3099], [0.5958, 0.5005, 0.4052], [0.6911, 0.7865, 0.9771]],+ [[0.1193, 0.2146, 0.3099], [0.5958, 0.5005, 0.4052], [0.6911, 0.7865, 0.9771]],+ ],+ [+ [[0.0245, 0.1428, 0.2612], [0.6163, 0.4980, 0.3796], [0.7347, 0.8531, 1.0000]],+ [[0.0245, 0.1428, 0.2612], [0.6163, 0.4980, 0.3796], [0.7347, 0.8531, 1.0000]],+ [[0.0245, 0.1428, 0.2612], [0.6163, 0.4980, 0.3796], [0.7347, 0.8531, 1.0000]],+ ],+ ],+ device=device,+ dtype=dtype,+ )++ def test_random_contrast(self, device, dtype):+ torch.manual_seed(42)+ f = ColorJitter(contrast=0.2)++ input = torch.tensor(+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype+ ) # 1 x 1 x 3 x 3+ input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3++ expected = self._get_expected_contrast(device, dtype)++ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)++ def test_random_contrast_list(self, device, dtype):+ torch.manual_seed(42)+ f = ColorJitter(contrast=[0.8, 1.2])++ input = torch.tensor(+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype+ ) # 1 x 1 x 3 x 3+ input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3++ expected = self._get_expected_contrast(device, dtype)++ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)++ def _get_expected_saturation(self, device, dtype):+ return torch.tensor(+ [+ [+ [[0.1570, 0.2238, 0.3216], [0.6033, 0.4863, 0.3863], [0.7068, 0.7555, 0.9487]],+ [[0.9693, 0.4946, 0.5924], [0.6033, 0.3058, 0.2058], [0.7971, 0.1237, 0.2266]],+ [[0.6083, 0.7654, 0.6826], [0.8741, 0.3058, 0.2058], [0.7971, 0.3945, 0.4974]],+ ],+ [+ [[0.0312, 0.1713, 0.2740], [0.5960, 0.5165, 0.4165], [0.6918, 0.8536, 1.0000]],+ [[1.0000, 0.5065, 0.6092], [0.5960, 0.2930, 0.1930], [0.8035, 0.0714, 0.1679]],+ [[0.5900, 0.8418, 0.7210], [0.9312, 0.2930, 0.1930], [0.8035, 0.4066, 0.5031]],+ ],+ ],+ device=device,+ dtype=dtype,+ )++ def test_random_saturation(self, device, dtype):+ torch.manual_seed(42)+ f = ColorJitter(saturation=0.2)++ input = torch.tensor(+ [+ [+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],+ ]+ ],+ device=device,+ dtype=dtype,+ ) # 1 x 1 x 3 x 3+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3++ expected = self._get_expected_saturation(device, dtype)+ assert_close(f(input), expected, atol=1e-4, rtol=1e-4)++ def test_random_saturation_tensor(self, device, dtype):+ torch.manual_seed(42)+ f = ColorJitter(saturation=torch.tensor(0.2))++ input = torch.tensor(+ [+ [+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],+ ]+ ],+ device=device,+ dtype=dtype,+ ) # 1 x 1 x 3 x 3+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3++ expected = self._get_expected_saturation(device, dtype)++ assert_close(f(input), expected, atol=1e-4, rtol=1e-4)++ def test_random_saturation_tuple(self, device, dtype):+ torch.manual_seed(42)+ f = ColorJitter(saturation=(0.8, 1.2))++ input = torch.tensor(+ [+ [+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],+ ]+ ],+ device=device,+ dtype=dtype,+ ) # 1 x 1 x 3 x 3+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3++ expected = self._get_expected_saturation(device, dtype)++ assert_close(f(input), expected, atol=1e-4, rtol=1e-4)++ def _get_expected_hue(self, device, dtype):+ return torch.tensor(+ [+ [+ [[0.1000, 0.2000, 0.3000], [0.6000, 0.5000, 0.4000], [0.7000, 0.8000, 1.0000]],+ [[1.0000, 0.5251, 0.6167], [0.6126, 0.3000, 0.2000], [0.8000, 0.1000, 0.2000]],+ [[0.5623, 0.8000, 0.7000], [0.9000, 0.3084, 0.2084], [0.7958, 0.4293, 0.5335]],+ ],+ [+ [[0.1000, 0.2000, 0.3000], [0.6116, 0.5000, 0.4000], [0.7000, 0.8000, 1.0000]],+ [[1.0000, 0.4769, 0.5846], [0.6000, 0.3077, 0.2077], [0.7961, 0.1000, 0.2000]],+ [[0.6347, 0.8000, 0.7000], [0.9000, 0.3000, 0.2000], [0.8000, 0.3730, 0.4692]],+ ],+ ],+ device=device,+ dtype=dtype,+ )++ def test_random_hue(self, device, dtype):+ torch.manual_seed(42)+ f = ColorJiggle(hue=0.1 / pi.item())++ input = torch.tensor(+ [+ [+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],+ ]+ ],+ device=device,+ dtype=dtype,+ ) # 1 x 1 x 3 x 3+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3++ expected = self._get_expected_hue(device, dtype)++ assert_close(f(input), expected, atol=1e-4, rtol=1e-4)++ def test_random_hue_list(self, device, dtype):+ torch.manual_seed(42)+ f = ColorJiggle(hue=[-0.1 / pi, 0.1 / pi])input = torch.tensor([@@ -1259,7 +1541,7 @@ class TestColorJitter:def test_sequential(self, device, dtype):- f = AugmentationSequential(ColorJitter(), ColorJitter())+ f = AugmentationSequential(ColorJiggle(), ColorJiggle())input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 1 x 3 x 5 x 5@@ -1332,7 +1614,7 @@ class TestRectangleRandomErasing:class TestRandomGrayscale:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")def test_smoke(self):f = RandomGrayscale()@@ -1627,7 +1909,7 @@ class TestRandomRotation:torch.manual_seed(0) # for random reproductibility# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")def test_smoke(self):f = RandomRotation(degrees=45.5)@@ -1781,7 +2063,7 @@ class TestRandomRotation:class TestRandomCrop:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")def test_smoke(self):f = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, pad_if_needed=False, p=1.0)@@ -2026,7 +2308,7 @@ class TestRandomCrop:class TestRandomResizedCrop:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")def test_smoke(self):f = RandomResizedCrop(size=(2, 3), scale=(1.0, 1.0), ratio=(1.0, 1.0))@@ -2180,7 +2462,7 @@ class TestRandomResizedCrop:class TestRandomEqualize:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing precision.")def test_smoke(self, device, dtype):f = RandomEqualize(p=0.5)@@ -2298,7 +2580,7 @@ class TestRandomEqualize:class TestGaussianBlur:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")def test_smoke(self):f = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.0)@@ -2338,7 +2620,7 @@ class TestRandomGaussianNoise:class TestNormalize:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a 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.0]), std=torch.tensor([1.0]))@@ -2412,7 +2694,7 @@ class TestNormalize:class TestDenormalize:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent- # return values such a torch.Tensor variable.+ # return values such a 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.0]), std=torch.tensor([1.0]))diff --git a/test/augmentation/test_backward.py b/test/augmentation/test_backward.pyindex 7539d62a5..a70dd0ea4 100644--- a/test/augmentation/test_backward.py+++ b/test/augmentation/test_backward.py@@ -3,6 +3,7 @@ import torchimport torch.nn as nnfrom kornia.augmentation import (+ ColorJiggle,ColorJitter,RandomAffine,RandomErasing,@@ -14,13 +15,71 @@ from kornia.augmentation import ()+class TestColorJiggleBackward:+ @pytest.mark.parametrize("brightness", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])+ @pytest.mark.parametrize("contrast", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])+ @pytest.mark.parametrize("saturation", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])+ @pytest.mark.parametrize("hue", [0.1, torch.tensor(0.1), torch.tensor([-0.1, 0.1])])+ @pytest.mark.parametrize("same_on_batch", [True, False])+ def test_param(self, brightness, contrast, saturation, hue,+ same_on_batch, device, dtype):++ _brightness = (+ brightness+ if isinstance(brightness, (int, float))+ else nn.Parameter(brightness.clone().to(device=device, dtype=dtype))+ )+ _contrast = (+ contrast+ if isinstance(contrast, (int, float))+ else nn.Parameter(contrast.clone().to(device=device, dtype=dtype))+ )+ _saturation = (+ saturation+ if isinstance(saturation, (int, float))+ else nn.Parameter(saturation.clone().to(device=device, dtype=dtype))+ )+ _hue = hue if isinstance(hue, (int, float)) else nn.Parameter(hue.clone().to(device=device, dtype=dtype))++ torch.manual_seed(0)+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0+ aug = ColorJiggle(_brightness, _contrast, _saturation, _hue, same_on_batch)++ output = aug(input)++ if len(list(aug.parameters())) != 0:+ mse = nn.MSELoss()+ opt = torch.optim.SGD(aug.parameters(), lr=10)+ loss = mse(output, torch.ones_like(output) * 2)+ loss.backward()+ opt.step()++ if not isinstance(brightness, (int, float)):+ assert isinstance(aug.brightness, torch.Tensor)+ # Assert if param not updated+ assert (brightness.to(device=device, dtype=dtype) - aug.brightness.data).sum() != 0+ if not isinstance(contrast, (int, float)):+ assert isinstance(aug.contrast, torch.Tensor)+ # Assert if param not updated+ assert (contrast.to(device=device, dtype=dtype) - aug.contrast.data).sum() != 0+ if not isinstance(saturation, (int, float)):+ assert isinstance(aug.saturation, torch.Tensor)+ # Assert if param not updated+ assert (saturation.to(device=device, dtype=dtype) - aug.saturation.data).sum() != 0+ if not isinstance(hue, (int, float)):+ assert isinstance(aug.hue, torch.Tensor)+ # Assert if param not updated+ assert (hue.to(device=device, dtype=dtype) - aug.hue.data).sum() != 0++class TestColorJitterBackward:@pytest.mark.parametrize("brightness", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])@pytest.mark.parametrize("contrast", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])@pytest.mark.parametrize("saturation", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])@pytest.mark.parametrize("hue", [0.1, torch.tensor(0.1), torch.tensor([-0.1, 0.1])])@pytest.mark.parametrize("same_on_batch", [True, False])- def test_param(self, brightness, contrast, saturation, hue, same_on_batch, device, dtype):+ def test_param(self, brightness, contrast, saturation, hue,+ same_on_batch, device, dtype):_brightness = (brightnessdiff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.pyindex f8b5221e1..8cb024902 100644--- a/test/augmentation/test_container.py+++ b/test/augmentation/test_container.py@@ -37,7 +37,7 @@ 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)+ aug_list = K.VideoSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1), data_format=data_format, same_on_frame=True)with pytest.raises(AssertionError):img = torch.randn(*shape, device=device, dtype=dtype)aug_list(img)@@ -47,7 +47,7 @@ class TestVideoSequential:[K.RandomAffine(360, p=1.0),K.CenterCrop((3, 3), p=1.0),- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomCrop((5, 5), p=1.0),K.RandomErasing(p=1.0),K.RandomGrayscale(p=1.0),@@ -75,13 +75,13 @@ class TestVideoSequential:@pytest.mark.parametrize('augmentations',[- [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)],- [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)],+ [K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)],+ [K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)],[K.RandomAffine(360, p=1.0), kornia.color.BgrToRgb()],- [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.0), K.RandomAffine(360, p=0.0)],- [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.0)],+ [K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.0), K.RandomAffine(360, p=0.0)],+ [K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.0)],[K.RandomAffine(360, p=0.0)],- [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0), K.RandomMixUp(p=1.0)],+ [K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0), K.RandomMixUp(p=1.0)],],)@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])@@ -114,7 +114,7 @@ class TestVideoSequential:[[K.RandomAffine(360, p=1.0)],[K.RandomCrop((2, 2), padding=2)],- [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)],+ [K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)],[K.RandomAffine(360, p=0.0), K.ImageSequential(K.RandomAffine(360, p=0.0))],],)@@ -148,7 +148,7 @@ class TestVideoSequential:def test_jit(self, device, dtype):B, C, D, H, W = 2, 3, 5, 4, 4img = 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 = K.VideoSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1), same_on_frame=True)op_jit = torch.jit.script(op)assert_close(op(img), op_jit(img))@@ -159,7 +159,7 @@ class TestSequential:inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)with pytest.raises(Exception): # AssertError and NotImplementedErrorK.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), random_apply_weights=random_apply_weights+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), random_apply_weights=random_apply_weights).inverse(inp)@pytest.mark.parametrize('same_on_batch', [True, False, None])@@ -167,7 +167,7 @@ class TestSequential:@pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 20, True, False])def test_construction(self, same_on_batch, keepdim, random_apply):aug = K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomAffine(360, p=1.0),K.RandomMixUp(p=1.0),same_on_batch=same_on_batch,@@ -189,10 +189,10 @@ class TestSequential:def test_forward(self, random_apply, device, dtype):inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)aug = K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),kornia.filters.MedianBlur((3, 3)),- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),- K.ImageSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)),K.ImageSequential(K.RandomAffine(360, p=1.0)),K.RandomAffine(360, p=1.0),K.RandomMixUp(p=1.0),@@ -210,7 +210,7 @@ class TestAugmentationSequential:@pytest.mark.parametrize('data_keys', ["input", ["mask", "input"], ["input", "bbox_yxyx"], [0, 10], [BorderType.REFLECT]])- @pytest.mark.parametrize("augmentation_list", [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)])+ @pytest.mark.parametrize("augmentation_list", [K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)])def test_exception(self, augmentation_list, data_keys, device, dtype):with pytest.raises(Exception): # AssertError and NotImplementedErrorK.AugmentationSequential(augmentation_list, data_keys=data_keys)@@ -222,9 +222,9 @@ class TestAugmentationSequential:inp = torch.as_tensor(inp, device=device, dtype=dtype)aug = K.AugmentationSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomAffine(360, p=1.0),K.RandomMixUp(p=1.0),data_keys=["input"],@@ -245,7 +245,7 @@ class TestAugmentationSequential:points = torch.tensor([[[1.0, 1.0]]], device=device, dtype=dtype).expand(2, -1, -1)[None]aug_list = K.AugmentationSequential(K.VideoSequential(- kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), kornia.augmentation.RandomAffine(360, p=1.0)+ kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), kornia.augmentation.RandomAffine(360, p=1.0)),data_keys=["input", "mask", "bbox", "keypoints"],)@@ -424,14 +424,14 @@ class TestAugmentationSequential:)[:, None].float()aug = K.AugmentationSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),K.AugmentationSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0),K.RandomAffine(360, p=1.0),data_keys=["input", "mask", "bbox", "keypoints"]),- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomAffine(360, p=1.0),data_keys=["input", "mask", "bbox", "keypoints"],random_apply=random_apply,@@ -460,10 +460,10 @@ class TestAugmentationSequential:aug = K.AugmentationSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),K.AugmentationSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),K.RandomAffine(360, p=1.0),K.RandomCrop(crop_size, padding=1, cropping_mode='resample', fill=0),@@ -504,12 +504,12 @@ class TestAugmentationSequential:)[:, None].float()aug = K.AugmentationSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),K.AugmentationSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomAffine(360, p=1.0),data_keys=["input", "mask", "bbox", "keypoints"],random_apply=random_apply,@@ -553,12 +553,12 @@ class TestAugmentationSequential:)[:, None].float()aug = K.AugmentationSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),K.AugmentationSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomAffine(360, p=1.0),data_keys=["input", "mask", "bbox", "keypoints", "bbox", "BBOX_XYWH", "BBOX_XYWH"],random_apply=random_apply,@@ -580,7 +580,7 @@ class TestAugmentationSequential:B, C, H, W = 2, 3, 4, 4img = torch.ones(B, C, H, W, device=device, dtype=dtype)op = K.AugmentationSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0), same_on_batch=True+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0), same_on_batch=True)op_jit = torch.jit.script(op)assert_close(op(img), op_jit(img))@@ -599,17 +599,17 @@ class TestPatchSequential:with pytest.raises(Exception): # AssertError and NotImplementedErrorK.PatchSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),K.RandomPerspective(0.2, p=0.5),K.RandomSolarize(0.1, 0.1, p=0.5),),- K.ColorJitter(0.1, 0.1, 0.1, 0.1),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1),K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),K.RandomPerspective(0.2, p=0.5),K.RandomSolarize(0.1, 0.1, p=0.5),),- K.ColorJitter(0.1, 0.1, 0.1, 0.1),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1),**error_param,)@@ -624,9 +624,9 @@ class TestPatchSequential:try: # skip wrong param settings.seq = K.PatchSequential(K.color.RgbToBgr(),- K.ColorJitter(0.1, 0.1, 0.1, 0.1),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1),K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),K.RandomPerspective(0.2, p=0.5),K.RandomSolarize(0.1, 0.1, p=0.5),),@@ -653,26 +653,26 @@ class TestPatchSequential:def test_intensity_only(self):seq = K.PatchSequential(K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),K.RandomPerspective(0.2, p=0.5),K.RandomSolarize(0.1, 0.1, p=0.5),),- K.ColorJitter(0.1, 0.1, 0.1, 0.1),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1),K.ImageSequential(- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),K.RandomPerspective(0.2, p=0.5),K.RandomSolarize(0.1, 0.1, p=0.5),),- K.ColorJitter(0.1, 0.1, 0.1, 0.1),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1),grid_size=(2, 2),)assert not seq.is_intensity_only()seq = K.PatchSequential(- K.ImageSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5)),- K.ColorJitter(0.1, 0.1, 0.1, 0.1),- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),- K.ColorJitter(0.1, 0.1, 0.1, 0.1),+ K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5)),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1),grid_size=(2, 2),)assert seq.is_intensity_only()diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.pyindex 2f4ce1be4..76ee3a82a 100644--- a/test/augmentation/test_random_generator.py+++ b/test/augmentation/test_random_generator.py@@ -1,8 +1,10 @@import pytestimport torch+from torch import Tensorfrom kornia.augmentation.random_generator import (AffineGenerator,+ ColorJiggleGenerator,ColorJitterGenerator,CropGenerator,MotionBlurGenerator,@@ -71,6 +73,189 @@ class TestRandomProbGen(RandomGeneratorBaseTests):assert (res['probs'] == torch.tensor(expected)).long().sum() == batch_size+class TestColorJiggleGen(RandomGeneratorBaseTests):+ @pytest.mark.parametrize('brightness', [None, torch.tensor([0.8, 1.2])])+ @pytest.mark.parametrize('contrast', [None, torch.tensor([0.8, 1.2])])+ @pytest.mark.parametrize('saturation', [None, torch.tensor([0.8, 1.2])])+ @pytest.mark.parametrize('hue', [None, torch.tensor([-0.1, 0.1])])+ @pytest.mark.parametrize('batch_size', [0, 1, 8])+ @pytest.mark.parametrize('same_on_batch', [True, False])+ def test_valid_param_combinations(+ self, brightness, contrast, saturation, hue,+ batch_size, same_on_batch, device, dtype+ ):+ ColorJiggleGenerator(+ torch.as_tensor(+ brightness if brightness is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),+ torch.as_tensor(+ contrast if contrast is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),+ torch.as_tensor(+ saturation if saturation is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),+ torch.as_tensor(+ hue if hue is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),+ )(torch.Size([batch_size]), same_on_batch)++ @pytest.mark.parametrize(+ 'brightness,contrast,saturation,hue',+ [+ # Should be failed if value out of bounds or tensor.shape != [1, 2]+ (torch.tensor([-1.0, 2.0]), None, None, None),+ (torch.tensor([0.0, 3.0]), None, None, None),+ (torch.tensor([0.0]), None, None, None),+ (torch.tensor([0.0, 1.0, 2.0]), None, None, None),+ (None, torch.tensor([-1.0, 2.0]), None, None),+ (None, torch.tensor([0.0]), None, None),+ (None, torch.tensor([0.0, 1.0, 2.0]), None, None),+ (None, None, torch.tensor([-1.0, 2.0]), None),+ (None, None, torch.tensor([0.0]), None),+ (None, None, torch.tensor([0.0, 1.0, 2.0]), None),+ (None, None, None, torch.tensor([-1.0, 0.0])),+ (None, None, None, torch.tensor([0, 1.0])),+ (None, None, None, torch.tensor([0.0])),+ (None, None, None, torch.tensor([0.0, 1.0, 2.0])),+ ],+ )+ def test_invalid_param_combinations(+ self,+ brightness,+ contrast,+ saturation,+ hue,+ device,+ dtype+ ):+ with pytest.raises(Exception):+ ColorJiggleGenerator(+ torch.as_tensor(+ brightness if brightness is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),+ torch.as_tensor(+ contrast if contrast is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),+ torch.as_tensor(+ saturation if saturation is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),+ torch.as_tensor(hue if hue is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),+ )(torch.Size([8]))++ def test_random_gen(self, device, dtype):+ # TODO(jian): crashes with pytorch 1.10, cuda and fp64+ if torch_version_geq(1, 10) and "cuda" in str(device):+ pytest.skip("AssertionError: Tensor-likes are not close!")+ torch.manual_seed(42)+ batch_size = 8+ jitter_params = ColorJiggleGenerator(+ brightness=torch.tensor([0.8, 1.2], device=device, dtype=dtype),+ contrast=torch.tensor([0.7, 1.3], device=device, dtype=dtype),+ saturation=torch.tensor([0.6, 1.4], device=device, dtype=dtype),+ hue=torch.tensor([-0.1, 0.1], device=device, dtype=dtype),+ )(torch.Size([batch_size]))++ expected_jitter_params = {+ 'brightness_factor': torch.tensor(+ [1.1529, 1.1660, 0.9531, 1.1837, 0.9562, 1.0404, 0.9026, 1.1175], device=device, dtype=dtype+ ),+ 'contrast_factor': torch.tensor(+ [1.2645, 0.7799, 1.2608, 1.0561, 1.2216, 1.0406, 1.1447, 0.9576], device=device, dtype=dtype+ ),+ 'hue_factor': torch.tensor(+ [0.0771, 0.0148, -0.0467, 0.0255, -0.0461, -0.0117, -0.0406, 0.0663], device=device, dtype=dtype+ ),+ 'saturation_factor': torch.tensor(+ [0.6843, 0.8156, 0.8871, 0.7595, 1.0378, 0.6049, 1.3612, 0.6602], device=device, dtype=dtype+ ),+ 'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),+ }++ assert set(list(jitter_params.keys())) == {+ 'brightness_factor',+ 'contrast_factor',+ 'hue_factor',+ 'saturation_factor',+ 'order',+ }, "Redundant keys found apart from \+ 'brightness_factor', 'contrast_factor', 'hue_factor', 'saturation_factor', 'order'"++ assert_close(+ jitter_params['brightness_factor'], expected_jitter_params['brightness_factor'], rtol=1e-4, atol=1e-4+ )+ assert_close(jitter_params['contrast_factor'], expected_jitter_params['contrast_factor'], rtol=1e-4, atol=1e-4)+ assert_close(jitter_params['hue_factor'], expected_jitter_params['hue_factor'], rtol=1e-4, atol=1e-4)+ assert_close(+ jitter_params['saturation_factor'], expected_jitter_params['saturation_factor'], rtol=1e-4, atol=1e-4+ )+ assert_close(jitter_params['order'].to(dtype), expected_jitter_params['order'], rtol=1e-4, atol=1e-4)++ def test_random_gen_accumulative_additive_additive(self, device, dtype):+ # TODO(jian): crashes with pytorch 1.10, cuda and fp64+ if torch_version_geq(1, 10) and "cuda" in str(device):+ pytest.skip("AssertionError: Tensor-likes are not close!")+ torch.manual_seed(42)+ batch_size = 8+ jitter_params = ColorJiggleGenerator(+ brightness=torch.tensor([0.8, 1.2], device=device, dtype=dtype),+ contrast=torch.tensor([0.7, 1.3], device=device, dtype=dtype),+ saturation=torch.tensor([0.6, 1.4], device=device, dtype=dtype),+ hue=torch.tensor([-0.1, 0.1], device=device, dtype=dtype),+ )(torch.Size([batch_size]))++ expected_jitter_params = {+ 'brightness_factor': torch.tensor(+ [1.1529, 1.1660, 0.9531, 1.1837, 0.9562, 1.0404, 0.9026, 1.1175], device=device, dtype=dtype+ ),+ 'contrast_factor': torch.tensor(+ [1.2645, 0.7799, 1.2608, 1.0561, 1.2216, 1.0406, 1.1447, 0.9576], device=device, dtype=dtype+ ),+ 'hue_factor': torch.tensor(+ [0.0771, 0.0148, -0.0467, 0.0255, -0.0461, -0.0117, -0.0406, 0.0663], device=device, dtype=dtype+ ),+ 'saturation_factor': torch.tensor(+ [0.6843, 0.8156, 0.8871, 0.7595, 1.0378, 0.6049, 1.3612, 0.6602], device=device, dtype=dtype+ ),+ 'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),+ }++ assert set(list(jitter_params.keys())) == {+ 'brightness_factor',+ 'contrast_factor',+ 'hue_factor',+ 'saturation_factor',+ 'order',+ }, "Redundant keys found apart from \+ 'brightness_factor', 'contrast_factor', 'hue_factor', 'saturation_factor', 'order'"++ assert_close(+ jitter_params['brightness_factor'], expected_jitter_params['brightness_factor'], rtol=1e-4, atol=1e-4+ )+ assert_close(jitter_params['contrast_factor'], expected_jitter_params['contrast_factor'], rtol=1e-4, atol=1e-4)+ assert_close(jitter_params['hue_factor'], expected_jitter_params['hue_factor'], rtol=1e-4, atol=1e-4)+ assert_close(+ jitter_params['saturation_factor'], expected_jitter_params['saturation_factor'], rtol=1e-4, atol=1e-4+ )+ assert_close(jitter_params['order'].to(dtype), expected_jitter_params['order'], rtol=1e-4, atol=1e-4)++ def test_same_on_batch(self, device, dtype):+ torch.manual_seed(42)+ batch_size = 8+ jitter_params = ColorJiggleGenerator(+ brightness=torch.tensor([0.8, 1.2], device=device, dtype=dtype),+ contrast=torch.tensor([0.7, 1.3], device=device, dtype=dtype),+ saturation=torch.tensor([0.6, 1.4], device=device, dtype=dtype),+ hue=torch.tensor([-0.1, 0.1], device=device, dtype=dtype),+ )(torch.Size([batch_size]), same_on_batch=True)++ expected_res = {+ 'brightness_factor': torch.tensor([1.1529] * batch_size, device=device, dtype=dtype),+ 'contrast_factor': torch.tensor([1.2490] * batch_size, device=device, dtype=dtype),+ 'hue_factor': torch.tensor([-0.0234] * batch_size, device=device, dtype=dtype),+ 'saturation_factor': torch.tensor([1.3674] * batch_size, device=device, dtype=dtype),+ 'order': torch.tensor([2, 3, 0, 1], device=device, dtype=dtype),+ }++ assert_close(jitter_params['brightness_factor'], expected_res['brightness_factor'], rtol=1e-4, atol=1e-4)+ assert_close(jitter_params['contrast_factor'], expected_res['contrast_factor'], rtol=1e-4, atol=1e-4)+ assert_close(jitter_params['hue_factor'], expected_res['hue_factor'], rtol=1e-4, atol=1e-4)+ assert_close(jitter_params['saturation_factor'], expected_res['saturation_factor'], rtol=1e-4, atol=1e-4)+ assert_close(jitter_params['order'].to(dtype), expected_res['order'], rtol=1e-4, atol=1e-4)++class TestColorJitterGen(RandomGeneratorBaseTests):@pytest.mark.parametrize('brightness', [None, torch.tensor([0.8, 1.2])])@pytest.mark.parametrize('contrast', [None, torch.tensor([0.8, 1.2])])@@ -79,7 +264,8 @@ class TestColorJitterGen(RandomGeneratorBaseTests):@pytest.mark.parametrize('batch_size', [0, 1, 8])@pytest.mark.parametrize('same_on_batch', [True, False])def test_valid_param_combinations(- self, brightness, contrast, saturation, hue, batch_size, same_on_batch, device, dtype+ self, brightness, contrast, saturation, hue,+ batch_size, same_on_batch, device, dtype):ColorJitterGenerator(torch.as_tensor(@@ -97,7 +283,6 @@ class TestColorJitterGen(RandomGeneratorBaseTests):[# Should be failed if value out of bounds or tensor.shape != [1, 2](torch.tensor([-1.0, 2.0]), None, None, None),- (torch.tensor([0.0, 3.0]), None, None, None),(torch.tensor([0.0]), None, None, None),(torch.tensor([0.0, 1.0, 2.0]), None, None, None),(None, torch.tensor([-1.0, 2.0]), None, None),@@ -112,7 +297,15 @@ class TestColorJitterGen(RandomGeneratorBaseTests):(None, None, None, torch.tensor([0.0, 1.0, 2.0])),],)- def test_invalid_param_combinations(self, brightness, contrast, saturation, hue, device, dtype):+ def test_invalid_param_combinations(+ self,+ brightness,+ contrast,+ saturation,+ hue,+ device,+ dtype+ ):with pytest.raises(Exception):ColorJitterGenerator(torch.as_tensor(@@ -416,7 +609,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):@pytest.mark.parametrize('resize_to', [None, (100, 100)])@pytest.mark.parametrize('same_on_batch', [True, False])def test_valid_param_combinations(self, batch_size, input_size, size, resize_to, same_on_batch, device, dtype):- if isinstance(size, torch.Tensor):+ if isinstance(size, Tensor):size = size.repeat(batch_size, 1).to(device=device, dtype=dtype)CropGenerator(size, resize_to)(torch.Size([batch_size, 1, *input_size]), same_on_batch)@@ -428,7 +621,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):batch_size = 2with pytest.raises(Exception):CropGenerator(- size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size, resize_to+ size.to(device=device, dtype=dtype) if isinstance(size, Tensor) else size, resize_to)(torch.Size([batch_size, 1, *input_size]))def test_random_gen(self, device, dtype):@@ -803,7 +996,7 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):@pytest.mark.parametrize('bits', [(torch.tensor([-1, 1])), (torch.tensor([0, 9])), (torch.tensor([3])), ([0, 8],)])def test_invalid_param_combinations(self, bits, device, dtype):with pytest.raises(Exception):- if isinstance(bits, torch.Tensor):+ if isinstance(bits, Tensor):PosterizeGenerator(bits.to(device=device, dtype=dtype))(torch.Size([3]))else:PosterizeGenerator(bits)(torch.Size([3]))@@ -883,7 +1076,7 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):batch_size=batch_size,p=p,lambda_val=lambda_val.to(device=device, dtype=dtype)- if isinstance(lambda_val, (torch.Tensor))+ if isinstance(lambda_val, (Tensor))else lambda_val,same_on_batch=same_on_batch,)@@ -951,8 +1144,8 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):width=width,height=height,num_mix=num_mix,- beta=beta.to(device=device, dtype=dtype) if isinstance(beta, (torch.Tensor)) else beta,- cut_size=cut_size.to(device=device, dtype=dtype) if isinstance(cut_size, (torch.Tensor)) else cut_size,+ beta=beta.to(device=device, dtype=dtype) if isinstance(beta, (Tensor)) else beta,+ cut_size=cut_size.to(device=device, dtype=dtype) if isinstance(cut_size, (Tensor)) else cut_size,same_on_batch=same_on_batch,)@@ -977,8 +1170,8 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):width=width,height=height,num_mix=num_mix,- beta=beta.to(device=device, dtype=dtype) if isinstance(beta, (torch.Tensor)) else beta,- cut_size=beta.to(device=device, dtype=dtype) if isinstance(cut_size, (torch.Tensor)) else cut_size,+ beta=beta.to(device=device, dtype=dtype) if isinstance(beta, (Tensor)) else beta,+ cut_size=beta.to(device=device, dtype=dtype) if isinstance(cut_size, (Tensor)) else cut_size,same_on_batch=same_on_batch,)diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.pyindex 25de4fabe..44697a78d 100644--- a/test/enhance/test_adjust.py+++ b/test/enhance/test_adjust.py@@ -1,5 +1,6 @@import pytestimport torch+from torch import Tensorfrom torch.autograd import gradcheckimport kornia@@ -60,6 +61,12 @@ class TestAdjustSaturation:out = kornia.enhance.adjust_saturation(img, 1.0)assert out.shape == shape+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 3, 3), (4, 3, 3, 1, 1)])+ def test_cardinality_with_gray_subtraction(self, device, dtype, shape):+ img = torch.rand(shape, device=device, dtype=dtype)+ out = kornia.enhance.adjust_saturation_with_gray_subtraction(img, 1.0)+ assert out.shape == shape+def test_saturation_one(self, device, dtype):data = torch.tensor([[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],@@ -72,6 +79,18 @@ class TestAdjustSaturation:f = kornia.enhance.AdjustSaturation(1.0)assert_close(f(data), expected)+ def test_saturation_with_gray_subtraction_one(self, device, dtype):+ data = torch.tensor(+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],+ device=device,+ dtype=dtype,+ ) # 3x2x2++ expected = data.clone()++ f = kornia.enhance.AdjustSaturationWithGraySubtraction(1.0)+ assert_close(f(data), expected)+def test_saturation_one_batch(self, device, dtype):data = torch.tensor([@@ -86,12 +105,34 @@ class TestAdjustSaturation:f = kornia.enhance.AdjustSaturation(torch.ones(2))assert_close(f(data), expected)+ def test_saturation_with_gray_subtraction_one_batch(self, device, dtype):+ data = torch.tensor(+ [+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],+ ],+ device=device,+ dtype=dtype,+ ) # 2x3x2x2++ expected = data+ f = kornia.enhance.AdjustSaturationWithGraySubtraction(torch.ones(2))+ assert_close(f(data), expected)+def test_gradcheck(self, device, dtype):batch_size, channels, height, width = 2, 3, 4, 5img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)img = tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.enhance.adjust_saturation, (img, 2.0), raise_exception=True)+ def test_gradcheck_with_gray_subtraction(self, device, dtype):+ batch_size, channels, height, width = 2, 3, 4, 5+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)+ img = tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.enhance.adjust_saturation_with_gray_subtraction,+ (img, 2.0),+ raise_exception=True)+class TestAdjustHue:@pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 3, 3), (4, 3, 3, 1, 1)])@@ -249,6 +290,12 @@ class TestAdjustContrast:out = kornia.enhance.adjust_contrast(img, 0.5)assert out.shape == shape+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 3, 3), (4, 3, 3, 1, 1)])+ def test_cardinality_with_mean_subtraction(self, device, dtype, shape):+ img = torch.rand(shape, device=device, dtype=dtype)+ out = kornia.enhance.adjust_contrast_with_mean_subtraction(img, 0.5)+ assert out.shape == shape+def test_factor_zero(self, device, dtype):# prepare input datadata = torch.tensor(@@ -262,7 +309,25 @@ class TestAdjustContrast:f = kornia.enhance.AdjustContrast(0.0)assert_close(f(data), expected)- def test_factor_one(self, device, dtype):+ def test_factor_zero_with_mean_subtraction(self, device, dtype):+ # prepare input data+ data = torch.tensor(+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],+ device=device,+ dtype=dtype,+ ) # 3x2x2++ expected = torch.tensor(+ [[[0.6210, 0.6210], [0.6210, 0.6210]], [[0.6210, 0.6210], [0.6210, 0.6210]],+ [[0.6210, 0.6210], [0.6210, 0.6210]]],+ device=device,+ dtype=dtype,+ ) # 3x2x2++ f = kornia.enhance.AdjustContrastWithMeanSubtraction(0.0)+ assert_close(f(data), expected)++ def test_factor_one_acumulative(self, device, dtype):# prepare input datadata = torch.tensor([[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],@@ -275,6 +340,19 @@ class TestAdjustContrast:f = kornia.enhance.AdjustContrast(1.0)assert_close(f(data), expected)+ def test_factor_one_with_mean_subtraction(self, device, dtype):+ # prepare input data+ data = torch.tensor(+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],+ device=device,+ dtype=dtype,+ ) # 3x2x2++ expected = data.clone()++ f = kornia.enhance.AdjustContrastWithMeanSubtraction(1.0)+ assert_close(f(data), expected)+def test_factor_two(self, device, dtype):# prepare input datadata = torch.tensor(@@ -290,6 +368,24 @@ class TestAdjustContrast:f = kornia.enhance.AdjustContrast(2.0)assert_close(f(data), expected)+ def test_factor_two_with_mean_subtraction(self, device, dtype):+ # prepare input data+ data = torch.tensor(+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],+ device=device,+ dtype=dtype,+ ) # 3x2x2++ expected = torch.tensor(+ [[[1.0000, 1.0000], [1.0000, 1.0000]], [[0.3790, 0.3790], [0.3790, 0.3790]],+ [[0.0000, 0.0000], [0.0000, 0.0000]]],+ device=device,+ dtype=dtype+ ) # 3x2x2++ f = kornia.enhance.AdjustContrastWithMeanSubtraction(2.0)+ assert_close(f(data), expected)+def test_factor_tensor(self, device, dtype):# prepare input datadata = torch.tensor(@@ -344,6 +440,31 @@ class TestAdjustContrast:f = kornia.enhance.AdjustContrast(factor)assert_close(f(data), expected)+ def test_factor_tensor_color_with_mean_subtraction(self, device, dtype):+ # prepare input data+ data = torch.tensor(+ [+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],+ [[[0.0, 0.0], [0.0, 0.0]], [[0.3, 0.3], [0.3, 0.3]], [[0.6, 0.6], [0.6, 0.6]]],+ ],+ device=device,+ dtype=dtype,+ ) # 2x3x2x2++ expected = torch.tensor(+ [+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],+ [[[0.0, 0.0], [0.0, 0.0]], [[0.3555, 0.3555], [0.3555, 0.3555]], [[0.9555, 0.9555], [0.9555, 0.9555]]],+ ],+ device=device,+ dtype=dtype,+ ) # 2x3x2x2++ factor = torch.tensor([1, 2], device=device, dtype=dtype)++ f = kornia.enhance.AdjustContrastWithMeanSubtraction(factor)+ assert_close(f(data), expected)+def test_factor_tensor_shape(self, device, dtype):# prepare input datadata = torch.tensor(@@ -385,71 +506,59 @@ class TestAdjustContrast:f = kornia.enhance.AdjustContrast(factor)assert_close(f(data), expected)- def test_gradcheck(self, device, dtype):- batch_size, channels, height, width = 2, 3, 4, 5- img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)- img = tensor_to_gradcheck_var(img) # to var- assert gradcheck(kornia.enhance.adjust_contrast, (img, 2.0), raise_exception=True)-- def test_factor_one_rgb(self, device, dtype):+ def test_factor_tensor_shape_with_mean_subtraction(self, device, dtype):# prepare input datadata = torch.tensor(- [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],- device=device,- dtype=dtype,- ) # 3x2x2-- expected = torch.tensor(- [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],- device=device,- dtype=dtype,- ) # 3x2x2-- f = kornia.enhance.adjust_contrast_with_mean_subtraction- assert_close(f(data, 1.0), expected)-- def test_factor_zero_rgb(self, device, dtype):- # prepare input data- data = torch.tensor(- [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],+ [+ [+ [[1.0, 1.0, 0.5], [1.0, 1.0, 0.5]],+ [[0.5, 0.5, 0.25], [0.5, 0.5, 0.25]],+ [[0.25, 0.25, 0.25], [0.6, 0.6, 0.3]],+ ],+ [+ [[0.0, 0.0, 1.0], [0.0, 0.0, 0.25]],+ [[0.3, 0.3, 0.4], [0.3, 0.3, 0.4]],+ [[0.6, 0.6, 0.0], [0.3, 0.2, 0.1]],+ ],+ ],device=device,dtype=dtype,- ) # 3x2x2+ ) # 2x3x2x3expected = torch.tensor([- [[0.6210, 0.6210], [0.6210, 0.6210]],- [[0.6210, 0.6210], [0.6210, 0.6210]],- [[0.6210, 0.6210], [0.6210, 0.6210]],+ [+ [[1.0000, 1.0000, 0.4818], [1.0000, 1.0000, 0.4818]],+ [[0.4818, 0.4818, 0.1068], [0.4818, 0.4818, 0.1068]],+ [[0.1068, 0.1068, 0.1068], [0.6318, 0.6318, 0.1818]]+ ],+ [+ [[0.0000, 0.0000, 1.0000], [0.0000, 0.0000, 0.2079]],+ [[0.3079, 0.3079, 0.5079], [0.3079, 0.3079, 0.5079]],+ [[0.9079, 0.9079, 0.0000], [0.3079, 0.1079, 0.0000]]+ ],],device=device,dtype=dtype,- ) # 3x2x2+ ) # 2x3x2x3- f = kornia.enhance.adjust_contrast_with_mean_subtraction- assert_close(f(data, 0.0), expected)+ factor = torch.tensor([1.5, 2.0], device=device, dtype=dtype)- def test_factor_zero_nchannels(self, device, dtype):- # prepare input data- data = torch.tensor(- [- [[1.0, 1.0], [1.0, 1.0]],- [[0.5, 0.5], [0.5, 0.5]],- [[0.25, 0.25], [0.25, 0.25]],- [[0.25, 0.25], [0.25, 0.25]],- ],- device=device,- dtype=dtype,- ) # 3x2x2+ f = kornia.enhance.AdjustContrastWithMeanSubtraction(factor)- expected = torch.tensor(- [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]]],- device=device,- dtype=dtype,- ) # 3x2x2+ assert_close(f(data), expected, rtol=1e-4, atol=1e-4)- f = kornia.enhance.adjust_contrast_with_mean_subtraction- assert_close(f(data, 0.0), expected)+ def test_gradcheck(self, device, dtype):+ batch_size, channels, height, width = 2, 3, 4, 5+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)+ img = tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.enhance.adjust_contrast, (img, 2.0), raise_exception=True)++ def test_gradcheck_with_mean_subtraction(self, device, dtype):+ batch_size, channels, height, width = 2, 3, 4, 5+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)+ img = tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.enhance.adjust_contrast_with_mean_subtraction, (img, 2.0), raise_exception=True)class TestAdjustBrightness:@@ -486,12 +595,47 @@ class TestAdjustBrightness:out = kornia.enhance.adjust_brightness(data, factor)assert out.shape == (channels, 2, 3)- def test_gradcheck(self, device, dtype):+ def test_factor_tensor_color_accumulative(self, device, dtype):+ # prepare input data+ data = torch.tensor(+ [+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],+ [[[0.0, 0.0], [0.0, 0.0]], [[0.3, 0.3], [0.3, 0.3]], [[0.6, 0.6], [0.6, 0.6]]],+ ],+ device=device,+ dtype=dtype,+ ) # 2x3x2x2++ expected = torch.tensor(+ [+ [[[0.2500, 0.2500], [0.2500, 0.2500]], [[0.1250, 0.1250], [0.1250, 0.1250]],+ [[0.0625, 0.0625], [0.0625, 0.0625]]],+ [[[0.0000, 0.0000], [0.0000, 0.0000]], [[0.0300, 0.0300], [0.0300, 0.0300]],+ [[0.0600, 0.0600], [0.0600, 0.0600]]]+ ],+ device=device,+ dtype=dtype,+ ) # 2x3x2x2++ factor = torch.tensor([0.25, 0.1], device=device, dtype=dtype)++ f = kornia.enhance.AdjustBrightnessAccumulative(factor)+ assert_close(f(data), expected)++ def test_gradcheck_additive(self, device, dtype):batch_size, channels, height, width = 2, 3, 4, 5img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)img = tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.enhance.adjust_brightness, (img, 1.0), raise_exception=True)+ def test_gradcheck_accumulative(self, device, dtype):+ batch_size, channels, height, width = 2, 3, 4, 5+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)+ img = tensor_to_gradcheck_var(img) # to var+ assert gradcheck(kornia.enhance.adjust_brightness_accumulative,+ (img, 2.0),+ raise_exception=True)+class TestEqualize:@pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 4, 4), (3, 2, 3, 3, 4, 4)])@@ -698,7 +842,7 @@ class TestSharpness(BaseTester):def test_smoke(self, device, dtype):B, C, H, W = 2, 3, 4, 5img = torch.rand(B, C, H, W, device=device, dtype=dtype)- assert isinstance(TestSharpness.f(img, 0.8), torch.Tensor)+ assert isinstance(TestSharpness.f(img, 0.8), Tensor)@pytest.mark.parametrize("shape", [(1, 1, 4, 5), (2, 3, 4, 5), (2, 5, 4, 5), (4, 5), (5, 4, 5), (2, 3, 2, 3, 4, 5)])@pytest.mark.parametrize("factor", [0.7, 0.8])@@ -804,7 +948,7 @@ class TestSolarize(BaseTester):def test_smoke(self, device, dtype):B, C, H, W = 2, 3, 4, 5img = torch.rand(B, C, H, W, device=device, dtype=dtype)- assert isinstance(TestSolarize.f(img, 0.8), torch.Tensor)+ assert isinstance(TestSolarize.f(img, 0.8), Tensor)@pytest.mark.parametrize("shape, thresholds, additions",@@ -895,7 +1039,7 @@ class TestPosterize(BaseTester):def test_smoke(self, device, dtype):B, C, H, W = 2, 3, 4, 5img = torch.rand(B, C, H, W, device=device, dtype=dtype)- assert isinstance(TestPosterize.f(img, 8), torch.Tensor)+ assert isinstance(TestPosterize.f(img, 8), Tensor)@pytest.mark.parametrize("shape, bits",