π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
add random_vflip and RandomVerticalFlip
kshitij123454e36b2bb2e77
diff --git a/kornia/__init__.py b/kornia/__init__.pyindex 8474f621b..845dc798d 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -82,6 +82,7 @@ from kornia.utils import ()from kornia.augmentation import (random_hflip,+ random_vflip,color_jitter,)diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 5235dd15c..5425899bf 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -4,6 +4,8 @@ from kornia.augmentation.random_erasing import *__all__ = ["random_hflip","RandomHorizontalFlip",+ "random_vflip",+ "RandomVerticalFlip","color_jitter","ColorJitter","RandomRectangleErasing",diff --git a/kornia/augmentation/augmentations.py b/kornia/augmentation/augmentations.pyindex ab64ef7b7..ba9ef31ca 100644--- a/kornia/augmentation/augmentations.py+++ b/kornia/augmentation/augmentations.py@@ -1,9 +1,10 @@from typing import Tuple, List, Union, cast+import torchimport torch.nn as nnfrom torch.distributions import Uniform-from kornia.geometry.transform.flips import hflip+from kornia.geometry.transform.flips import hflip, vflipfrom kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHuefrom kornia.geometry import pi@@ -77,6 +78,70 @@ class RandomHorizontalFlip(nn.Module):return random_hflip(input, p=self.p, return_transform=self.return_transform)+class RandomVerticalFlip(nn.Module):++ r"""Vertically 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 Vertically 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_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.RandomVerticalFlip(p=1.0, return_transform=True))+ >>> seq(input)+ (tensor([[0., 1., 1.],+ [0., 0., 0.],+ [0., 0., 0.]]),+ tensor([[[1., 0., 0.],+ [0., -1., 3.],+ [0., 0., 1.]]]))++ """++ def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:+ super(RandomVerticalFlip, self).__init__()+ self.p = p+ self.return_transform = return_transform++ def __repr__(self) -> str:+ repr = f"(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):++ inp: torch.Tensor = input[0]+ prev_trans: torch.Tensor = input[1]++ if self.return_transform:++ out = random_vflip(inp, p=self.p, return_transform=True)+ img: torch.Tensor = out[0]+ trans_mat: torch.Tensor = out[1]++ return img, prev_trans @ trans_mat++ # https://mypy.readthedocs.io/en/latest/casts.html cast the return type to please mypy gods+ img = cast(torch.Tensor, random_vflip(inp, p=self.p, return_transform=False))++ # Transform image but pass along the previous transformation+ return img, prev_trans++ return random_vflip(input, p=self.p, return_transform=self.return_transform)++class ColorJitter(nn.Module):r"""Change the brightness, contrast, saturation and hue randomly given tensor image or a batch of tensor images.@@ -177,6 +242,60 @@ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = Freturn flipped+def random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False) -> UnionType:+ r"""Vertically 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_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor.++ Returns:+ torch.Tensor: The vertically flipped input+ torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)` if return_transform 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. 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++ 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()++ flipped[to_flip] = vflip(input[to_flip])+ flipped.squeeze_()++ if return_transform:++ trans_mat: torch.Tensor = torch.eye(3, device=device, dtype=dtype).repeat(input.shape[0], 1, 1)++ h: int = input.shape[-2]+ flip_mat: torch.Tensor = torch.tensor([[1, 0, 0],+ [0, -1, h],+ [0, 0, 1]])++ trans_mat[to_flip] = flip_mat.to(device).to(dtype)++ return flipped, trans_mat++ return flipped++def color_jitter(input: torch.Tensor, brightness: FloatUnionType = 0.,contrast: FloatUnionType = 0., saturation: FloatUnionType = 0.,hue: FloatUnionType = 0., return_transform: bool = False) -> UnionType: