Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement `diamond_square` and plasma augmentations (#1700)

Edgar Ribab6674d3bac51
diff --git a/docs/generate_example_images.py b/docs/generate_example_images.py
index 197efd4ca..88d9e44a2 100644
--- a/docs/generate_example_images.py
+++ b/docs/generate_example_images.py
@@ -72,6 +72,9 @@ def main():
"RandomMotionBlur": ((7, 35.0, 0.5), 2, 2020),
"RandomPerspective": ((0.2,), 2, 2020),
"RandomPlanckianJitter": ((), 2, 2022),
+ "RandomPlasmaShadow": (((0.2, 0.5),), 2, 2022),
+ "RandomPlasmaBrightness": ((), 2, 2022),
+ "RandomPlasmaContrast": ((), 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.rst
index 476cbe662..5ba2f63f6 100644
--- a/docs/source/augmentation.module.rst
+++ b/docs/source/augmentation.module.rst
@@ -12,6 +12,9 @@ Intensity
~~~~~~~~~
.. autoclass:: RandomPlanckianJitter
+.. autoclass:: RandomPlasmaShadow
+.. autoclass:: RandomPlasmaBrightness
+.. autoclass:: RandomPlasmaContrast
.. autoclass:: ColorJiggle
.. autoclass:: ColorJitter
.. autoclass:: RandomBoxBlur
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 2296eda9a..5c8087ac2 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -52,5 +52,6 @@ Distance Transform
------------------
.. autofunction:: distance_transform
+.. autofunction:: diamond_square
.. autoclass:: DistanceTransform
diff --git a/docs/source/references.bib b/docs/source/references.bib
index ed2d408a2..a1ed0f1d5 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -198,3 +198,14 @@
journal={arXiv preprint arXiv:2202.07993},
year={2022}
}
+
+@misc{tormentor,
+ doi = {10.48550/ARXIV.2204.03776},
+ url = {https://arxiv.org/abs/2204.03776},
+ author = {Nicolaou, Anguelos and Christlein, Vincent and Riba, Edgar and Shi, Jian and Vogeler, Georg and Seuret, Mathias},
+ keywords = {Computer Vision and Pattern Recognition (cs.CV), Artificial Intelligence (cs.AI), FOS: Computer and information sciences, FOS: Computer and information sciences},
+ title = {TorMentor: Deterministic dynamic-path, data augmentations with fractals},
+ publisher = {arXiv},
+ year = {2022},
+ copyright = {Creative Commons Attribution 4.0 International}
+}
diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.py
index 729c66e69..9715da512 100644
--- a/kornia/augmentation/_2d/geometric/fisheye.py
+++ b/kornia/augmentation/_2d/geometric/fisheye.py
@@ -21,6 +21,7 @@ class RandomFisheye(GeometricAugmentationBase2D):
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+
Examples:
>>> import torch
>>> img = torch.ones(1, 1, 2, 2)
@@ -88,6 +89,6 @@ class RandomFisheye(GeometricAugmentationBase2D):
gamma = params["gamma"].view(B, 1, 1).to(input)
# compute and apply the distances respect to the camera optical center
distance = ((center_x - field_x) ** 2 + (center_y - field_y) ** 2) ** 0.5
- field_x = field_x + field_x * distance ** gamma # BxHxw
- field_y = field_y + field_y * distance ** gamma # BxHxW
+ field_x = field_x + field_x * distance**gamma # BxHxw
+ field_y = field_y + field_y * distance**gamma # BxHxW
return remap(input, field_x, field_y, normalized_coordinates=True, align_corners=True)
diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.py
index fee4ddf03..25283dfff 100644
--- a/kornia/augmentation/_2d/intensity/__init__.py
+++ b/kornia/augmentation/_2d/intensity/__init__.py
@@ -12,6 +12,7 @@ from kornia.augmentation._2d.intensity.invert import RandomInvert
from kornia.augmentation._2d.intensity.motion_blur import RandomMotionBlur
from kornia.augmentation._2d.intensity.normalize import Normalize
from kornia.augmentation._2d.intensity.planckian_jitter import RandomPlanckianJitter
+from kornia.augmentation._2d.intensity.plasma import RandomPlasmaBrightness, RandomPlasmaContrast, RandomPlasmaShadow
from kornia.augmentation._2d.intensity.posterize import RandomPosterize
from kornia.augmentation._2d.intensity.sharpness import RandomSharpness
from kornia.augmentation._2d.intensity.solarize import RandomSolarize
diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.py
new file mode 100644
index 000000000..55d0b7c08
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/plasma.py
@@ -0,0 +1,177 @@
+from typing import Any, Dict, Optional, Tuple, cast
+
+from torch import Tensor
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.contrib import diamond_square
+
+
+class RandomPlasmaBrightness(IntensityAugmentationBase2D):
+ r"""Adds brightness to the image based on a fractal map generated by the diamond square algorithm.
+
+ .. image:: _static/img/RandomPlasmaBrightness.png
+
+ This is based on the original paper: TorMentor: Deterministic dynamic-path, data augmentations with fractals.
+ See: :cite:`tormentor` for more details.
+
+ .. note::
+ This function internally uses :func:`kornia.contrib.diamond_square`.
+
+ Args:
+ roughness: value to scale during the recursion in the generation of the fractal map.
+ intensity: value that scales the intensity values of the generated maps.
+ same_on_batch: apply the same transformation across the batch.
+ p: probability of applying the transformation.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> img = torch.ones(1, 1, 3, 4)
+ >>> RandomPlasmaBrightness(roughness=(0.1, 0.7), p=1.)(img)
+ tensor([[[[0.6415, 1.0000, 0.3142, 0.6836],
+ [1.0000, 0.5593, 0.5556, 0.4566],
+ [0.5809, 1.0000, 0.7005, 1.0000]]]])
+ """
+
+ def __init__(
+ self,
+ roughness: Tuple[float, float] = (0.1, 0.7),
+ intensity: Tuple[float, float] = (0.0, 1.0),
+ 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, p_batch=1.0, keepdim=keepdim
+ )
+ self._param_generator = cast(
+ rg.PlainUniformGenerator,
+ rg.PlainUniformGenerator((roughness, "roughness", None, None), (intensity, "intensity", None, None)),
+ )
+
+ def apply_transform(
+ self, image: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ B, C, H, W = image.shape
+ roughness = params["roughness"].to(image)
+ intensity = params["intensity"].to(image).view(-1, 1, 1, 1)
+ brightness_map = 2 * diamond_square((B, C, H, W), roughness, device=image.device, dtype=image.dtype) - 1
+ brightness_map = brightness_map * intensity
+ return (image + brightness_map).clamp_(0, 1)
+
+
+class RandomPlasmaContrast(IntensityAugmentationBase2D):
+ r"""Adds contrast to the image based on a fractal map generated by the diamond square algorithm.
+
+ .. image:: _static/img/RandomPlasmaContrast.png
+
+ This is based on the original paper: TorMentor: Deterministic dynamic-path, data augmentations with fractals.
+ See: :cite:`tormentor` for more details.
+
+ .. note::
+ This function internally uses :func:`kornia.contrib.diamond_square`.
+
+ Args:
+ roughness: value to scale during the recursion in the generation of the fractal map.
+ same_on_batch: apply the same transformation across the batch.
+ p: probability of applying the transformation.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> img = torch.ones(1, 1, 3, 4)
+ >>> RandomPlasmaContrast(roughness=(0.1, 0.7), p=1.)(img)
+ tensor([[[[0.9651, 1.0000, 1.0000, 1.0000],
+ [1.0000, 0.9103, 0.8038, 0.9263],
+ [0.6882, 1.0000, 0.9544, 1.0000]]]])
+ """
+
+ def __init__(
+ self,
+ roughness: Tuple[float, float] = (0.1, 0.7),
+ 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, p_batch=1.0, keepdim=keepdim
+ )
+ self._param_generator = cast(
+ rg.PlainUniformGenerator, rg.PlainUniformGenerator((roughness, "roughness", None, None))
+ )
+
+ def apply_transform(
+ self, image: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ B, C, H, W = image.shape
+ roughness = params["roughness"].to(image)
+ contrast_map = 4 * diamond_square((B, C, H, W), roughness, device=image.device, dtype=image.dtype)
+ return ((image - 0.5) * contrast_map + 0.5).clamp_(0, 1)
+
+
+class RandomPlasmaShadow(IntensityAugmentationBase2D):
+ r"""Add gaussian noise to a batch of multi-dimensional images.
+
+ .. image:: _static/img/RandomPlasmaShadow.png
+
+ This is based on the original paper: TorMentor: Deterministic dynamic-path, data augmentations with fractals.
+ See: :cite:`tormentor` for more details.
+
+ .. note::
+ This function internally uses :func:`kornia.contrib.diamond_square`.
+
+ Args:
+ roughness: value to scale during the recursion in the generation of the fractal map.
+ shade_intensity: value that scales the intensity values of the generated maps.
+ shade_quantity: value to select the pixels to mask.
+ same_on_batch: apply the same transformation across the batch.
+ p: probability of applying the transformation.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> img = torch.ones(1, 1, 3, 4)
+ >>> RandomPlasmaShadow(roughness=(0.1, 0.7), p=1.)(img)
+ tensor([[[[0.7682, 1.0000, 1.0000, 1.0000],
+ [1.0000, 1.0000, 1.0000, 1.0000],
+ [1.0000, 1.0000, 1.0000, 1.0000]]]])
+ """
+
+ def __init__(
+ self,
+ roughness: Tuple[float, float] = (0.1, 0.7),
+ shade_intensity: Tuple[float, float] = (-1.0, 0.0),
+ shade_quantity: Tuple[float, float] = (0.0, 1.0),
+ 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, p_batch=1.0, keepdim=keepdim
+ )
+ self._param_generator = cast(
+ rg.PlainUniformGenerator,
+ rg.PlainUniformGenerator(
+ (roughness, "roughness", None, None),
+ (shade_intensity, "shade_intensity", None, None),
+ (shade_quantity, "shade_quantity", None, None),
+ ),
+ )
+
+ def apply_transform(
+ self, image: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ B, _, H, W = image.shape
+ roughness = params["roughness"].to(image)
+ shade_intensity = params["shade_intensity"].to(image).view(-1, 1, 1, 1)
+ shade_quantity = params["shade_quantity"].to(image).view(-1, 1, 1, 1)
+ shade_map = diamond_square((B, 1, H, W), roughness, device=image.device, dtype=image.dtype)
+ shade_map = (shade_map < shade_quantity).to(image.dtype) * shade_intensity
+ return (image + shade_map).clamp_(0, 1)
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 2b45466ae..07a79f7d2 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -24,6 +24,9 @@ from kornia.augmentation._2d import (
RandomMotionBlur,
RandomPerspective,
RandomPlanckianJitter,
+ RandomPlasmaBrightness,
+ RandomPlasmaContrast,
+ RandomPlasmaShadow,
RandomPosterize,
RandomResizedCrop,
RandomRotation,
@@ -79,6 +82,9 @@ __all__ = [
"RandomVerticalFlip",
"RandomPerspective",
"RandomPlanckianJitter",
+ "RandomPlasmaShadow",
+ "RandomPlasmaBrightness",
+ "RandomPlasmaContrast",
"RandomResizedCrop",
"RandomRotation",
"RandomSolarize",
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index 48099040f..9aa836f93 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -1,5 +1,6 @@
from .classification import ClassificationHead
from .connected_components import connected_components
+from .diamond_square import diamond_square
from .distance_transform import DistanceTransform, distance_transform
from .extract_patches import (
CombineTensorPatches,
@@ -31,4 +32,5 @@ __all__ = [
"ImageStitcher",
"distance_transform",
"DistanceTransform",
+ "diamond_square",
]
diff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.py
new file mode 100644
index 000000000..f4718eb0e
--- /dev/null
+++ b/kornia/contrib/diamond_square.py
@@ -0,0 +1,209 @@
+# based on: https://github.com/anguelos/tormentor/blob/e8050ac235b0c7ad3c7d931cfa47c308a305c486/diamond_square/diamond_square.py # noqa: E501
+import math
+from typing import Callable, List, Optional, Tuple, Union
+
+import torch
+from torch import Tensor
+
+from kornia.enhance import normalize_min_max
+from kornia.filters import filter2D
+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+
+# the default kernels for the diamond square
+default_diamond_kernel: List[List[float]] = [[0.25, 0.0, 0.25], [0.0, 0.0, 0.0], [0.25, 0.0, 0.25]]
+default_square_kernel: List[List[float]] = [[0.0, 0.25, 0.0], [0.25, 0.0, 0.25], [0.0, 0.25, 0.0]]
+
+
+def _diamond_square_seed(
+ replicates: int,
+ width: int,
+ height: int,
+ random_fn: Callable,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> Tensor:
+ """Helper function to generate the diamond square image seee.
+
+ Args:
+ replicates: the num of batched replicas for the image.
+ width: the expected image width.
+ height: the expected image height.
+ random_fn: the random function to generate the image seed.
+ device: the torch device where to create the image seed.
+ dtype: the torch dtype where to create the image seed.
+
+ Return:
+ the generated image seed of size Bx1xHxW.
+ """
+ KORNIA_CHECK(width == 3 or height == 3, "Height or Width must be equal to 3.")
+ # TODO(anguelos): can we avoid transposing and passing always fixed size. This will cause issues with onnx/jit
+ transpose: bool = False
+ if height == 3:
+ transpose = True
+ width, height = height, width
+
+ # width is always 3
+ KORNIA_CHECK(height % 2 == 1 and height > 2, "Height must be odd and height bigger than 2")
+
+ res: Tensor = random_fn([replicates, 1, width, height], device=device, dtype=dtype)
+ res[..., ::2, ::2] = random_fn([replicates, 1, 2, (height + 1) // 2], device=device, dtype=dtype)
+
+ # Diamond step
+ res[..., 1, 1::2] = (res[..., ::2, :-2:2] + res[..., ::2, 2::2]).sum(dim=2) / 4.0
+
+ # Square step
+ if width > 3:
+ res[..., 1, 2:-3:2] = (
+ res[..., 0, 2:-3:2] + res[..., 2, 2:-3:2] + res[..., 1, 0:-4:2] + res[..., 1, 2:-3:2]
+ ) / 4.0
+
+ tmp1 = res[..., 2, 0]
+ res[..., 1, 0] = res[..., 0, 0] + res[..., 1, 1] + tmp1
+ res[..., 1, -1] = res[..., -1, -1] + res[..., 1, -2] + tmp1
+ tmp2 = res[..., 1, 1::2]
+ res[..., 0, 1::2] = res[..., 0, 0:-2:2] + res[..., 0, 2::2] + tmp2
+ res[..., 2, 1::2] = res[..., 2, 0:-2:2] + res[..., 2, 2::2] + tmp2
+ res = res / 3.0
+
+ if transpose:
+ res = res.transpose(2, 3)
+ return res
+
+
+def _one_diamond_one_square(
+ img: Tensor,
+ random_scale: Union[float, Tensor],
+ random_fn: Callable = torch.rand,
+ diamond_kernel: Optional[Tensor] = None,
+ square_kernel: Optional[Tensor] = None,
+) -> Tensor:
+ """Doubles the image resolution by applying a single diamond square steps.
+
+ Recursive application of this method creates plasma fractals.
+
+ Attention! The function is differentiable and gradients are computed as well.
+
+ If this function is run in the usual sense, it is more efficient if it is run in a no_grad()
+
+ Args:
+ img: a 4D tensor where dimensions are Batch, Channel, Width, Height. Width and Height must both be 2^N+1 and
+ Batch and Channels should in the usual case be 1.
+ random_scale: a float number in [0,1] controlling the randomness created pixels get. I the usual case, it is
+ halved at every applycation of this function.
+ random_fn: the random function to generate the image seed.
+ diamond_kernel: the 3x3 kernel to perform the diamond step.
+ square_kernel: the 3x3 kernel to perform the square step.
+
+ Return:
+ A tensor on the same device as img with the same channels as img and width, height of 2^(N+1)+1.
+ """
+ KORNIA_CHECK_SHAPE(img, ["B", "C", "H", "W"])
+ # TODO (anguelos) test multi channel and batch size > 1
+
+ if diamond_kernel is None:
+ diamond_kernel = Tensor([default_diamond_kernel]).to(img) # 1x3x3
+ if square_kernel is None:
+ square_kernel = Tensor([default_square_kernel]).to(img) # 1x3x3
+
+ batch_sz, _, height, width = img.shape
+ new_img: Tensor = torch.zeros(
+ [batch_sz, 1, 2 * (height - 1) + 1, 2 * (width - 1) + 1], device=img.device, dtype=img.dtype
+ )
+ new_img[:, :, ::2, ::2] = img
+
+ factor: float = 1.0 / 0.75
+ pad_compencate = torch.ones_like(new_img)
+ pad_compencate[:, :, :, 0] = factor
+ pad_compencate[:, :, :, -1] = factor
+ pad_compencate[:, :, 0, :] = factor
+ pad_compencate[:, :, -1, :] = factor
+
+ random_img: Tensor = random_fn(new_img.size(), device=img.device, dtype=img.dtype) * random_scale
+
+ # TODO(edgar): use kornia.filter2d
+ # diamond
+ diamond_regions = filter2D(new_img, diamond_kernel)
+ diamond_centers = (diamond_regions > 0).to(img.dtype)
+ # TODO (anguelos) make sure diamond_regions*diamond_centers is needed
+ new_img = new_img + (1 - random_scale) * diamond_regions * diamond_centers + diamond_centers * random_img
+
+ # square
+ square_regions = filter2D(new_img, square_kernel) * pad_compencate
+ square_centers = (square_regions > 0).to(img.dtype)
+
+ # TODO (anguelos) make sure square_centers*square_regions is needed
+ new_img = new_img + square_centers * random_img + (1 - random_scale) * square_centers * square_regions
+
+ return new_img
+
+
+def diamond_square(
+ output_size: Tuple[int, int, int, int],
+ roughness: Union[float, Tensor] = 0.5,
+ random_scale: Union[float, Tensor] = 1.0,
+ random_fn: Callable = torch.rand,
+ normalize_range: Optional[Tuple[int, int]] = None,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+) -> Tensor:
+ """Generates Plasma Fractal Images.
+
+ Args:
+ outout_size: a tuple of integers with the BxCxHxW of the image to be generated.
+ roughness: the scale value to apply at each recursion step.
+ random_scale: the initial value of the scale for recursion.
+ random_fn: the callable function to use to sample a random tensor.
+ normalize_range: whether to normalize using min-max the output map. In case of a
+ range is specified, min-max norm is applied between the provided range.
+ device: the torch device to place the output map.
+ dtype: the torch dtype to place the output map.
+
+ Returns:
+ A tensor with shape :math:`(B,C,H,W)` containing the fractal image.
+ """
+ KORNIA_CHECK(len(output_size) == 4, "output_size must be (B,C,H,W)")
+ if not isinstance(random_scale, Tensor):
+ random_scale = Tensor([[[[random_scale]]]]).to(device, dtype)
+ random_scale = random_scale.expand([output_size[0] * output_size[1], 1, 1, 1])
+ else:
+ KORNIA_CHECK_IS_TENSOR(random_scale)
+ random_scale = random_scale.view(-1, 1, 1, 1)
+ random_scale = random_scale.expand([output_size[0], output_size[1], 1, 1])
+ random_scale = random_scale.reshape([-1, 1, 1, 1])
+
+ if not isinstance(roughness, Tensor):
+ roughness = Tensor([[[[roughness]]]]).to(device, dtype)
+ roughness = roughness.expand([output_size[0] * output_size[1], 1, 1, 1])
+ else:
+ roughness = roughness.view(-1, 1, 1, 1)
+ roughness = roughness.expand([output_size[0], output_size[1], 1, 1])
+ roughness = roughness.reshape([-1, 1, 1, 1])
+
+ width, height = output_size[-2:]
+ num_samples: int = 1
+ for x in output_size[:-2]:
+ num_samples *= x
+
+ # compute the image seed
+ p2_width: float = 2 ** math.ceil(math.log2(width - 1)) + 1
+ p2_height: float = 2 ** math.ceil(math.log2(height - 1)) + 1
+ recursion_depth: int = int(min(math.log2(p2_width - 1) - 1, math.log2(p2_height - 1) - 1))
+ seed_width: int = (p2_width - 1) // 2**recursion_depth + 1
+ seed_height: int = (p2_height - 1) // 2**recursion_depth + 1
+ img: Tensor = random_scale * _diamond_square_seed(num_samples, seed_width, seed_height, random_fn, device, dtype)
+
+ # perform recursion
+ scale = random_scale
+ for _ in range(recursion_depth):
+ scale = scale * roughness
+ img = _one_diamond_one_square(img, scale, random_fn)
+
+ # slice to match with the output size
+ img = img[..., :width, :height]
+ img = img.view(output_size)
+
+ # normalize the output in the range using min-max
+ if normalize_range is not None:
+ min_val, max_val = normalize_range
+ img = normalize_min_max(img, min_val, max_val)
+ return img
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 65e4abc84..25aef1972 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -28,6 +28,9 @@ from kornia.augmentation import (
RandomHorizontalFlip,
RandomInvert,
RandomPlanckianJitter,
+ RandomPlasmaBrightness,
+ RandomPlasmaContrast,
+ RandomPlasmaShadow,
RandomPosterize,
RandomResizedCrop,
RandomRotation,
@@ -255,11 +258,7 @@ class CommonTests(BaseTester):
def _test_gradcheck_implementation(self, params):
input_tensor = torch.rand((3, 5, 5), device=self.device, dtype=self.dtype) # 3 x 3
input_tensor = utils.tensor_to_gradcheck_var(input_tensor) # to var
- assert gradcheck(
- self._create_augmentation_from_params(**params, p=1.0),
- (input_tensor,),
- raise_exception=True,
- )
+ assert gradcheck(self._create_augmentation_from_params(**params, p=1.0), (input_tensor,), raise_exception=True)
class TestRandomEqualizeAlternative(CommonTests):
@@ -748,9 +747,7 @@ class TestRandomHorizontalFlip:
def test_sequential(self, device, dtype):
- f = AugmentationSequential(
- RandomHorizontalFlip(p=1.0), RandomHorizontalFlip(p=1.0)
- )
+ f = AugmentationSequential(RandomHorizontalFlip(p=1.0), RandomHorizontalFlip(p=1.0))
input = torch.tensor(
[[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]], device=device, dtype=dtype
@@ -899,9 +896,7 @@ class TestRandomVerticalFlip:
def test_sequential(self, device, dtype):
- f = AugmentationSequential(
- RandomVerticalFlip(p=1.0), RandomVerticalFlip(p=1.0)
- )
+ f = AugmentationSequential(RandomVerticalFlip(p=1.0), RandomVerticalFlip(p=1.0))
input = torch.tensor(
[[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]], device=device, dtype=dtype
@@ -1837,8 +1832,7 @@ class TestRandomGrayscale:
assert_close(img_gray, expected, atol=1e-4, rtol=1e-4)
def test_random_grayscale_sequential_batch(self, device, dtype):
- f = AugmentationSequential(
- RandomGrayscale(p=0.0), RandomGrayscale(p=0.0))
+ f = AugmentationSequential(RandomGrayscale(p=0.0), RandomGrayscale(p=0.0))
input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype) # 2 x 3 x 5 x 5
expected = input
@@ -2016,10 +2010,7 @@ class TestRandomRotation:
torch.manual_seed(0) # for random reproductibility
- f = AugmentationSequential(
- RandomRotation(torch.tensor([-45.0, 90]), p=1.0),
- RandomRotation(10.4, p=1.0),
- )
+ f = AugmentationSequential(RandomRotation(torch.tensor([-45.0, 90]), p=1.0), RandomRotation(10.4, p=1.0))
input = torch.tensor(
[[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
@@ -2234,7 +2225,7 @@ class TestRandomCrop:
inp = torch.tensor([[[[3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]], device=device, dtype=dtype)
trans = torch.eye(3, device=device, dtype=dtype)[None]
# Not return transform
- rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=9, align_corners=True, p=0., cropping_mode="resample")
+ rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=9, align_corners=True, p=0.0, cropping_mode="resample")
out = rc(inp)
assert_close(out, inp, atol=1e-4, rtol=1e-4)
@@ -2624,10 +2615,7 @@ class TestNormalize:
@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]))
- repr = (
- "Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, "
- "same_on_batch=False)"
- )
+ repr = "Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, " "same_on_batch=False)"
assert str(f) == repr
@staticmethod
@@ -2698,10 +2686,7 @@ class TestDenormalize:
@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]))
- repr = (
- "Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, "
- "same_on_batch=False)"
- )
+ repr = "Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, " "same_on_batch=False)"
assert str(f) == repr
def test_random_denormalize(self, device, dtype):
@@ -2836,128 +2821,206 @@ class TestRandomPosterize:
assert out.shape == (1, 1, 4, 5)
-class TestPlanckianJitter:
+class TestRandomPlasma:
+ def test_plasma_shadow(self, device, dtype):
+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
+ aug = RandomPlasmaShadow(p=1.0).to(device)
+ out = aug(img)
+ assert out.shape == (2, 3, 4, 5)
+
+ def test_plasma_brightness(self, device, dtype):
+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
+ aug = RandomPlasmaBrightness(p=1.0).to(device)
+ out = aug(img)
+ assert out.shape == (2, 3, 4, 5)
+ def test_plasma_contrast(self, device, dtype):
+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
+ aug = RandomPlasmaContrast(p=1.0).to(device)
+ out = aug(img)
+ assert out.shape == (2, 3, 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
@@ -2987,7 +3050,6 @@ class TestPlanckianJitter:
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)
+ 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-4)
diff --git a/test/test_contrib.py b/test/test_contrib.py
index ad8ae9aff..270396dae 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -11,6 +11,18 @@ from kornia.testing import assert_close
from packaging import version
+class TestDiamondSquare:
+ def test_smoke(self, device, dtype):
+ torch.manual_seed(0)
+ output_size = (1, 1, 3, 4)
+ roughness = 0.5
+ random_scale = 1.0
+ out = kornia.contrib.diamond_square(output_size, roughness, random_scale, device=device, dtype=dtype)
+ assert out.shape == output_size
+ assert out.device == device
+ assert out.dtype == dtype
+
+
class TestVisionTransformer:
@pytest.mark.parametrize("B", [1, 2])
@pytest.mark.parametrize("H", [1, 3, 8])
@@ -18,7 +30,7 @@ class TestVisionTransformer:
@pytest.mark.parametrize("image_size", [32, 224])
def test_smoke(self, device, dtype, B, H, D, image_size):
patch_size = 16
- T = image_size ** 2 // patch_size ** 2 + 1 # tokens size
+ T = image_size**2 // patch_size**2 + 1 # tokens size
img = torch.rand(B, 3, image_size, image_size, device=device, dtype=dtype)
vit = kornia.contrib.VisionTransformer(image_size=image_size, num_heads=H, embed_dim=D).to(device, dtype)