π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Splitted param_gen.py out of functional.py and updated API naming in params_gen.py
Jian Sab250d57a907
diff --git a/kornia/augmentation/augmentations.py b/kornia/augmentation/augmentations.pyindex d32109b4c..a0c5610b5 100644--- a/kornia/augmentation/augmentations.py+++ b/kornia/augmentation/augmentations.py@@ -4,6 +4,7 @@ import torchimport torch.nn as nnimport kornia.augmentation.functional as F+import kornia.augmentation.param_gen as pgUnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]@@ -39,10 +40,10 @@ class RandomFlip(AugmentationBase):@staticmethoddef get_params(batch_size: int, p: float = 0.5) -> Optional[Dict[str, torch.Tensor]]:- return F._get_random_p_params(batch_size, p)+ return pg._random_prob_gen(batch_size, p)def forward_flip(self, input: UnionType, flip_func: Callable,- params: Optional[Dict[str, torch.Tensor]]= None) -> UnionType: # type: ignore+ params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignoreif params is None:if isinstance(input, tuple):@@ -184,9 +185,9 @@ class ColorJitter(AugmentationBase):@staticmethoddef get_params(batch_size: int, brightness: FloatUnionType = 0., contrast: FloatUnionType = 0.,saturation: FloatUnionType = 0., hue: FloatUnionType = 0.) -> Dict[str, torch.Tensor]:- return F._get_color_jitter_params(batch_size, brightness, contrast, saturation, hue)+ return pg._random_color_jitter_gen(batch_size, brightness, contrast, saturation, hue)- def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]]= None) -> UnionType: # type: ignore+ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignoreif params is None:if isinstance(input, tuple):batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1@@ -228,7 +229,7 @@ class RandomGrayscale(AugmentationBase):@staticmethoddef get_params(batch_size: int, p: float = .5) -> Dict[str, torch.Tensor]:- return F._get_random_p_params(batch_size, p)+ return pg._random_prob_gen(batch_size, p)def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignoreif params is None:diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.pyindex 0aecfe2cb..e2ceb4230 100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@ -1,14 +1,12 @@from typing import Tuple, List, Union, Dict-import warningsimport torchimport torch.nn as nn-from torch.distributions import Uniform+import kornia.augmentation.param_gen as pgfrom kornia.geometry.transform.flips import hflip, vflipfrom kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHuefrom kornia.color.gray import rgb_to_grayscale-from kornia.geometry import piUnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]@@ -16,52 +14,44 @@ FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False) -> UnionType:- warnings.warn("random_hflip is going to be deprecated. Please use kornia.augmentation.RandomHorizontalFlip instead.",- DeprecationWarning, stacklevel=1)if isinstance(input, tuple):batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1else:batch_size = input.shape[0] if len(input.shape) == 4 else 1- params = _get_random_p_params(batch_size, p=p)+ params = pg._random_prob_gen(batch_size, p=p)return apply_hflip(input, params, return_transform)def random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False) -> UnionType:- warnings.warn("random_vflip is going to be deprecated. Please use kornia.augmentation.RandomVerticalFlip instead.",- DeprecationWarning, stacklevel=1)if isinstance(input, tuple):batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1else:batch_size = input.shape[0] if len(input.shape) == 4 else 1- params = _get_random_p_params(batch_size, p=p)+ params = pg._random_prob_gen(batch_size, p=p)return apply_vflip(input, params, return_transform)def color_jitter(input: torch.Tensor, brightness: FloatUnionType = 0.,contrast: FloatUnionType = 0., saturation: FloatUnionType = 0.,hue: FloatUnionType = 0., return_transform: bool = False) -> UnionType:- warnings.warn("color_jitter is going to be deprecated. Please use kornia.augmentation.ColorJitter instead.",- DeprecationWarning, stacklevel=1)if isinstance(input, tuple):batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1else:batch_size = input.shape[0] if len(input.shape) == 4 else 1- params = _get_color_jitter_params(batch_size, brightness, contrast, saturation, hue)+ params = pg._random_color_jitter_gen(batch_size, brightness, contrast, saturation, hue)return apply_color_jitter(input, params, return_transform)def random_grayscale(input: torch.Tensor, p: float = 0.5, return_transform: bool = False):- warnings.warn("random_grayscale is going to be deprecated. Please use kornia.augmentation.RandomGrayScale instead.",- DeprecationWarning, stacklevel=1)if isinstance(input, tuple):batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1else:batch_size = input.shape[0] if len(input.shape) == 4 else 1- params = _get_random_p_params(batch_size, p=p)+ params = pg._random_prob_gen(batch_size, p=p)return apply_grayscale(input, params, return_transform)-def apply_hflip(input: torch.Tensor, params: dict, return_transform: bool = False) -> UnionType:+def apply_hflip(input: torch.Tensor, params: Dict[str, torch.Tensor], 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)`.@@ -119,7 +109,7 @@ def apply_hflip(input: torch.Tensor, params: dict, return_transform: bool = Falsreturn flipped-def apply_vflip(input: torch.Tensor, params: dict, return_transform: bool = False) -> UnionType:+def apply_vflip(input: torch.Tensor, params: Dict[str, torch.Tensor], 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)`.@@ -173,7 +163,7 @@ def apply_vflip(input: torch.Tensor, params: dict, return_transform: bool = Falsreturn flipped-def apply_color_jitter(input: torch.Tensor, params: dict, return_transform: bool = False) -> UnionType:+def apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False) -> UnionType:# TODO: params validationif not torch.is_tensor(input):@@ -214,86 +204,7 @@ def apply_color_jitter(input: torch.Tensor, params: dict, return_transform: boolreturn jittered-def _get_color_jitter_params(batch_size: int, brightness: FloatUnionType = 0.,- contrast: FloatUnionType = 0., saturation: FloatUnionType = 0.,- hue: FloatUnionType = 0.) -> Dict[str, torch.Tensor]:- 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)-- brightness_bound: torch.Tensor = _check_and_bound(- brightness, 'brightness', bounds=(- float('-inf'), float('inf')))- contrast_bound: torch.Tensor = _check_and_bound(contrast, 'contrast', center=1.)- saturation_bound: torch.Tensor = _check_and_bound(saturation, 'saturation', center=1.)- hue_bound: torch.Tensor = _check_and_bound(hue, 'hue', bounds=(-pi.item(), pi.item()))-- brightness_distribution = Uniform(brightness_bound[0], brightness_bound[1])- brightness_factor = brightness_distribution.rsample([batch_size])-- contrast_distribution = Uniform(contrast_bound[0], contrast_bound[1])- contrast_factor = contrast_distribution.rsample([batch_size])-- hue_distribution = Uniform(hue_bound[0], hue_bound[1])- hue_factor = hue_distribution.rsample([batch_size])-- saturation_distribution = Uniform(saturation_bound[0], saturation_bound[1])- saturation_factor = saturation_distribution.rsample([batch_size])-- return {- "brightness_factor": brightness_factor,- "contrast_factor": contrast_factor,- "hue_factor": hue_factor,- "saturation_factor": saturation_factor,- }---def apply_grayscale(input: torch.Tensor, params: dict, return_transform: bool = False) -> UnionType:+def apply_grayscale(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False) -> UnionType:"""params: {'bool_p': torch.Tensor}"""@@ -326,19 +237,3 @@ def apply_grayscale(input: torch.Tensor, params: dict, return_transform: bool =return grayscale, identityreturn grayscale---def _get_random_p_params(batch_size: int, p: float = .5) -> Dict[str, torch.Tensor]:- r"""Random grayscale of an image or batch of images.-- See :class:`~kornia.augmentation.RandomGrayscale` for details.- """-- 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)-- batch_prob: torch.Tensor = probs < p-- return {'batch_prob': batch_prob}diff --git a/kornia/augmentation/param_gen.py b/kornia/augmentation/param_gen.pynew file mode 100644index 000000000..e337f7f0f--- /dev/null+++ b/kornia/augmentation/param_gen.py@@ -0,0 +1,105 @@+from typing import Tuple, List, Union, Dict++import torch+from torch.distributions import Uniform++from kornia.geometry import pi+++UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]+FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]+++def _random_color_jitter_gen(batch_size: int, brightness: FloatUnionType = 0.,+ contrast: FloatUnionType = 0., saturation: FloatUnionType = 0.,+ hue: FloatUnionType = 0.) -> Dict[str, torch.Tensor]:+ 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)++ brightness_bound: torch.Tensor = _check_and_bound(+ brightness, 'brightness', bounds=(+ float('-inf'), float('inf')))+ contrast_bound: torch.Tensor = _check_and_bound(contrast, 'contrast', center=1.)+ saturation_bound: torch.Tensor = _check_and_bound(saturation, 'saturation', center=1.)+ hue_bound: torch.Tensor = _check_and_bound(hue, 'hue', bounds=(-pi.item(), pi.item()))++ brightness_distribution = Uniform(brightness_bound[0], brightness_bound[1])+ brightness_factor = brightness_distribution.rsample([batch_size])++ contrast_distribution = Uniform(contrast_bound[0], contrast_bound[1])+ contrast_factor = contrast_distribution.rsample([batch_size])++ hue_distribution = Uniform(hue_bound[0], hue_bound[1])+ hue_factor = hue_distribution.rsample([batch_size])++ saturation_distribution = Uniform(saturation_bound[0], saturation_bound[1])+ saturation_factor = saturation_distribution.rsample([batch_size])++ return {+ "brightness_factor": brightness_factor,+ "contrast_factor": contrast_factor,+ "hue_factor": hue_factor,+ "saturation_factor": saturation_factor,+ }+++def _random_prob_gen(batch_size: int, p: float = .5) -> Dict[str, torch.Tensor]:+ r"""Random grayscale of an image or batch of images.++ See :class:`~kornia.augmentation.RandomGrayscale` for details.+ """++ 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)++ batch_prob: torch.Tensor = probs < p++ return {'batch_prob': batch_prob}