π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix bug in augmentation
dvd42e2e15284a9bb
diff --git a/kornia/augmentation/augmentations.py b/kornia/augmentation/augmentations.pyindex d904acbad..ab64ef7b7 100644--- a/kornia/augmentation/augmentations.py+++ b/kornia/augmentation/augmentations.py@@ -1,10 +1,14 @@-from typing import Tuple, Union, cast+from typing import Tuple, List, Union, castimport torchimport torch.nn as nn+from torch.distributions import Uniformfrom kornia.geometry.transform.flips import hflip+from kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHue+from kornia.geometry import piUnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]+FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]class RandomHorizontalFlip(nn.Module):@@ -73,6 +77,52 @@ class RandomHorizontalFlip(nn.Module):return random_hflip(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.++ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.++ Args:+ brightness (float or tuple): Default value is 0+ contrast (float or tuple): Default value is 0+ saturation (float or tuple): Default value is 0+ hue (float or tuple): Default value is 0+ """++ def __init__(self, brightness: FloatUnionType = 0., contrast: FloatUnionType = 0.,+ saturation: FloatUnionType = 0., hue: FloatUnionType = 0., return_transform: bool = False) -> None:+ super(ColorJitter, self).__init__()+ self.brightness: FloatUnionType = brightness+ self.contrast: FloatUnionType = contrast+ self.saturation: FloatUnionType = saturation+ self.hue: FloatUnionType = hue+ self.return_transform: bool = return_transform++ def __repr__(self) -> str:+ repr = f"(brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation},\+ hue={self.hue}, return_transform={self.return_transform})"+ return self.__class__.__name__ + repr++ def forward(self, input: UnionType) -> UnionType: # type: ignore++ if isinstance(input, tuple):++ jittered: torch.Tensor = cast(+ torch.Tensor,+ color_jitter(+ input[0],+ brightness=self.brightness,+ contrast=self.contrast,+ saturation=self.saturation,+ hue=self.hue,+ return_transform=False))++ return jittered, input[1]++ return color_jitter(input, self.brightness, self.contrast, self.saturation, self.hue, self.return_transform)++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)`.@@ -102,18 +152,19 @@ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = Finput = 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 < pflipped: torch.Tensor = input.clone()- trans_mat: torch.Tensor = torch.eye(3, device=device, dtype=dtype).expand(input.shape[0], -1, -1)-flipped[to_flip] = hflip(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)+w: int = input.shape[-2]flip_mat: torch.Tensor = torch.tensor([[-1, 0, w],[0, 1, 0],@@ -124,3 +175,106 @@ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = Freturn flipped, trans_matreturn flipped+++def color_jitter(input: torch.Tensor, brightness: FloatUnionType = 0.,+ contrast: FloatUnionType = 0., saturation: FloatUnionType = 0.,+ hue: FloatUnionType = 0., return_transform: bool = False) -> UnionType:+ r"""Random color jiter of an image or batch of images.++ See :class:`~kornia.augmentation.ColorJitter` for details.+ """++ def _check_and_bound(factor: FloatUnionType, name: str, center: float = 0.,+ bounds: Tuple[float, float] = (0, float('inf')),+ device: torch.device = torch.device('cpu'),+ dtype: torch.dtype = torch.float32) -> torch.Tensor:+ r"""Check inputs and compute the corresponding factor bounds+ """++ if isinstance(factor, float):++ if factor < 0:+ raise ValueError(f"If {name} is a single number number, it must be non negative. Got {factor}")++ factor_bound = torch.tensor([center - factor, center + factor])+ factor_bound = torch.clamp(factor_bound, bounds[0], bounds[1])++ elif (isinstance(factor, torch.Tensor) and factor.dim() == 0):++ if factor < 0:+ raise ValueError(f"If {name} is a single number number, it must be non negative. Got {factor}")++ factor_bound = torch.tensor([torch.tensor(center) - factor, torch.tensor(center) + factor])+ factor_bound = torch.clamp(factor_bound, bounds[0], bounds[1])++ elif isinstance(factor, (tuple, list)) and len(factor) == 2:++ if not bounds[0] <= factor[0] <= factor[1] <= bounds[1]:+ raise ValueError(f"{name}[0] should be smaller than {name}[1] got {factor}")++ factor_bound = torch.tensor(factor)++ elif isinstance(factor, torch.Tensor) and factor.shape[0] == 2 and factor.dim() == 1:++ if not bounds[0] <= factor[0] <= factor[1] <= bounds[1]:+ raise ValueError(f"{name}[0] should be smaller than {name}[1] got {factor}")++ factor_bound = factor++ else:++ raise TypeError(+ f"The {name} should be a float number or a tuple with length 2 whose values move between {bounds}.")++ return factor_bound.to(device).to(dtype)++ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ 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++ brightness_bound: torch.Tensor = _check_and_bound(+ brightness, 'brightness', bounds=(+ float('-inf'), float('inf')), device=device, dtype=dtype)+ contrast_bound: torch.Tensor = _check_and_bound(contrast, 'contrast', center=1., device=device, dtype=dtype)+ saturation_bound: torch.Tensor = _check_and_bound(saturation, 'saturation', center=1., device=device, dtype=dtype)+ hue_bound: torch.Tensor = _check_and_bound(hue, 'hue', bounds=(-pi.item(), pi.item()), device=device, dtype=dtype)++ input = input.unsqueeze(0)+ input = input.view((-1, (*input.shape[-3:])))++ brightness_distribution = Uniform(brightness_bound[0], brightness_bound[1])+ brightness_factor = brightness_distribution.rsample([input.shape[0]])++ contrast_distribution = Uniform(contrast_bound[0], contrast_bound[1])+ contrast_factor = contrast_distribution.rsample([input.shape[0]])++ hue_distribution = Uniform(hue_bound[0], hue_bound[1])+ hue_factor = hue_distribution.rsample([input.shape[0]])++ saturation_distribution = Uniform(saturation_bound[0], saturation_bound[1])+ saturation_factor = saturation_distribution.rsample([input.shape[0]])++ transforms = nn.ModuleList([AdjustBrightness(brightness_factor),+ AdjustContrast(contrast_factor),+ AdjustSaturation(saturation_factor),+ AdjustHue(hue_factor)])++ jittered = input++ for idx in torch.randperm(4).tolist():+ t = transforms[idx]+ jittered = t(jittered)++ if return_transform:++ identity: torch.Tensor = torch.eye(3, device=device, dtype=dtype).repeat(input.shape[0], 1, 1)++ return jittered, identity++ return jittered