π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add `RandomPlanckianJitter` in color augmentations (#1607)
Nrupatungafa2a5a8b39b4
diff --git a/docs/generate_example_images.py b/docs/generate_example_images.pyindex 3a66e4c74..4aa9aadd4 100644--- a/docs/generate_example_images.py+++ b/docs/generate_example_images.py@@ -71,6 +71,7 @@ def main():"RandomInvert": ((), 1, 2020),"RandomMotionBlur": ((7, 35.0, 0.5), 2, 2020),"RandomPerspective": ((0.2,), 2, 2020),+ "RandomPlanckianJitter": ((), 2, 2022),"RandomPosterize": (((1, 4),), 2, 2016),"RandomResizedCrop": ((img1.shape[-2:], (1.0, 2.0), (1.0, 2.0)), 2, 2020),"RandomRotation": ((45.0,), 2, 2019),diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex 37b26533a..8ecaec6f3 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -25,6 +25,7 @@ Set of operators to perform data augmentation on 2D image tensors... autoclass:: RandomMixUp.. autoclass:: RandomMotionBlur.. autoclass:: RandomPerspective+.. autoclass:: RandomPlanckianJitter.. autoclass:: RandomPosterize.. autoclass:: RandomResizedCrop.. autoclass:: RandomRotationdiff --git a/docs/source/references.bib b/docs/source/references.bibindex a2ba874ca..ed2d408a2 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -191,3 +191,10 @@volume={12544},pages={432 - 444}}++@article{zini2022planckian,+ title={Planckian jitter: enhancing the color quality of self-supervised visual representations},+ author={Zini, Simone and Buzzelli, Marco and Twardowski, Bart{\l}omiej and van de Weijer, Joost},+ journal={arXiv preprint arXiv:2202.07993},+ year={2022}+}diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.pyindex d0b4fbc65..6be83be13 100644--- a/kornia/augmentation/_2d/intensity/__init__.py+++ b/kornia/augmentation/_2d/intensity/__init__.py@@ -10,6 +10,7 @@ from kornia.augmentation._2d.intensity.grayscale import RandomGrayscalefrom kornia.augmentation._2d.intensity.invert import RandomInvertfrom kornia.augmentation._2d.intensity.motion_blur import RandomMotionBlurfrom kornia.augmentation._2d.intensity.normalize import Normalize+from kornia.augmentation._2d.intensity.planckian_jitter import RandomPlanckianJitterfrom kornia.augmentation._2d.intensity.posterize import RandomPosterizefrom kornia.augmentation._2d.intensity.sharpness import RandomSharpnessfrom kornia.augmentation._2d.intensity.solarize import RandomSolarizediff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.pynew file mode 100644index 000000000..1a3345c90--- /dev/null+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py@@ -0,0 +1,189 @@+from typing import Dict, List, Optional, Union, cast++from torch import Tensor, stack++from kornia.augmentation import random_generator as rg+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D++_planckian_coeffs = {+ 'blackbody': Tensor(+ [+ [0.6743, 0.4029, 0.0013],+ [0.6281, 0.4241, 0.1665],+ [0.5919, 0.4372, 0.2513],+ [0.5623, 0.4457, 0.3154],+ [0.5376, 0.4515, 0.3672],+ [0.5163, 0.4555, 0.4103],+ [0.4979, 0.4584, 0.4468],+ [0.4816, 0.4604, 0.4782],+ [0.4672, 0.4619, 0.5053],+ [0.4542, 0.4630, 0.5289],+ [0.4426, 0.4638, 0.5497],+ [0.4320, 0.4644, 0.5681],+ [0.4223, 0.4648, 0.5844],+ [0.4135, 0.4651, 0.5990],+ [0.4054, 0.4653, 0.6121],+ [0.3980, 0.4654, 0.6239],+ [0.3911, 0.4655, 0.6346],+ [0.3847, 0.4656, 0.6444],+ [0.3787, 0.4656, 0.6532],+ [0.3732, 0.4656, 0.6613],+ [0.3680, 0.4655, 0.6688],+ [0.3632, 0.4655, 0.6756],+ [0.3586, 0.4655, 0.6820],+ [0.3544, 0.4654, 0.6878],+ [0.3503, 0.4653, 0.6933],+ ]+ ),+ 'CIED': Tensor(+ [+ [0.5829, 0.4421, 0.2288],+ [0.5510, 0.4514, 0.2948],+ [0.5246, 0.4576, 0.3488],+ [0.5021, 0.4618, 0.3941],+ [0.4826, 0.4646, 0.4325],+ [0.4654, 0.4667, 0.4654],+ [0.4502, 0.4681, 0.4938],+ [0.4364, 0.4692, 0.5186],+ [0.4240, 0.4700, 0.5403],+ [0.4127, 0.4705, 0.5594],+ [0.4023, 0.4709, 0.5763],+ [0.3928, 0.4713, 0.5914],+ [0.3839, 0.4715, 0.6049],+ [0.3757, 0.4716, 0.6171],+ [0.3681, 0.4717, 0.6281],+ [0.3609, 0.4718, 0.6380],+ [0.3543, 0.4719, 0.6472],+ [0.3480, 0.4719, 0.6555],+ [0.3421, 0.4719, 0.6631],+ [0.3365, 0.4719, 0.6702],+ [0.3313, 0.4719, 0.6766],+ [0.3263, 0.4719, 0.6826],+ [0.3217, 0.4719, 0.6882],+ ]+ ),+}++_planckian_coeffs_ratio = {+ 'blackbody': stack(+ (+ _planckian_coeffs['blackbody'][:, 0] / _planckian_coeffs['blackbody'][:, 1],+ _planckian_coeffs['blackbody'][:, 2] / _planckian_coeffs['blackbody'][:, 1],+ ),+ 1,+ ),+ 'CIED': stack(+ (+ _planckian_coeffs['CIED'][:, 0] / _planckian_coeffs['CIED'][:, 1],+ _planckian_coeffs['CIED'][:, 2] / _planckian_coeffs['CIED'][:, 1],+ ),+ 1,+ ),+}+++class RandomPlanckianJitter(IntensityAugmentationBase2D):+ r"""Apply planckian jitter transformation to input tensor.++ .. image:: _static/img/RandomPlanckianJitter.png++ This is physics based color augmentation, that creates realistic+ variations in chromaticity, this can simulate the illumination+ changes in the scene.++ See :cite:`zini2022planckian` for more details.++ Args:+ mode: 'blackbody' or 'CIED'.+ select_from: choose a list of jitters to apply from. `blackbody` range [0-24], `CIED` range [0-22]+ same_on_batch: apply the same transformation across the batch.+ p: probability that the random erasing operation will be performed.+ 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)`+ - Output: :math:`(B, C, H, W)`++ Note:+ Input tensor must be float and normalized into [0, 1].++ Examples:+ To apply planckian jitter based on mode+ >>> rng = torch.manual_seed(0)+ >>> input = torch.randn(1, 3, 2, 2)+ >>> aug = RandomPlanckianJitter(mode='CIED')+ >>> aug(input)+ tensor([[[[ 1.0000, -0.2389],+ [-1.7740, 0.4628]],+ <BLANKLINE>+ [[-1.0845, -1.3986],+ [ 0.4033, 0.8380]],+ <BLANKLINE>+ [[-0.9228, -0.5175],+ [-0.7654, 0.2335]]]])++ To apply planckian jitter on image(s) from list of interested jitters+ >>> rng = torch.manual_seed(0)+ >>> input = torch.randn(2, 3, 2, 2)+ >>> aug = RandomPlanckianJitter(mode='blackbody', select_from=[23, 24, 1, 2])+ >>> aug(input)+ tensor([[[[-1.1258, -1.1524],+ [-0.2506, -0.4339]],+ <BLANKLINE>+ [[ 0.8487, 0.6920],+ [-0.3160, -2.1152]],+ <BLANKLINE>+ [[ 0.4681, -0.1577],+ [ 1.4437, 0.2660]]],+ <BLANKLINE>+ <BLANKLINE>+ [[[ 0.2465, 1.0000],+ [-0.2125, -0.1653]],+ <BLANKLINE>+ [[ 0.9318, 1.0000],+ [ 1.0000, 0.0537]],+ <BLANKLINE>+ [[ 0.2426, -0.1621],+ [-0.3302, -0.9093]]]])+ """++ def __init__(+ self,+ mode: str = "blackbody",+ select_from: Optional[Union[int, List[int]]] = None,+ same_on_batch: bool = False,+ p: float = 0.5,+ 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)++ if isinstance(select_from, int):+ select_from = [select_from]++ if select_from is not None:+ self.register_buffer('pl', _planckian_coeffs_ratio[mode][select_from])+ else:+ self.register_buffer('pl', _planckian_coeffs_ratio[mode])++ # the range of the sampling parameters+ _param_min: float = 0.0+ _param_max: float = float(cast(Tensor, self.pl).shape[0])++ self._param_generator = cast(rg.PlanckianJitterGenerator, rg.PlanckianJitterGenerator([_param_min, _param_max]))++ def apply_transform(self, input: Tensor, params: Dict[str, Tensor], transform: Optional[Tensor] = None) -> Tensor:++ list_idx = params['idx'].tolist()+ coeffs = cast(Tensor, self.pl)[list_idx]++ r_w = coeffs[:, 0][..., None, None]+ b_w = coeffs[:, 1][..., None, None]++ r = input[..., 0, :, :] * r_w+ g = input[..., 1, :, :]+ b = input[..., 2, :, :] * b_w++ output = stack([r, g, b], -3)++ return output.clamp(max=1.0)diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex a719122f5..20acd8084 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -22,6 +22,7 @@ from kornia.augmentation._2d import (RandomMixUp,RandomMotionBlur,RandomPerspective,+ RandomPlanckianJitter,RandomPosterize,RandomResizedCrop,RandomRotation,@@ -75,6 +76,7 @@ __all__ = ["RandomHorizontalFlip","RandomVerticalFlip","RandomPerspective",+ "RandomPlanckianJitter","RandomResizedCrop","RandomRotation","RandomSolarize",diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.pyindex a790b7129..1a7a20ec4 100644--- a/kornia/augmentation/random_generator/_2d/__init__.py+++ b/kornia/augmentation/random_generator/_2d/__init__.py@@ -7,6 +7,7 @@ from kornia.augmentation.random_generator._2d.mixup import *from kornia.augmentation.random_generator._2d.motion_blur import *from kornia.augmentation.random_generator._2d.perspective import *from kornia.augmentation.random_generator._2d.plain_uniform import *+from kornia.augmentation.random_generator._2d.planckian_jitter import *from kornia.augmentation.random_generator._2d.posterize import *from kornia.augmentation.random_generator._2d.probability import *from kornia.augmentation.random_generator._2d.rectangle_earase import *diff --git a/kornia/augmentation/random_generator/_2d/planckian_jitter.py b/kornia/augmentation/random_generator/_2d/planckian_jitter.pynew file mode 100644index 000000000..23ad5c394--- /dev/null+++ b/kornia/augmentation/random_generator/_2d/planckian_jitter.py@@ -0,0 +1,36 @@+from typing import Dict, List++import torch+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+++class PlanckianJitterGenerator(RandomGeneratorBase):++ r"""Generate random planckian jitter parameters for a batch of images+ """++ def __init__(self, domain: List[float]) -> None:+ super().__init__()+ self.domain = domain++ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:++ idx_range = _range_bound(self.domain,+ 'idx_range',+ device=device, dtype=dtype)++ _joint_range_check(idx_range, 'idx_range', (0, self.domain[1]))+ self.pl_idx_dist = Uniform(idx_range[0], idx_range[1], validate_args=False)++ def forward(self, batch_shape: torch.Size, same_on_batch: bool =+ False) -> Dict[str, torch.Tensor]:+ batch_size = batch_shape[0]+ _common_param_check(batch_size, same_on_batch)+ pl_idx = _adapted_rsampling((batch_size,),+ self.pl_idx_dist,+ same_on_batch)++ return dict(idx=pl_idx.long())diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex 472807cac..192d3d6bb 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -26,6 +26,7 @@ from kornia.augmentation import (RandomGrayscale,RandomHorizontalFlip,RandomInvert,+ RandomPlanckianJitter,RandomPosterize,RandomResizedCrop,RandomRotation,@@ -2551,3 +2552,160 @@ class TestRandomPosterize:aug = RandomPosterize(bits=6, p=1.0).to(device)out = aug(img)assert out.shape == (1, 1, 4, 5)+++class TestPlanckianJitter:++ def _get_expected_output_blackbody(self, device, dtype):+ return torch.tensor([[[[0.7350, 1.0000, 0.1311, 0.1955],+ [0.4553, 0.9391, 0.7258, 1.0000],+ [0.6748, 0.9364, 0.5167, 0.5949],+ [0.0330, 0.2501, 0.4353, 0.7679]],++ [[0.6977, 0.8000, 0.1610, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742],+ [0.4194, 0.5529, 0.9527, 0.0362],+ [0.1852, 0.3734, 0.3051, 0.9320]],++ [[0.0691, 0.1059, 0.0592, 0.0124],+ [0.0817, 0.3650, 0.2839, 0.2914],+ [0.2066, 0.0957, 0.2295, 0.0130],+ [0.0545, 0.0951, 0.3202, 0.3114]]]],+ device=device,+ dtype=dtype)++ def _get_expected_output_cied(self, device, dtype):+ return torch.tensor([[[[0.6058, 0.9377, 0.1080, 0.1611],+ [0.3752, 0.7740, 0.5982, 1.0000],+ [0.5561, 0.7718, 0.4259, 0.4903],+ [0.0272, 0.2062, 0.3587, 0.6329]],++ [[0.6977, 0.8000, 0.1610, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742],+ [0.4194, 0.5529, 0.9527, 0.0362],+ [0.1852, 0.3734, 0.3051, 0.9320]],++ [[0.1149, 0.1762, 0.0984, 0.0207],+ [0.1359, 0.6072, 0.4722, 0.4848],+ [0.3437, 0.1592, 0.3818, 0.0217],+ [0.0906, 0.1582, 0.5326, 0.5180]]]],+ device=device,+ dtype=dtype)++ def _get_expected_output_batch(self, device, dtype):+ return torch.tensor([[[[0.7350, 1.0000, 0.1311, 0.1955],+ [0.4553, 0.9391, 0.7258, 1.0000],+ [0.6748, 0.9364, 0.5167, 0.5949],+ [0.0330, 0.2501, 0.4353, 0.7679]],++ [[0.6977, 0.8000, 0.1610, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742],+ [0.4194, 0.5529, 0.9527, 0.0362],+ [0.1852, 0.3734, 0.3051, 0.9320]],++ [[0.0691, 0.1059, 0.0592, 0.0124],+ [0.0817, 0.3650, 0.2839, 0.2914],+ [0.2066, 0.0957, 0.2295, 0.0130],+ [0.0545, 0.0951, 0.3202, 0.3114]]],+++ [[[0.4963, 0.7682, 0.0885, 0.1320],+ [0.3074, 0.6341, 0.4901, 0.8964],+ [0.4556, 0.6323, 0.3489, 0.4017],+ [0.0223, 0.1689, 0.2939, 0.5185]],++ [[0.6977, 0.8000, 0.1610, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742],+ [0.4194, 0.5529, 0.9527, 0.0362],+ [0.1852, 0.3734, 0.3051, 0.9320]],++ [[0.1759, 0.2698, 0.1507, 0.0317],+ [0.2081, 0.9298, 0.7231, 0.7423],+ [0.5263, 0.2437, 0.5846, 0.0332],+ [0.1387, 0.2422, 0.8155, 0.7932]]]],+ device=device,+ dtype=dtype)++ def _get_expected_output_same_on_batch(self, device, dtype):+ return torch.tensor([[[[0.3736, 0.5783, 0.0666, 0.0994],+ [0.2314, 0.4774, 0.3690, 0.6749],+ [0.3430, 0.4760, 0.2627, 0.3024],+ [0.0168, 0.1272, 0.2213, 0.3904]],++ [[0.6977, 0.8000, 0.1610, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742],+ [0.4194, 0.5529, 0.9527, 0.0362],+ [0.1852, 0.3734, 0.3051, 0.9320]],++ [[0.2621, 0.4020, 0.2245, 0.0472],+ [0.3101, 1.0000, 1.0000, 1.0000],+ [0.7842, 0.3631, 0.8711, 0.0495],+ [0.2067, 0.3609, 1.0000, 1.0000]]],+++ [[[0.3736, 0.5783, 0.0666, 0.0994],+ [0.2314, 0.4774, 0.3690, 0.6749],+ [0.3430, 0.4760, 0.2627, 0.3024],+ [0.0168, 0.1272, 0.2213, 0.3904]],++ [[0.6977, 0.8000, 0.1610, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742],+ [0.4194, 0.5529, 0.9527, 0.0362],+ [0.1852, 0.3734, 0.3051, 0.9320]],++ [[0.2621, 0.4020, 0.2245, 0.0472],+ [0.3101, 1.0000, 1.0000, 1.0000],+ [0.7842, 0.3631, 0.8711, 0.0495],+ [0.2067, 0.3609, 1.0000, 1.0000]]]],+ device=device,+ dtype=dtype)++ def _get_input(self, device, dtype):+ return torch.tensor([[[[0.4963, 0.7682, 0.0885, 0.1320],+ [0.3074, 0.6341, 0.4901, 0.8964],+ [0.4556, 0.6323, 0.3489, 0.4017],+ [0.0223, 0.1689, 0.2939, 0.5185]],++ [[0.6977, 0.8000, 0.1610, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742],+ [0.4194, 0.5529, 0.9527, 0.0362],+ [0.1852, 0.3734, 0.3051, 0.9320]],++ [[0.1759, 0.2698, 0.1507, 0.0317],+ [0.2081, 0.9298, 0.7231, 0.7423],+ [0.5263, 0.2437, 0.5846, 0.0332],+ [0.1387, 0.2422, 0.8155, 0.7932]]]],+ device=device, dtype=dtype)++ def test_planckian_jitter_blackbody(self, device, dtype):+ torch.manual_seed(0)+ f = RandomPlanckianJitter(select_from=1).to(device, dtype)+ input = self._get_input(device, dtype)+ expected = self._get_expected_output_blackbody(device, dtype)+ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)++ def test_planckian_jitter_cied(self, device, dtype):+ torch.manual_seed(0)+ f = RandomPlanckianJitter(mode='CIED', select_from=1).to(device, dtype)+ input = self._get_input(device, dtype)+ expected = self._get_expected_output_cied(device, dtype)+ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)++ def test_planckian_jitter_batch(self, device, dtype):+ torch.manual_seed(0)+ input = self._get_input(device, dtype).repeat(2, 1, 1, 1)++ select_from = [1, 2, 24]+ f = RandomPlanckianJitter(select_from=select_from).to(device, dtype)+ expected = self._get_expected_output_batch(device, dtype)+ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)++ def test_planckian_jitter_same_on_batch(self, device, dtype):+ torch.manual_seed(0)+ input = self._get_input(device, dtype).repeat(2, 1, 1, 1)++ select_from = [1, 2, 24, 3, 4, 5]+ f = RandomPlanckianJitter(select_from=select_from, same_on_batch=True,+ p=1.0).to(device, dtype)+ expected = self._get_expected_output_same_on_batch(device, dtype)+ assert_close(f(input), expected, atol=1e-4, rtol=1e-5)