Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

proper support for nn.Sequential

dvd423b7cd76cb6e3
diff --git a/kornia/augmentation/augmentations.py b/kornia/augmentation/augmentations.py
index 2f4affe2e..79aa9a438 100644
--- a/kornia/augmentation/augmentations.py
+++ b/kornia/augmentation/augmentations.py
@@ -4,7 +4,6 @@ import torch.nn as nn
from kornia.geometry.transform.flips import hflip
-
UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
@@ -12,38 +11,72 @@ 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)`.
+ If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
+ the corresponding transformation matrix that has been applied to them. In this case the module
+ will Horizontally flip the tensors and concatenate the corresponding transformation matrix to the
+ previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` 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.
+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ wont be concatenated
+
+ Examples:
+ >>> input = torch.tensor([[[
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 1., 1.]]]])
+ >>> seq = nn.Sequential(kornia.augmentation.RandomHorizontalFlip(p=1.0, return_transform=True),
+ kornia.augmentation.RandomHorizontalFlip(p=1.0, return_transform=True)
+ )
+ >>> seq(input)
+ (tensor([[0., 0., 0.],
+ [0., 0., 0.],
+ [0., 1., 1.]]),
+ tensor([[[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]]]))
+
"""
- def __init__(self, p: float = 0.5, return_transformation: bool = False) -> None:
+ def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:
super(RandomHorizontalFlip, self).__init__()
self.p = p
- self.return_transformation = return_transformation
+ self.return_transform = return_transform
def __repr__(self) -> str:
- repr = f"(p={self.p})"
+ repr = f"(p={self.p}, return_transform={self.return_transform})"
return self.__class__.__name__ + repr
- def forward(self, input: torch.Tensor) -> UnionType: # type: ignore
- return random_hflip(input, self.p, self.return_transformation)
+ def forward(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> UnionType: # type: ignore
+
+ if isinstance(input, tuple):
+
+ if self.return_transform:
+ img, trans_mat = random_hflip(input[0], self.p, self.return_transform)
+ return img, input[1] @ trans_mat
+
+ # Transform image but pass along the previous transformation
+ return random_hflip(input[0], self.p, self.return_transform), input[1]
+
+
+ return random_hflip(input, self.p, self.return_transform)
-def random_hflip(input: torch.Tensor, p: float = 0.5, return_transformation: bool = False) -> UnionType:
+def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: 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
+ return_transform (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 if return_transformation flag is set to ``True``
+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)` if return_transform flag
+ is set to ``True``
"""
if not torch.is_tensor(input):
@@ -52,8 +85,8 @@ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transformation: boo
if not isinstance(p, float):
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)}")
+ if not isinstance(return_transform, bool):
+ raise TypeError(f"The return_transform flag must be a bool. Got {type(return_transform)}")
device: torch.device = input.device
dtype: torch.dtype = input.dtype
@@ -70,7 +103,7 @@ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transformation: boo
flipped[to_flip] = hflip(input[to_flip])
flipped.squeeze_()
- if return_transformation:
+ if return_transform:
w: int = input.shape[-2]
flip_mat: torch.Tensor = torch.tensor([[-1, 0, w],
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 51532fd4e..4be23e23a 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -1,10 +1,12 @@
-import kornia
-import torch
import pytest
+import torch
+import torch.nn as nn
-import kornia.testing as utils # test utils
from torch.testing import assert_allclose
from torch.autograd import gradcheck
+
+import kornia
+import kornia.testing as utils # test utils
from kornia.augmentation import RandomHorizontalFlip
@@ -12,13 +14,13 @@ class TestRandomHorizontalFlip:
def smoke_test(self):
f = RandomHorizontalFlip(0.5)
- repr = "RandomHorizontalFlip(p=0.5)"
+ repr = "RandomHorizontalFlip(p=0.5, return_transform=False)"
assert str(f) == repr
def test_random_hflip(self):
- f = RandomHorizontalFlip(p=1.0, return_transformation=True)
- f1 = RandomHorizontalFlip(p=0., return_transformation=True)
+ f = RandomHorizontalFlip(p=1.0, return_transform=True)
+ f1 = RandomHorizontalFlip(p=0., return_transform=True)
f2 = RandomHorizontalFlip(p=1.)
f3 = RandomHorizontalFlip(p=0.)
@@ -47,8 +49,8 @@ class TestRandomHorizontalFlip:
def test_batch_random_hflip(self):
- f = RandomHorizontalFlip(p=1.0, return_transformation=True)
- f1 = RandomHorizontalFlip(p=0.0, return_transformation=True)
+ f = RandomHorizontalFlip(p=1.0, return_transform=True)
+ f1 = RandomHorizontalFlip(p=0.0, return_transform=True)
input = torch.tensor([[[[0., 0., 0.],
[0., 0., 0.],
@@ -76,6 +78,34 @@ class TestRandomHorizontalFlip:
assert (f1(input)[0] == input).all()
assert (f1(input)[1] == identity).all()
+
+ def test_sequential(self):
+
+ f = nn.Sequential(
+ RandomHorizontalFlip(1.0, return_transform=True),
+ RandomHorizontalFlip(1.0, return_transform=True),
+ )
+ f1 = nn.Sequential(
+ RandomHorizontalFlip(1.0, return_transform=True),
+ RandomHorizontalFlip(1.0),
+ )
+
+ input = torch.tensor([[[[0., 0., 0.],
+ [0., 0., 0.],
+ [0., 1., 1.]]]]) # 1 x 1 x 3 x 3
+
+ expected_transform = torch.tensor([[[-1., 0., 3.],
+ [0., 1., 0.],
+ [0., 0., 1.]]]) # 1 x 3 x 3
+
+ expected_transform_1 = expected_transform @ expected_transform
+
+ assert(f(input)[0] == input).all()
+ assert(f(input)[1] == expected_transform_1).all()
+ assert(f1(input)[0] == input).all()
+ assert(f1(input)[1] == expected_transform).all()
+
+
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self):
@torch.jit.script