π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
update random_perspective with new structure
edgarriba890071f9fba6
diff --git a/kornia/__init__.py b/kornia/__init__.pyindex 3adedb314..81e520d68 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -4,7 +4,10 @@ import sysif sys.version_info < (3, 6, 0):raise RuntimeError("Kornia requires Python 3.6.0 or later")-from .version import __version__+try:+ from .version import __version__ # noqa: F401+except ImportError:+ passfrom kornia import augmentationfrom kornia import colordiff --git a/kornia/augmentation/_perspective.py b/kornia/augmentation/_perspective.pynew file mode 100644index 000000000..0eb915b28--- /dev/null+++ b/kornia/augmentation/_perspective.py@@ -0,0 +1,49 @@+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_perspectivediff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex cbe3d47c8..59669f4ee 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -79,6 +79,7 @@ class RandomHorizontalFlip(AugmentationBase):[0., 0., 1.]]]))"""+def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:super(RandomHorizontalFlip, self).__init__(F.apply_hflip, return_transform)self.p: float = p@@ -124,6 +125,7 @@ class RandomVerticalFlip(AugmentationBase):[0., 0., 1.]]]))"""+def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:super(RandomVerticalFlip, self).__init__(F.apply_vflip, return_transform)self.p: float = p@@ -240,3 +242,33 @@ class RandomRectangleErasing(nn.Module):self.erase_scale_range,self.aspect_ratio_range)+++class RandomPerspective(nn.Module):+ r"""Performs Perspective transformation of the given torch.Tensor randomly with a given probability.++ Args:+ 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.+ """++ def __init__(self, distortion_scale: float = 0.5, p: float = 0.5, return_transform: bool = False) -> None:+ super(RandomPerspective, self).__init__()+ self.p: float = p+ self.distortion_scale: float = distortion_scale+ self.return_transform: bool = return_transform++ def __repr__(self) -> str:+ 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++ 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)diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.pyindex 1a0f45103..b640740d3 100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@ -1,14 +1,16 @@-from typing import Tuple, List, Union, Dict+from typing import Tuple, List, Union, Dict, castimport torchimport torch.nn as nnfrom kornia.geometry.transform.flips import hflip, vflip+from kornia.geometry.transform import get_perspective_transform, warp_perspectivefrom kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHuefrom kornia.color.gray import rgb_to_grayscalefrom . import param_gen as pgfrom .erasing import erase_rectangles, get_random_rectangles_params+from ._perspective import _get_perspective_paramsUnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]@@ -327,3 +329,104 @@ def random_rectangle_erase()images = erase_rectangles(images, rect_params)return images+++def perspective(input: torch.Tensor,+ start_points: torch.Tensor,+ end_points: torch.Tensor,+ return_transform: bool = False) -> UnionType:+ r"""Perform perspective transform of the given torch.Tensor or batch of tensors.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape BxCxHxW.+ start_points (torch.Tensor): Tensor containing [top-left, top-right, bottom-right,+ bottom-left] of the orignal image with shape Bx4x2.+ end_points (torch.Tensor): Tensor containing [top-left, top-right, bottom-right,+ bottom-left] of the transformed image with shape Bx4x2.+ return_transform (bool): if ``True`` return the matrix describing the transformation+ 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.+ """+ 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)}")++ # 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 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)++ # compute and apply transform+ out_perspective: UnionType = perspective(+ x_data, start_points, end_points, return_transform+ )++ out_data: torch.Tensor = x_data.clone()++ 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_datadiff --git a/kornia/augmentation/perspective.py b/kornia/augmentation/perspective.pydeleted file mode 100644index bfd010d8a..000000000--- a/kornia/augmentation/perspective.py+++ /dev/null@@ -1,176 +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---def perspective(input: torch.Tensor,- start_points: torch.Tensor,- end_points: torch.Tensor,- return_transform: bool = False) -> UnionType:- r"""Perform perspective transform of the given torch.Tensor or batch of tensors.-- Args:- input (torch.Tensor): Tensor to be transformed with shape BxCxHxW.- start_points (torch.Tensor): Tensor containing [top-left, top-right, bottom-right,- bottom-left] of the orignal image with shape Bx4x2.- end_points (torch.Tensor): Tensor containing [top-left, top-right, bottom-right,- bottom-left] of the transformed image with shape Bx4x2.- return_transform (bool): if ``True`` return the matrix describing the transformation- 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 = kornia.get_perspective_transform(start_points, end_points)-- # apply the computed transform- height, width = input.shape[-2:]- img_warped: torch.Tensor = kornia.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.- """- 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)}")-- # 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 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)-- # compute and apply transform- out_perspective: UnionType = perspective(- x_data, start_points, end_points, return_transform- )-- out_data: torch.Tensor = x_data.clone()-- if return_transform:- x_warped, transform = out_perspective- 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---class RandomPerspective(nn.Module):- r"""Performs Perspective transformation of the given torch.Tensor randomly with a given probability.-- Args:- 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.- """- def __init__(self, distortion_scale: float = 0.5, p: float = 0.5, return_transform: bool = False) -> None:- super(RandomPerspective, self).__init__()- self.p: float = p- self.distortion_scale: float = distortion_scale- self.return_transform: bool = return_transform-- def __repr__(self) -> str:- 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-- if isinstance(input, tuple):- raise NotImplementedError("wait for AugmentationBase class")- return random_perspective(- input, distortion_scale=self.distortion_scale, p=self.p,- return_transform=self.return_transform)diff --git a/test/augmentation/test_perspective.py b/test/augmentation/test_perspective.pyindex 9ac68fe1b..2be9ddacf 100644--- a/test/augmentation/test_perspective.py+++ b/test/augmentation/test_perspective.py@@ -16,7 +16,7 @@ class TestPerspective:start_points = torch.rand(1, 4, 2).to(device)end_points = torch.rand(1, 4, 2).to(device)- out_perspective = kornia.augmentation.perspective(+ out_perspective = kornia.augmentation.functional.perspective(x_data, start_points, end_points, return_transform=False)assert out_perspective.shape == x_data.shape@@ -26,7 +26,7 @@ class TestPerspective:start_points = torch.rand(1, 4, 2).to(device)end_points = torch.rand(1, 4, 2).to(device)- out_perspective = kornia.augmentation.perspective(+ out_perspective = kornia.augmentation.functional.perspective(x_data, start_points, end_points, return_transform=True)assert isinstance(out_perspective, tuple)@@ -43,7 +43,8 @@ class TestPerspective:end_points = torch.rand(1, 4, 2).to(device)end_points = utils.tensor_to_gradcheck_var(end_points) # to var- assert gradcheck(kornia.augmentation.perspective, (input, start_points, end_points), raise_exception=True)+ assert gradcheck(kornia.augmentation.functional.perspective,+ (input, start_points, end_points), raise_exception=True)class TestRandomPerspective:@@ -53,7 +54,7 @@ class TestRandomPerspective:def test_smoke_no_transform(self, device):x_data = torch.rand(1, 2, 8, 9).to(device)- out_perspective = kornia.augmentation.random_perspective(+ out_perspective = kornia.augmentation.functional.random_perspective(x_data, 0.5, 0.5, return_transform=False)assert out_perspective.shape == x_data.shape@@ -61,7 +62,7 @@ class TestRandomPerspective:def test_smoke_transform(self, device):x_data = torch.rand(1, 2, 4, 5).to(device)- out_perspective = kornia.augmentation.random_perspective(+ out_perspective = kornia.augmentation.functional.random_perspective(x_data, 0.5, 0.5, return_transform=True)assert isinstance(out_perspective, tuple)