Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[feat] Added Jigsaw Augmentation (#1852)

Jian Shife977ab5f7b3
diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rst
index d997e3f20..cda750b1b 100644
--- a/docs/source/augmentation.module.rst
+++ b/docs/source/augmentation.module.rst
@@ -49,11 +49,10 @@ Geometric
Mix
~~~
-.. autoclass:: RandomMosaic
-.. autoclass:: RandomCutMix
.. autoclass:: RandomCutMixV2
-.. autoclass:: RandomMixUp
.. autoclass:: RandomMixUpV2
+.. autoclass:: RandomMosaic
+.. autoclass:: RandomJigsaw
Transforms3D
------------
diff --git a/kornia/augmentation/_2d/mix/__init__.py b/kornia/augmentation/_2d/mix/__init__.py
index f5fe4202d..c28e46dcc 100644
--- a/kornia/augmentation/_2d/mix/__init__.py
+++ b/kornia/augmentation/_2d/mix/__init__.py
@@ -1,3 +1,4 @@
from kornia.augmentation._2d.mix.cutmix import RandomCutMix, RandomCutMixV2
+from kornia.augmentation._2d.mix.jigsaw import RandomJigsaw
from kornia.augmentation._2d.mix.mixup import RandomMixUp, RandomMixUpV2
from kornia.augmentation._2d.mix.mosaic import RandomMosaic
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index be0f667f8..e7b9b50a8 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -163,7 +163,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
if sum(to_apply) != 0:
applied = self.apply_transform(in_tensor, params, flags)
output = self.apply_non_transform(in_tensor, params, flags)
- output[to_apply] = self.apply_non_transform(applied, params, flags)
+ output = output.index_put((to_apply,), self.apply_non_transform(applied, params, flags))
output = _transform_output_shape(output, ori_shape) if self.keepdim else output
return output
diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.py
new file mode 100644
index 000000000..226e36024
--- /dev/null
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -0,0 +1,81 @@
+from typing import Any, Dict, List, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
+from kornia.constants import DataKey
+from kornia.core import Tensor
+
+__all__ = ["RandomJigsaw"]
+
+
+class RandomJigsaw(MixAugmentationBaseV2):
+ r"""RandomJigsaw augmentation.
+
+ .. image:: https://raw.githubusercontent.com/kornia/data/main/random_jigsaw.png
+
+ Make Jigsaw puzzles for each image individually. To mix with different images in a
+ batch, referring to :class:`kornia.augmentation.RandomMosic`.
+
+ Args:
+ grid: the Jigsaw puzzle grid. e.g. (2, 2) means
+ each output will mix image patches in a 2x2 grid.
+ ensure_perm: to ensure the nonidentical patch permutation generation against
+ the original one.
+ data_keys: the input type sequential for applying augmentations.
+ Accepts "input", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints".
+ p: probability of applying the transformation for the whole batch.
+ 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``.
+
+ Examples:
+ >>> jigsaw = RandomJigsaw((4, 4))
+ >>> input = torch.randn(8, 3, 256, 256)
+ >>> out = jigsaw(input)
+ >>> out.shape
+ torch.Size([8, 3, 256, 256])
+ """
+
+ def __init__(
+ self,
+ grid: Tuple[int, int] = (4, 4),
+ data_keys: List[Union[str, int, DataKey]] = [DataKey.INPUT],
+ p: float = 0.5,
+ same_on_batch: bool = False,
+ keepdim: bool = False,
+ ensure_perm: bool = True,
+ ) -> None:
+ super().__init__(p=p, p_batch=1.0, same_on_batch=same_on_batch, keepdim=keepdim, data_keys=data_keys)
+ self._param_generator = cast(rg.JigsawGenerator, rg.JigsawGenerator(grid, ensure_perm))
+ self.flags = dict(grid=grid)
+
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
+ # different from the Base class routine. This function will not refer to any non-transformation images.
+ to_apply = params['batch_prob']
+ input = input[to_apply].clone()
+
+ b, c, h, w = input.shape
+ perm = params["permutation"]
+ piece_size_h, piece_size_w = input.shape[-2] // self.flags["grid"][0], input.shape[-1] // self.flags["grid"][1]
+ # Convert to C BxN H' W'
+ input = (
+ input.unfold(2, piece_size_h, piece_size_w)
+ .unfold(3, piece_size_h, piece_size_w)
+ .reshape(b, c, -1, piece_size_h, piece_size_w)
+ .permute(1, 0, 2, 3, 4)
+ .reshape(c, -1, piece_size_h, piece_size_w)
+ )
+ perm = (perm + torch.arange(0, b, device=perm.device)[:, None] * perm.shape[1]).view(-1)
+ input = input[:, perm, :, :]
+ input = (
+ input.reshape(-1, b, self.flags["grid"][1], h, piece_size_w)
+ .permute(0, 1, 2, 4, 3)
+ .reshape(-1, b, h, w)
+ .permute(0, 1, 3, 2)
+ .permute(1, 0, 2, 3)
+ )
+ return input
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index bb4fdf9e4..85590e130 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -21,7 +21,8 @@ class RandomMosaic(MixAugmentationBaseV2):
.. image:: https://raw.githubusercontent.com/kornia/data/main/random_mosaic.png
Given a certain number of images, mosaic transform combines them into one output image.
- The output image is composed of the parts from each sub-image.
+ The output image is composed of the parts from each sub-image. To mess up each image individually,
+ referring to :class:`kornia.augmentation.RandomJigsaw`.
The mosaic transform steps are as follows:
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 61137cf95..b9d8f5661 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -21,6 +21,7 @@ from kornia.augmentation._2d import (
RandomGrayscale,
RandomHorizontalFlip,
RandomInvert,
+ RandomJigsaw,
RandomMixUp,
RandomMixUpV2,
RandomMosaic,
@@ -99,10 +100,9 @@ __all__ = [
"RandomMotionBlur",
"RandomInvert",
"RandomThinPlateSpline",
- "RandomMixUp",
"RandomMixUpV2",
- "RandomCutMix",
"RandomCutMixV2",
+ "RandomJigsaw",
"RandomMosaic",
"Resize",
"SmallestMaxSize",
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 70b8f6eb4..2662dd2d9 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -247,9 +247,12 @@ class _AugmentationBase(_BasicAugmentationBase):
else:
output = in_tensor.clone()
trans_matrix = self.identity_matrix(in_tensor)
- trans_matrix[to_apply] = self.compute_transformation(in_tensor[to_apply], params=params, flags=flags)
- output[to_apply] = self.apply_transform(
- in_tensor[to_apply], params=params, flags=flags, transform=trans_matrix[to_apply]
+ trans_matrix = trans_matrix.index_put(
+ (to_apply,), self.compute_transformation(in_tensor[to_apply], params=params, flags=flags)
+ )
+ output = output.index_put(
+ (to_apply,),
+ self.apply_transform(in_tensor[to_apply], params=params, flags=flags, transform=trans_matrix[to_apply]),
)
self._transform_matrix = trans_matrix
diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.py
index 49ae1bd21..359016eaa 100644
--- a/kornia/augmentation/random_generator/_2d/__init__.py
+++ b/kornia/augmentation/random_generator/_2d/__init__.py
@@ -4,6 +4,7 @@ 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 *
from kornia.augmentation.random_generator._2d.func import *
+from kornia.augmentation.random_generator._2d.jigsaw 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/jigsaw.py b/kornia/augmentation/random_generator/_2d/jigsaw.py
new file mode 100644
index 000000000..5e8ecaa50
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/jigsaw.py
@@ -0,0 +1,55 @@
+from typing import Dict, Tuple
+
+import torch
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.random_generator.utils import randperm
+from kornia.augmentation.utils import _common_param_check
+
+
+class JigsawGenerator(RandomGeneratorBase):
+ r"""Generate Jigsaw permutation indices for a batch of inputs.
+
+ Args:
+ grid: the Jigsaw puzzle grid. e.g. (2, 2) means
+ each output will mix image patches in a 2x2 grid.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - permutation (Tensor): Jigsaw permutation arrangement.
+
+ 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, grid: Tuple[int, int] = (4, 4), ensure_perm: bool = True) -> None:
+ super().__init__()
+ self.grid = grid
+ self.ensure_perm = ensure_perm
+
+ def __repr__(self) -> str:
+ repr = f"grid={self.grid}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self._device = device
+ self._dtype = dtype
+
+ 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)
+
+ perm_times = self.grid[0] * self.grid[1]
+ # Generate mosiac order in one shot
+ if batch_size == 0:
+ rand_ids = torch.zeros([0, perm_times], device=self._device)
+ elif same_on_batch:
+ rand_ids = randperm(perm_times, ensure_perm=self.ensure_perm, device=self._device)
+ rand_ids = torch.stack([rand_ids] * batch_size)
+ else:
+ rand_ids = torch.stack(
+ [randperm(perm_times, ensure_perm=self.ensure_perm, device=self._device) for _ in range(batch_size)]
+ )
+ return dict(permutation=rand_ids)
diff --git a/kornia/augmentation/random_generator/utils.py b/kornia/augmentation/random_generator/utils.py
new file mode 100644
index 000000000..518ff347b
--- /dev/null
+++ b/kornia/augmentation/random_generator/utils.py
@@ -0,0 +1,11 @@
+import torch
+from torch import Tensor
+
+
+def randperm(n: int, ensure_perm: bool = True, **kwargs) -> Tensor:
+ """`randomperm` with the ability to ensure the different arrangement generated."""
+ perm = torch.randperm(n, **kwargs)
+ if ensure_perm:
+ while torch.all(torch.eq(perm, torch.arange(n, device=perm.device))):
+ perm = torch.randperm(n, **kwargs)
+ return perm
diff --git a/test/augmentation/test_augmentation_mix.py b/test/augmentation/test_augmentation_mix.py
index 0d10a91cf..d1243acbb 100644
--- a/test/augmentation/test_augmentation_mix.py
+++ b/test/augmentation/test_augmentation_mix.py
@@ -1,7 +1,7 @@
import pytest
import torch
-from kornia.augmentation import RandomCutMixV2, RandomMixUpV2, RandomMosaic
+from kornia.augmentation import RandomCutMixV2, RandomJigsaw, RandomMixUpV2, RandomMosaic
from kornia.testing import assert_close
@@ -333,3 +333,46 @@ class TestRandomMosaic:
)
f(input, boxes)
+
+
+class TestRandomJigsaw:
+ def test_smoke(self):
+ f = RandomJigsaw(data_keys=["input"])
+ repr = "RandomJigsaw(grid=(4, 4), p=0.5, p_batch=1.0, same_on_batch=False, grid=(4, 4))"
+ assert str(f) == repr
+
+ def test_numerical(self, device, dtype):
+ torch.manual_seed(22)
+ f = RandomJigsaw(grid=(2, 2), p=1.0, data_keys=["input"])
+
+ input = torch.arange(32, device=device, dtype=dtype).reshape(2, 1, 4, 4)
+
+ out_image = f(input)
+
+ expected = torch.tensor(
+ [
+ [[[2.0, 3.0, 0.0, 1.0], [6.0, 7.0, 4.0, 5.0], [8.0, 9.0, 10.0, 11.0], [12.0, 13.0, 14.0, 15.0]]],
+ [
+ [
+ [16.0, 17.0, 18.0, 19.0],
+ [20.0, 21.0, 22.0, 23.0],
+ [24.0, 25.0, 26.0, 27.0],
+ [28.0, 29.0, 30.0, 31.0],
+ ]
+ ],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
+
+ @pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
+ @pytest.mark.parametrize("same_on_batch", [True, False])
+ def test_p(self, p, same_on_batch, device, dtype):
+ torch.manual_seed(76)
+ f = RandomJigsaw(p=p, data_keys=["input"], same_on_batch=same_on_batch)
+
+ input = torch.randn((12, 3, 256, 256), device=device, dtype=dtype)
+
+ f(input)