Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat: Add RandomJPEG Augmentation (#2803)

Christoph Reich0857d1fdc158
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index e402fcffe..772c01748 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -149,6 +149,7 @@ def main():
"RandomHue": (((-0.5, 0.5),), 2, 2022),
"RandomHorizontalFlip": ((), 1, 2020),
"RandomInvert": ((), 1, 2020),
+ "RandomJPEG": (((1.0, 5.0),), 1, 2024),
"RandomMedianBlur": (((3, 3),), 1, 2023),
"RandomMotionBlur": ((7, 35.0, 0.5), 2, 2020),
"RandomPerspective": ((0.2,), 2, 2020),
@@ -182,6 +183,8 @@ def main():
torch.manual_seed(seed)
if aug_name == "RandomJigsaw": # make sure the image is dividable
img_in = K.geometry.resize(img_in, (1020, 500))
+ elif aug_name == "RandomJPEG":
+ img_in = img_in[..., :176, :]
# apply the augmentation to the image and concat
out = aug(img_in)
diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.py
index 5b6b4ba13..2c6fb82ab 100644
--- a/kornia/augmentation/_2d/intensity/__init__.py
+++ b/kornia/augmentation/_2d/intensity/__init__.py
@@ -16,6 +16,7 @@ from kornia.augmentation._2d.intensity.gaussian_noise import RandomGaussianNoise
from kornia.augmentation._2d.intensity.grayscale import RandomGrayscale
from kornia.augmentation._2d.intensity.hue import RandomHue
from kornia.augmentation._2d.intensity.invert import RandomInvert
+from kornia.augmentation._2d.intensity.jpeg import RandomJPEG
from kornia.augmentation._2d.intensity.median_blur import RandomMedianBlur
from kornia.augmentation._2d.intensity.motion_blur import RandomMotionBlur
from kornia.augmentation._2d.intensity.normalize import Normalize
diff --git a/kornia/augmentation/_2d/intensity/jpeg.py b/kornia/augmentation/_2d/intensity/jpeg.py
new file mode 100644
index 000000000..cc8654bdc
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/jpeg.py
@@ -0,0 +1,57 @@
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.core import Tensor
+from kornia.enhance import jpeg_codec_differentiable
+
+
+class RandomJPEG(IntensityAugmentationBase2D):
+ r"""Applies random (differentiable) JPEG coding to a tensor image.
+
+ .. image:: _static/img/RandomJPEG.png
+
+ Args:
+ jpeg_quality: The range of compression rates to be applied.
+ p: probability of applying the transformation.
+ 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)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.enhance.jpeg_codec_differentiable`.
+
+ Examples:
+ >>> import torch
+ >>> rng = torch.manual_seed(0)
+ >>> images = 0.1904 * torch.ones(2, 3, 32, 32)
+ >>> aug = RandomJPEG(jpeg_quality=(1.0, 50.0), p=1.)
+ >>> images_jpeg = aug(images)
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> images = 0.1904 * torch.ones(2, 3, 32, 32)
+ >>> aug = RandomJPEG(jpeg_quality=20.0, p=1.) # Samples a JPEG quality from the range [30.0, 70.0]
+ >>> (aug(images) == aug(images, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ jpeg_quality: Union[Tensor, float, Tuple[float, float], List[float]] = 50.0,
+ same_on_batch: bool = False,
+ p: float = 1.0,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
+ self.jpeg_quality = jpeg_quality
+ self._param_generator = rg.JPEGGenerator(jpeg_quality)
+
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ jpeg_output: Tensor = jpeg_codec_differentiable(input, params["jpeg_quality"])
+ return jpeg_output
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index df6ff7199..e642a3e05 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -30,6 +30,7 @@ from kornia.augmentation._2d import (
RandomHue,
RandomInvert,
RandomJigsaw,
+ RandomJPEG,
RandomMedianBlur,
RandomMixUpV2,
RandomMosaic,
diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.py
index cd683adf8..6d8855dc7 100644
--- a/kornia/augmentation/random_generator/_2d/__init__.py
+++ b/kornia/augmentation/random_generator/_2d/__init__.py
@@ -6,6 +6,7 @@ from kornia.augmentation.random_generator._2d.cutmix import *
from kornia.augmentation.random_generator._2d.gaussian_blur import *
from kornia.augmentation.random_generator._2d.gaussian_illumination import *
from kornia.augmentation.random_generator._2d.jigsaw import *
+from kornia.augmentation.random_generator._2d.jpeg import *
from kornia.augmentation.random_generator._2d.mixup import *
from kornia.augmentation.random_generator._2d.mosaic import *
from kornia.augmentation.random_generator._2d.motion_blur import *
diff --git a/kornia/augmentation/random_generator/_2d/jpeg.py b/kornia/augmentation/random_generator/_2d/jpeg.py
new file mode 100644
index 000000000..7e508340c
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/jpeg.py
@@ -0,0 +1,53 @@
+from typing import Dict, List, Tuple, Union
+
+import torch
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
+from kornia.core import Tensor
+from kornia.utils.helpers import _extract_device_dtype
+
+__all__ = ["JPEGGenerator"]
+
+
+class JPEGGenerator(RandomGeneratorBase):
+ r"""Generate random JPEG augmentation parameters for a batch.
+
+ Args:
+ jpeg_quality: The RandomJPEG quality to apply
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - jpeg_quality: element-wise contrast factors with a shape of (B,).
+
+ 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,
+ jpeg_quality: Union[Tensor, float, Tuple[float, float], List[float]] = 50.0,
+ ) -> None:
+ super().__init__()
+ self.jpeg_quality: Union[Tensor, float, Tuple[float, float], List[float]] = jpeg_quality
+
+ def __repr__(self) -> str:
+ return f"RandomJPEG quality={self.jpeg_quality}"
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ jpeg_quality = _range_bound(
+ self.jpeg_quality, "jpeg_quality", center=50.0, bounds=(1, 100), device=device, dtype=dtype
+ )
+
+ _joint_range_check(jpeg_quality, "jpeg_quality", (1, 100))
+
+ self.jpeg_quality_sampler = UniformDistribution(jpeg_quality[0], jpeg_quality[1], validate_args=False)
+
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.jpeg_quality])
+ jpeg_quality_value = _adapted_rsampling((batch_size,), self.jpeg_quality_sampler, same_on_batch)
+ return {"jpeg_quality": jpeg_quality_value.to(device=_device, dtype=_dtype)}
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 9c28f0f93..03cc32892 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -33,6 +33,7 @@ from kornia.augmentation import (
RandomHorizontalFlip,
RandomHue,
RandomInvert,
+ RandomJPEG,
RandomMedianBlur,
RandomPlanckianJitter,
RandomPlasmaBrightness,
@@ -4079,3 +4080,47 @@ class TestMultiprocessing:
pass
torch.cuda.empty_cache()
+
+
+class TestRandomJPEG(BaseTester):
+ torch.manual_seed(0) # for random reproductibility
+
+ def test_smoke(self):
+ images = torch.rand(4, 3, 16, 16)
+ aug = RandomJPEG(jpeg_quality=(1.0, 100.0), p=1.0)
+ images_aug = aug(images)
+ assert images_aug.shape == images.shape
+
+ def test_same_on_batch(self, device, dtype):
+ images = torch.rand(1, 3, 16, 16).repeat(2, 1, 1, 1)
+ aug = RandomJPEG(jpeg_quality=(1.0, 100.0), same_on_batch=True)
+ images_aug = aug(images)
+ self.assert_close(images_aug[0], images_aug[1])
+
+ def test_single_jpeg_quality(self, device, dtype):
+ images = torch.rand(4, 3, 16, 16)
+ aug = RandomJPEG(jpeg_quality=19.04, p=1.0)
+ images_aug = aug(images)
+ assert images_aug.shape == images.shape
+
+ def test_single_image(self, device, dtype):
+ images = torch.rand(3, 16, 16)
+ aug = RandomJPEG(jpeg_quality=19.04, p=1.0, keepdim=True)
+ images_aug = aug(images)
+ assert images_aug.shape == images.shape
+
+ @pytest.mark.slow
+ def test_gradcheck(self, device):
+ B, H, W = 1, 16, 16
+ img = torch.zeros(B, 3, H, W, device=device, dtype=torch.float)
+ img[..., 0, 4:-4, 4:-4] = 1.0
+ img[..., 1, 4:-4, 4:-4] = 0.5
+ img[..., 2, 4:-4, 4:-4] = 0.5
+ img.requires_grad = True
+ aug = RandomJPEG(jpeg_quality=(10.0, 10.0))
+ img_jpeg = aug(img)
+ (img_jpeg - torch.zeros_like(img_jpeg)).abs().sum().backward()
+ # Numbers generated based on reference implementation
+ img_jpeg_mean_grad_ref = torch.tensor([0.1919])
+ # We use a slightly higher tolerance since our implementation varies from the reference implementation
+ self.assert_close(img.grad.mean().view(-1), img_jpeg_mean_grad_ref, rtol=0.01, atol=0.01)