Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs + optional return of transforms

dvd42d87ed64d3067
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rst
new file mode 100644
index 000000000..ee4600001
--- /dev/null
+++ b/docs/source/augmentation.rst
@@ -0,0 +1,10 @@
+kornia.augmentation
+------------
+
+.. currentmodule:: kornia.augmentation
+
+The functions in this section perform various data augmentation operations
+
+.. autofunction:: random_hflip
+
+.. autoclass:: RandomHorizontalFlip
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 58865e75b..737185242 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -73,7 +73,6 @@ from kornia.utils import (
)
from kornia.augmentation import (
random_hflip,
- RandomHorizontalFlip,
)
from kornia.geometry import *
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 96d1849d7..782197c48 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -1,3 +1,3 @@
-from .augmentations import RandomHorizontalFlip, random_hflip
+from kornia.augmentation.augmentations import *
__all__ = ["random_hflip", "RandomHorizontalFlip"]
diff --git a/kornia/augmentation/augmentations.py b/kornia/augmentation/augmentations.py
index 413701d81..d78a27c24 100644
--- a/kornia/augmentation/augmentations.py
+++ b/kornia/augmentation/augmentations.py
@@ -1,9 +1,13 @@
+from typing import Tuple, Union
import torch
import torch.nn as nn
-from typing import Tuple
+
from kornia.geometry.transform.flips import hflip
+UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
+
+
class RandomHorizontalFlip(nn.Module):
r"""Horizontally flip a tensor image or a batch of tensor images randomly with a given probability.
@@ -11,60 +15,75 @@ class RandomHorizontalFlip(nn.Module):
Args:
p (float): probability of the image being flipped. Default value is 0.5
+ return_transformation (bool): if ``True`` return the matrix describing the transformation applied to each
+ input tensor.
"""
- def __init__(self, p=0.5):
+ def __init__(self, p: float = 0.5, return_transformation: bool = False) -> None:
super(RandomHorizontalFlip, self).__init__()
- self.p: float = p
+ self.p = p
+ self.return_transformation = return_transformation
- def __repr__(self):
- repr = "(p={0})".format(self.p)
+ def __repr__(self) -> str:
+ repr = f"(p={self.p})"
return self.__class__.__name__ + repr
- def forward(self, input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore
- return random_hflip(input, self.p)
+ def forward(self, input: torch.Tensor) -> UnionType: # type: ignore
+ return random_hflip(input, self.p, self.return_transformation)
-def random_hflip(input, p=0.5) -> Tuple[torch.Tensor, torch.Tensor]:
-
+def random_hflip(input: torch.Tensor, p: float = 0.5, return_transformation: bool = False) -> UnionType:
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
+ return_transformation (bool): if ``True`` return the matrix describing the transformation applied to each
+ input tensor.
+
Returns:
torch.Tensor: The horizontally flipped input
- torch.Tensor: The applied transformation matrix
+ torch.Tensor: The applied transformation matrix if return_transformation flag is set to ``True``
"""
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.")
+ raise TypeError(f"The probability should be a float number. Got {type(p)}")
+
+ if not isinstance(return_transformation, bool):
+ raise TypeError(f"The return_transformation flag must be a bool. Got {type(return_transformation)}")
device: torch.device = input.device
+ dtype: torch.dtype = input.dtype
- 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.empty(1, device=device).uniform_(0, 1)
+ input = input.unsqueeze(0)
+ input = input.view((-1, (*input.shape[-3:])))
+ probs: torch.Tensor = torch.empty(input.shape[0], device=device).uniform_(0, 1)
to_flip: torch.Tensor = probs < p
+ flipped: torch.Tensor = input.clone()
+
+ trans_mat: torch.Tensor = torch.eye(3, device=device, dtype=dtype).expand(input.shape[0], -1, -1)
if input[to_flip].nelement() != 0:
- flipped: torch.Tensor = 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]
+ flipped[to_flip] = hflip(input[to_flip])
+ flipped.squeeze_()
+
+ if return_transformation:
+
+ w: int = input.shape[-2]
+ flip_mat: torch.Tensor = torch.tensor([[-1, 0, w],
+ [0, 1, 0],
+ [0, 0, 0]])
+
+ trans_mat[to_flip] = flip_mat.to(device).to(dtype)
- 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 flipped, trans_mat
+ return flipped
- return input, torch.eye(3).unsqueeze(0).repeat(input.shape[0], 1, 1)
+ flipped.squeeze_()
+ return (flipped, trans_mat) if return_transformation else flipped
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 8417506e8..cc243f958 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -5,19 +5,22 @@ import pytest
import kornia.testing as utils # test utils
from torch.testing import assert_allclose
from torch.autograd import gradcheck
+from kornia.augmentation import RandomHorizontalFlip
class TestRandomHorizontalFlip:
def smoke_test(self):
- f = kornia.RandomHorizontalFlip(0.5)
+ f = 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.)
+ f = RandomHorizontalFlip(p=1.0, return_transformation=True)
+ f1 = RandomHorizontalFlip(p=0., return_transformation=True)
+ f2 = RandomHorizontalFlip(p=1.)
+ f3 = RandomHorizontalFlip(p=0.)
input = torch.tensor([[0., 0., 0.],
[0., 0., 0.],
@@ -39,19 +42,21 @@ class TestRandomHorizontalFlip:
assert (f(input)[1] == expected_transform).all()
assert (f1(input)[0] == input).all()
assert (f1(input)[1] == identity).all()
+ assert (f2(input) == expected).all()
+ assert (f3(input) == input).all()
def test_batch_random_hflip(self):
- f = kornia.RandomHorizontalFlip(p=1.0)
- f1 = kornia.RandomHorizontalFlip(p=0.0)
+ f = RandomHorizontalFlip(p=1.0, return_transformation=True)
+ f1 = RandomHorizontalFlip(p=0.0, return_transformation=True)
- input = torch.tensor([[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]) # 1 x 3 x 3
+ input = torch.tensor([[[[0., 0., 0.],
+ [0., 0., 0.],
+ [0., 1., 1.]]]]) # 1 x 1 x 3 x 3
- expected = torch.tensor([[[0., 0., 0.],
- [0., 0., 0.],
- [1., 1., 0.]]]) # 1 x 3 x 3
+ expected = torch.tensor([[[[0., 0., 0.],
+ [0., 0., 0.],
+ [1., 1., 0.]]]]) # 1 x 1 x 3 x 3
expected_transform = torch.tensor([[[-1., 0., 3.],
[0., 1., 0.],
@@ -61,10 +66,10 @@ class TestRandomHorizontalFlip:
[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
+ input = input.repeat(5, 3, 1, 1) # 5 x 3 x 3 x 3
+ expected = expected.repeat(5, 3, 1, 1) # 5 x 3 x 3 x 3
+ expected_transform = expected_transform.repeat(5, 1, 1) # 5 x 3 x 3
+ identity = identity.repeat(5, 1, 1) # 5 x 3 x 3
assert (f(input)[0] == expected).all()
assert (f(input)[1] == expected_transform).all()
@@ -108,4 +113,4 @@ class TestRandomHorizontalFlip:
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.RandomHorizontalFlip(p=1.), (input, ), raise_exception=True)
+ assert gradcheck(RandomHorizontalFlip(p=1.), (input, ), raise_exception=True)