Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

improve random_perspective

edgarriba0663b0c81ad7
diff --git a/kornia/augmentation/_perspective.py b/kornia/augmentation/_perspective.py
deleted file mode 100644
index 0eb915b28..000000000
--- a/kornia/augmentation/_perspective.py
+++ /dev/null
@@ -1,49 +0,0 @@
-from typing import Union, Tuple, cast
-
-import torch
-import torch.nn as nn
-
-import kornia
-
-
-UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
-
-
-def _get_perspective_params(
- batch_size: int,
- width: int, height: int,
- distortion_scale: float
-) -> Tuple[torch.Tensor, torch.Tensor]:
- r"""Get parameters for ``perspective`` for a random perspective transform.
-
- Args:
- batch_size (int): the tensor batch size.
- width (int): width of the image.
- height (int) : height of the image.
- distortion_scale (float): it controls the degree of distortion and ranges from 0 to 1. Default value is 0.5.
-
- Returns:
- List containing [top-left, top-right, bottom-right, bottom-left] of the original image,
- List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image.
- The points are in -x order.
- """
- start_points: torch.Tensor = torch.tensor([[
- [0., 0],
- [0, width - 1],
- [height - 1, 0],
- [height - 1, width - 1],
- ]]).expand(batch_size, -1, -1)
-
- # generate random offset not larger than half of the image
- fx: float = distortion_scale * width / 2
- fy: float = distortion_scale * height / 2
-
- factor = torch.tensor([fy, fx]).view(-1, 1, 2)
- offset = factor * torch.rand(batch_size, 4, 2) * 2 - 1
-
- end_points = start_points + offset
-
- return start_points, end_points
-
-
-# TODO: implement apply_perspective
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 59669f4ee..82ad01882 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -24,6 +24,13 @@ class AugmentationBase(nn.Module):
batch_size = input.shape[0] if len(input.shape) == 4 else 1
return batch_size
+ def infer_image_shape(self, input: UnionType) -> Tuple[int, int]:
+ if isinstance(input, tuple):
+ data, _ = cast(Tuple, input)
+ else:
+ data = cast(torch.Tensor, input)
+ return data.shape[-2:]
+
def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore
if isinstance(input, tuple):
@@ -244,7 +251,7 @@ class RandomRectangleErasing(nn.Module):
)
-class RandomPerspective(nn.Module):
+class RandomPerspective(AugmentationBase):
r"""Performs Perspective transformation of the given torch.Tensor randomly with a given probability.
Args:
@@ -256,7 +263,7 @@ class RandomPerspective(nn.Module):
"""
def __init__(self, distortion_scale: float = 0.5, p: float = 0.5, return_transform: bool = False) -> None:
- super(RandomPerspective, self).__init__()
+ super(RandomPerspective, self).__init__(F.apply_perspective, return_transform)
self.p: float = p
self.distortion_scale: float = distortion_scale
self.return_transform: bool = return_transform
@@ -265,10 +272,14 @@ class RandomPerspective(nn.Module):
repr = f"(distortion_scale={self.distortion_scale}, p={self.p}, return_transform={self.return_transform})"
return self.__class__.__name__ + repr
- def forward(self, input: UnionType) -> UnionType: # type: ignore
+ @staticmethod
+ def get_params(batch_size: int, height: int, width: int, p: float,
+ distortion_scale: float) -> Dict[str, torch.Tensor]:
+ return pg._random_perspective_gen(batch_size, height, width, p, distortion_scale)
- if isinstance(input, tuple):
- raise NotImplementedError("wait for AugmentationBase class")
- return F.random_perspective(
- input, distortion_scale=self.distortion_scale, p=self.p,
- return_transform=self.return_transform)
+ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore
+ if params is None:
+ height, width = self.infer_image_shape(input)
+ batch_size: int = self.infer_batch_size(input)
+ params = self.get_params(batch_size, height, width, self.p, self.distortion_scale)
+ return super().forward(input, params)
diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.py
index b640740d3..a6d2cf908 100644
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@ -10,7 +10,6 @@ from kornia.color.gray import rgb_to_grayscale
from . import param_gen as pg
from .erasing import erase_rectangles, get_random_rectangles_params
-from ._perspective import _get_perspective_params
UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
@@ -75,6 +74,29 @@ def random_grayscale(input: torch.Tensor, p: float = 0.5, return_transform: bool
return apply_grayscale(input, params, return_transform)
+def random_perspective(input: torch.Tensor,
+ distortion_scale: float = 0.5,
+ p: float = 0.5,
+ return_transform: bool = False) -> UnionType:
+ r"""Performs Perspective transformation of the given torch.Tensor randomly with a given probability.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (*, C, H, W).
+ p (float): probability of the image being perspectively transformed. Default value is 0.5
+ distortion_scale(float): it controls the degree of distortion and ranges from 0 to 1. Default value is 0.5.
+ return_transform (bool): if ``True`` return the matrix describing the transformation
+ applied to each. Default: False.
+ input tensor.
+ """
+ if isinstance(input, tuple):
+ batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1
+ else:
+ batch_size = input.shape[0] if len(input.shape) == 4 else 1
+ height, width = input.shape[-2:]
+ params = pg._random_perspective_gen(batch_size, height, width, p, distortion_scale)
+ return apply_perspective(input, params, return_transform)
+
+
def apply_hflip(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False) -> UnionType:
r"""Apply Horizontally flip on a tensor image or a batch of tensor images with given random parameters.
Input should be a tensor of shape (H, W), (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
@@ -280,7 +302,7 @@ def apply_grayscale(input: torch.Tensor, params: Dict[str, torch.Tensor], return
grayscale: torch.Tensor = input.clone()
- to_gray = params['batch_prob'].to(device)
+ to_gray = params['batch_prob'].to(device, dtype)
grayscale[to_gray] = rgb_to_grayscale(input[to_gray])
if return_transform:
@@ -331,10 +353,9 @@ def random_rectangle_erase(
return images
-def perspective(input: torch.Tensor,
- start_points: torch.Tensor,
- end_points: torch.Tensor,
- return_transform: bool = False) -> UnionType:
+def apply_perspective(input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ return_transform: bool = False) -> UnionType:
r"""Perform perspective transform of the given torch.Tensor or batch of tensors.
Args:
@@ -347,86 +368,33 @@ def perspective(input: torch.Tensor,
applied to each. Default: False.
Returns:
- torch.Tensor: Perspectively transformed tensor.
- """
- if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if not torch.is_tensor(start_points):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(start_points)}")
-
- if not torch.is_tensor(end_points):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(end_points)}")
-
- # compute the homography between the input points
- transform: torch.Tensor = get_perspective_transform(start_points, end_points)
-
- # apply the computed transform
- height, width = input.shape[-2:]
- img_warped: torch.Tensor = warp_perspective(input, transform, (height, width))
-
- if return_transform:
- return img_warped, transform
-
- return img_warped
-
-
-def random_perspective(input: torch.Tensor,
- distortion_scale: float = 0.5,
- p: float = 0.5,
- return_transform: bool = False) -> UnionType:
- r"""Performs Perspective transformation of the given torch.Tensor randomly with a given probability.
-
- Args:
- input (torch.Tensor): Tensor to be transformed with shape (*, C, H, W).
- p (float): probability of the image being perspectively transformed. Default value is 0.5
- distortion_scale(float): it controls the degree of distortion and ranges from 0 to 1. Default value is 0.5.
- return_transform (bool): if ``True`` return the matrix describing the transformation
- applied to each. Default: False.
- input tensor.
+ torch.Tensor: Perspectively transformed tensor.
"""
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
- if len(input.shape) > 4:
- raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {input.shape}")
-
- if not isinstance(p, float):
- raise TypeError(f"The probability should be a float number. Got {type(p)}")
-
- 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
# arrange input data
x_data: torch.Tensor = input.view(-1, *input.shape[-3:])
batch_size, _, height, width = x_data.shape
- # sample probabilities
- probs: torch.Tensor = torch.rand(batch_size, device=x_data.device)
- mask: torch.Tensor = probs < p
+ # compute the homography between the input points
+ transform: torch.Tensor = get_perspective_transform(
+ params['start_points'], params['end_points']).to(device, dtype)
- # compute points
- start_points, end_points = (
- _get_perspective_params(batch_size, width, height, distortion_scale)
- )
- start_points = start_points.to(x_data.device, x_data.dtype)
- end_points = end_points.to(x_data.device, x_data.dtype)
+ out_data: torch.Tensor = x_data.clone()
- # compute and apply transform
- out_perspective: UnionType = perspective(
- x_data, start_points, end_points, return_transform
- )
+ # process valid samples
+ mask = params['batch_prob'].to(device)
- out_data: torch.Tensor = x_data.clone()
+ # apply the computed transform
+ height, width = x_data.shape[-2:]
+ out_data[mask] = warp_perspective(x_data[mask], transform[mask], (height, width))
if return_transform:
- x_warped, transform = out_perspective # type: ignore
- out_data[mask] = x_warped[mask]
- return out_data, transform
- else:
- x_warped = cast(torch.Tensor, out_perspective)
-
- out_data[mask] = x_warped[mask]
+ return out_data.view_as(input), transform
- return out_data
+ return out_data.view_as(input)
diff --git a/kornia/augmentation/param_gen.py b/kornia/augmentation/param_gen.py
index 7ffa099bc..2f9f76e62 100644
--- a/kornia/augmentation/param_gen.py
+++ b/kornia/augmentation/param_gen.py
@@ -116,8 +116,56 @@ def _random_prob_gen(batch_size: int, p: float = .5) -> Dict[str, torch.Tensor]:
if not isinstance(p, float):
raise TypeError(f"The probability should be a float number. Got {type(p)}")
- probs: torch.Tensor = torch.empty(batch_size, device='cpu').uniform_(0, 1)
+ probs: torch.Tensor = Uniform(0, 1).rsample((batch_size,))
batch_prob: torch.Tensor = probs < p
return {'batch_prob': batch_prob}
+
+
+def _get_perspective_params(batch_size: int, width: int, height: int, distortion_scale: float
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Get parameters for ``perspective`` for a random perspective transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ width (int): width of the image.
+ height (int) : height of the image.
+ distortion_scale (float): it controls the degree of distortion and ranges from 0 to 1. Default value is 0.5.
+
+ Returns:
+ List containing [top-left, top-right, bottom-right, bottom-left] of the original image,
+ List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image.
+ The points are in -x order.
+ """
+ start_points: torch.Tensor = torch.tensor([[
+ [0., 0],
+ [0, width - 1],
+ [height - 1, 0],
+ [height - 1, width - 1],
+ ]]).expand(batch_size, -1, -1)
+
+ # generate random offset not larger than half of the image
+ fx: float = distortion_scale * width / 2
+ fy: float = distortion_scale * height / 2
+
+ factor = torch.tensor([fy, fx]).view(-1, 1, 2)
+
+ rand_val: torch.Tensor = Uniform(0, 1).rsample((batch_size, 4, 2))
+ offset = 2 * factor - 1
+
+ end_points = start_points + offset
+
+ return start_points, end_points
+
+
+def _random_perspective_gen(
+ batch_size: int, height: int, width: int, p: float, distortion_scale: float
+) -> Dict[str, torch.Tensor]:
+ params: Dict[str, torch.Tensor] = _random_prob_gen(batch_size, p)
+ start_points, end_points = (
+ _get_perspective_params(batch_size, width, height, distortion_scale)
+ )
+ params['start_points'] = start_points
+ params['end_points'] = end_points
+ return params
diff --git a/test/augmentation/test_perspective.py b/test/augmentation/test_perspective.py
index 2be9ddacf..4b3926685 100644
--- a/test/augmentation/test_perspective.py
+++ b/test/augmentation/test_perspective.py
@@ -5,6 +5,7 @@ from torch.testing import assert_allclose
from torch.autograd import gradcheck
import kornia
+import kornia.augmentation.functional as F
import kornia.testing as utils # test utils
from test.common import device
@@ -13,38 +14,43 @@ class TestPerspective:
def test_smoke_no_transform(self, device):
x_data = torch.rand(1, 2, 3, 4).to(device)
+ batch_prob = torch.rand(1) < 0.5
start_points = torch.rand(1, 4, 2).to(device)
end_points = torch.rand(1, 4, 2).to(device)
- out_perspective = kornia.augmentation.functional.perspective(
- x_data, start_points, end_points, return_transform=False)
+ params = dict(batch_prob=batch_prob, start_points=start_points, end_points=end_points)
+ out_data = F.apply_perspective(x_data, params, return_transform=False)
- assert out_perspective.shape == x_data.shape
+ assert out_data.shape == x_data.shape
def test_smoke_transform(self, device):
x_data = torch.rand(1, 2, 3, 4).to(device)
+ batch_prob = torch.rand(1) < 0.5
start_points = torch.rand(1, 4, 2).to(device)
end_points = torch.rand(1, 4, 2).to(device)
- out_perspective = kornia.augmentation.functional.perspective(
- x_data, start_points, end_points, return_transform=True)
+ params = dict(batch_prob=batch_prob, start_points=start_points, end_points=end_points)
+ out_data = F.apply_perspective(x_data, params, return_transform=True)
- assert isinstance(out_perspective, tuple)
- assert len(out_perspective) == 2
- assert out_perspective[0].shape == x_data.shape
- assert out_perspective[1].shape == (1, 3, 3)
+ assert isinstance(out_data, tuple)
+ assert len(out_data) == 2
+ assert out_data[0].shape == x_data.shape
+ assert out_data[1].shape == (1, 3, 3)
def test_gradcheck(self, device):
input = torch.rand(1, 2, 3, 4).to(device)
input = utils.tensor_to_gradcheck_var(input) # to var
+ batch_prob = torch.rand(1) < 0.5
+
start_points = torch.rand(1, 4, 2).to(device)
start_points = utils.tensor_to_gradcheck_var(start_points) # to var
end_points = torch.rand(1, 4, 2).to(device)
end_points = utils.tensor_to_gradcheck_var(end_points) # to var
- assert gradcheck(kornia.augmentation.functional.perspective,
- (input, start_points, end_points), raise_exception=True)
+
+ params = dict(batch_prob=batch_prob, start_points=start_points, end_points=end_points)
+ assert gradcheck(F.apply_perspective, (input, params,), raise_exception=True)
class TestRandomPerspective:
@@ -90,4 +96,4 @@ class TestRandomPerspective:
def test_gradcheck(self, device):
input = torch.rand(1, 2, 5, 7).to(device)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.augmentation.random_perspective, (input, 0.), raise_exception=True)
+ assert gradcheck(F.random_perspective, (input, 0.), raise_exception=True)