Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

augmentation module + random horizontal flip

dvd42e3bfc9577836
diff --git a/kornia/__init__.py b/kornia/__init__.py
index a9ea66650..58865e75b 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -13,6 +13,7 @@ from kornia import filters
from kornia import geometry
from kornia import losses
from kornia import utils
+from kornia import augmentation
# Exposes package functional to top level
@@ -70,5 +71,10 @@ from kornia.utils import (
save_pointcloud_ply,
load_pointcloud_ply,
)
+from kornia.augmentation import (
+ random_hflip,
+ RandomHorizontalFlip,
+)
+
from kornia.geometry import *
from kornia.geometry import pi
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
new file mode 100644
index 000000000..96d1849d7
--- /dev/null
+++ b/kornia/augmentation/__init__.py
@@ -0,0 +1,3 @@
+from .augmentations import RandomHorizontalFlip, random_hflip
+
+__all__ = ["random_hflip", "RandomHorizontalFlip"]
diff --git a/kornia/augmentation/augmentations.py b/kornia/augmentation/augmentations.py
new file mode 100644
index 000000000..ce118ce46
--- /dev/null
+++ b/kornia/augmentation/augmentations.py
@@ -0,0 +1,69 @@
+import torch
+import torch.nn as nn
+from kornia.geometry.transform import flips
+
+
+class RandomHorizontalFlip(nn.Module):
+
+ r"""Horizontally flip a tensor image or a batch of tensor images randomly with a given probability.
+ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+
+ Args:
+ p (float): probability of the image being flipped. Default value is 0.5
+ """
+
+ def __init__(self, p=0.5):
+ super(RandomHorizontalFlip, self).__init__()
+ self.p: float = p
+
+ def __repr__(self):
+ repr = "(p={0})".format(self.p)
+ return self.__class__.__name__ + repr
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ return random_hflip(input, self.p)
+
+
+def random_hflip(input, p=0.5):
+
+ r"""Horizontally flip a tensor image or a batch of tensor images randomly with a given probability.
+ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+
+ Args:
+ p (float): probability of the image being flipped. Default value is 0.5
+ Returns:
+ torch.Tensor: The horizontally flipped input
+ torch.Tensor: The applied transformation matrix
+ """
+
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+
+ if not isinstance(p, float):
+ raise TypeError(f"The probability should be a float number.")
+
+ device: torch.device = input.device
+
+ if len(input.shape) > 3:
+ input = input.view((-1, input.shape[-2], input.shape[-1]))
+ probs: torch.Tensor = torch.empty(input.shape[0], device=device).uniform_(0, 1)
+ else:
+ input = input.unsqueeze(0)
+ probs: torch.Tensor = torch.empty(1, device=device).uniform_(0, 1)
+
+ to_flip: torch.Tensor = probs < p
+
+ if input[to_flip].nelement() != 0:
+
+ flipped: torch.Tensor = flips.hflip(input[to_flip])
+ trans_mat: torch.Tensor = torch.zeros((3, 3))
+ trans_mat[0][0] = -1
+ trans_mat[1][1] = 1
+ trans_mat[0][2] = input.shape[-2]
+
+ trans_mat = trans_mat.unsqueeze(0).repeat(input.shape[0], 1, 1)
+ trans_mat[~to_flip] = torch.eye(3) # no transform on these inputs
+
+ return flipped, trans_mat
+
+ return input, torch.eye(3).unsqueeze(0).repeat(input.shape[0], 1, 1)
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
new file mode 100644
index 000000000..cf93e2058
--- /dev/null
+++ b/test/augmentation/test_augmentation.py
@@ -0,0 +1,113 @@
+import kornia
+import torch
+import pytest
+
+import kornia.testing as utils # test utils
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+
+class TestRandomHorizontalFlip:
+
+ def smoke_test(self):
+ f = kornia.RandomHorizontalFlip(0.5)
+ repr = "RandomHorizontalFlip(p=0.5)"
+ assert str(f) == repr
+
+ def test_random_hflip(self):
+
+ f = kornia.RandomHorizontalFlip(p=1.0)
+ f1 = kornia.RandomHorizontalFlip(p=0.)
+
+ input = torch.tensor([[0., 0., 0.],
+ [0., 0., 0.],
+ [0., 1., 1.]]) # 3 x 3
+
+ expected = torch.tensor([[0., 0., 0.],
+ [0., 0., 0.],
+ [1., 1., 0.]]) # 3 x 3
+
+ expected_transform = torch.tensor([[-1., 0., 3.],
+ [0., 1., 0.],
+ [0., 0., 0.]]) # 3 x 3
+
+ identity = torch.tensor([[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]]) # 3 x 3
+
+ assert (f(input)[0] == expected).all()
+ assert (f(input)[1] == expected_transform).all()
+ assert (f1(input)[0] == input).all()
+ assert (f1(input)[1] == identity).all()
+
+ def test_batch_random_hflip(self):
+
+ f = kornia.RandomHorizontalFlip(p=1.0)
+ f1 = kornia.RandomHorizontalFlip(p=0.0)
+
+ input = torch.tensor([[[0., 0., 0.],
+ [0., 0., 0.],
+ [0., 1., 1.]]]) # 1 x 3 x 3
+
+ expected = torch.tensor([[[0., 0., 0.],
+ [0., 0., 0.],
+ [1., 1., 0.]]]) # 1 x 3 x 3
+
+ expected_transform = torch.tensor([[[-1., 0., 3.],
+ [0., 1., 0.],
+ [0., 0., 0.]]]) # 1 x 3 x 3
+
+ identity = torch.tensor([[[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]]]) # 1 x 3 x 3
+
+ input = input.repeat(2, 1, 1) # 2 x 3 x 3
+ expected = expected.repeat(2, 1, 1) # 2 x 3 x 3
+ expected_transform = expected_transform.repeat(2, 1, 1) # 2 x 3 x 3
+ identity = identity.repeat(2, 1, 1) # 2 x 3 x 3
+
+ assert (f(input)[0] == expected).all()
+ assert (f(input)[1] == expected_transform).all()
+ assert (f1(input)[0] == input).all()
+ assert (f1(input)[1] == identity).all()
+
+ @pytest.mark.skip(reason="turn off all jit for a while")
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(data: torch.Tensor) -> torch.Tensor:
+
+ return kornia.random_hflip(data)
+
+ input = torch.tensor([[0., 0., 0.],
+ [0., 0., 0.],
+ [0., 1., 1.]]) # 3 x 3
+
+ # Build jit trace
+ op_trace = torch.jit.trace(op_script, (input, ))
+
+ # Create new inputs
+ input = torch.tensor([[0., 0., 0.],
+ [5., 5., 0.],
+ [0., 0., 0.]]) # 3 x 3
+
+ input = input.repeat(2, 1, 1) # 2 x 3 x 3
+
+ expected = torch.tensor([[[0., 0., 0.],
+ [0., 5., 5.],
+ [0., 0., 0.]]]) # 3 x 3
+
+ expected = expected.repeat(2, 1, 1)
+
+ actual = op_trace(input)
+
+ assert_allclose(actual, expected)
+
+ def test_gradcheck(self):
+
+ input = torch.tensor([[0., 0., 0.],
+ [0., 0., 0.],
+ [0., 1., 1.]]).double() # 3 x 3
+
+ input = utils.tensor_to_gradcheck_var(input) # to var
+
+ assert gradcheck(kornia.RandomHorizontalFlip(p=1.), (input, ), raise_exception=True)