π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Refactored AugmentationBase to be more clear
Jian S4057475c8500
diff --git a/kornia/augmentation/augmentations.py b/kornia/augmentation/augmentations.pyindex 6b3780bc2..f9b82c737 100644--- a/kornia/augmentation/augmentations.py+++ b/kornia/augmentation/augmentations.py@@ -11,47 +11,19 @@ FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]class AugmentationBase(nn.Module):- def __init__(self, return_transform: bool = False) -> None:+ def __init__(self, apply_fcn: Callable, return_transform: bool = False) -> None:super(AugmentationBase, self).__init__()self.return_transform = return_transform+ self._apply_fcn: Callable = apply_fcn- def __repr__(self) -> str:- repr = f"(return_transform={self.return_transform})"- return self.__class__.__name__ + repr-- def forward(self, input: UnionType) -> UnionType: # type: ignore- raise NotImplementedError("forward method is not implemented for this class.")-- @staticmethod- def get_params() -> Dict[str, torch.Tensor]:- raise NotImplementedError("forward method is not implemented for this class.")---class RandomFlip(AugmentationBase):- def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:- super(RandomFlip, self).__init__(return_transform)- self.p = p- self.return_transform = return_transform- self.flip_func = None-- def __repr__(self) -> str:- repr = f"(p={self.p}, return_transform={self.return_transform})"- return self.__class__.__name__ + repr-- @staticmethod- def get_params(batch_size: int, p: float = 0.5) -> Dict[str, torch.Tensor]:- 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-- if params is None:- 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- params = RandomFlip.get_params(batch_size, self.p)+ def infer_batch_size(self, input):+ 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+ return batch_size+ def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignoreif isinstance(input, tuple):inp: torch.Tensor = input[0]@@ -59,25 +31,22 @@ class RandomFlip(AugmentationBase):if self.return_transform:- out = flip_func(inp, params, return_transform=True)+ out = self._apply_fcn(inp, params, 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, flip_func(inp, params, return_transform=False))+ img = cast(torch.Tensor, self._apply_fcn(inp, params, return_transform=False))# Transform image but pass along the previous transformationreturn img, prev_trans- return flip_func(input, params, return_transform=self.return_transform)+ return self._apply_fcn(input, params, return_transform=self.return_transform)- def forward(self, input: UnionType) -> UnionType: # type: ignore- raise NotImplementedError("forward method is not implemented for this class.")--class RandomHorizontalFlip(RandomFlip):+class RandomHorizontalFlip(AugmentationBase):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)`.@@ -109,15 +78,22 @@ class RandomHorizontalFlip(RandomFlip):[0., 0., 1.]]]))"""-def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:- super(RandomHorizontalFlip, self).__init__(p=p, return_transform=return_transform)+ super(RandomHorizontalFlip, self).__init__(F.apply_hflip, return_transform)+ self.p: float = p++ @staticmethod+ def get_params(batch_size: int, p: float) -> Dict[str, torch.Tensor]:+ return pg._random_prob_gen(batch_size, p)def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore- return self.forward_flip(input, F.apply_hflip, params)+ if params is None:+ batch_size = self.infer_batch_size(input)+ params: Dict[str, torch.Tensor] = self.get_params(batch_size, self.p)+ return super().forward(input, params)-class RandomVerticalFlip(RandomFlip):+class RandomVerticalFlip(AugmentationBase):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)`.@@ -147,12 +123,19 @@ class RandomVerticalFlip(RandomFlip):[0., 0., 1.]]]))"""-def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:- super(RandomVerticalFlip, self).__init__(p=p, return_transform=return_transform)+ super(RandomVerticalFlip, self).__init__(F.apply_vflip, return_transform)+ self.p: float = p++ @staticmethod+ def get_params(batch_size: int, p: float) -> Dict[str, torch.Tensor]:+ return pg._random_prob_gen(batch_size, p)def forward(self, input: UnionType, params: Optional[Dict[str, torch.Tensor]] = None) -> UnionType: # type: ignore- return self.forward_flip(input, F.apply_vflip, params)+ if params is None:+ batch_size = self.infer_batch_size(input)+ params: Dict[str, torch.Tensor] = self.get_params(batch_size, self.p)+ return super().forward(input, params)class ColorJitter(AugmentationBase):@@ -170,7 +153,7 @@ class ColorJitter(AugmentationBase):def __init__(self, brightness: FloatUnionType = 0., contrast: FloatUnionType = 0.,saturation: FloatUnionType = 0., hue: FloatUnionType = 0., return_transform: bool = False) -> None:- super(ColorJitter, self).__init__()+ super(ColorJitter, self).__init__(F.apply_color_jitter, return_transform)self.brightness: FloatUnionType = brightnessself.contrast: FloatUnionType = contrastself.saturation: FloatUnionType = saturation@@ -189,24 +172,9 @@ class ColorJitter(AugmentationBase):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- else:- batch_size = input.shape[0] if len(input.shape) == 4 else 1+ batch_size = self.infer_batch_size(input)params = ColorJitter.get_params(batch_size, self.brightness, self.contrast, self.saturation, self.hue)-- if isinstance(input, tuple):-- jittered: torch.Tensor = cast(- torch.Tensor,- F.apply_color_jitter(- input[0],- params=params,- return_transform=False))-- return jittered, input[1]-- return F.apply_color_jitter(input, params, self.return_transform)+ return super().forward(input, params)class RandomGrayscale(AugmentationBase):@@ -220,7 +188,7 @@ class RandomGrayscale(AugmentationBase):"""def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:- super(RandomGrayscale, self).__init__(return_transform)+ super(RandomGrayscale, self).__init__(F.apply_grayscale, return_transform)self.p = pdef __repr__(self) -> str:@@ -233,21 +201,6 @@ class RandomGrayscale(AugmentationBase):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- else:- batch_size = input.shape[0] if len(input.shape) == 4 else 1+ batch_size = self.infer_batch_size(input)params = RandomGrayscale.get_params(batch_size, self.p)-- if isinstance(input, tuple):-- output: torch.Tensor = cast(- torch.Tensor,- F.apply_grayscale(- input[0],- params=params,- return_transform=False))-- return output, input[1]-- return F.apply_grayscale(input, params=params, return_transform=self.return_transform)+ return super().forward(input, params)diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.pyindex 17de76229..af35a4aed 100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@ -16,8 +16,8 @@ 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:"""Generate params and apply operation on input tensor.- See :class:`~kornia.augmentation.param_gen._random_prob_gen` for details.- See :class:`~kornia.augmentation.functional.apply_hflip` for details.+ See :function:`~kornia.augmentation.param_gen._random_prob_gen` for details.+ See :function:`~kornia.augmentation.functional.apply_hflip` for details."""if isinstance(input, tuple):batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1@@ -30,8 +30,8 @@ def random_hflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = Fdef random_vflip(input: torch.Tensor, p: float = 0.5, return_transform: bool = False) -> UnionType:"""Generate params and apply operation on input tensor.- See :class:`~kornia.augmentation.param_gen._random_prob_gen` for details.- See :class:`~kornia.augmentation.functional.apply_vflip` for details.+ See :function:`~kornia.augmentation.param_gen._random_prob_gen` for details.+ See :function:`~kornia.augmentation.functional.apply_vflip` for details."""if isinstance(input, tuple):batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1@@ -46,8 +46,8 @@ def color_jitter(input: torch.Tensor, brightness: FloatUnionType = 0.,hue: FloatUnionType = 0., return_transform: bool = False) -> UnionType:"""Generate params and apply operation on input tensor.- See :class:`~kornia.augmentation.param_gen._random_color_jitter_gen` for details.- See :class:`~kornia.augmentation.functional.apply_color_jitter` for details.+ See :function:`~kornia.augmentation.param_gen._random_color_jitter_gen` for details.+ See :function:`~kornia.augmentation.functional.apply_color_jitter` for details."""if isinstance(input, tuple):batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1@@ -60,8 +60,8 @@ def color_jitter(input: torch.Tensor, brightness: FloatUnionType = 0.,def random_grayscale(input: torch.Tensor, p: float = 0.5, return_transform: bool = False):"""Generate params and apply operation on input tensor.- See :class:`~kornia.augmentation.param_gen._random_prob_gen` for details.- See :class:`~kornia.augmentation.functional.apply_grayscale` for details.+ See :function:`~kornia.augmentation.param_gen._random_prob_gen` for details.+ See :function:`~kornia.augmentation.functional.apply_grayscale` for details."""if isinstance(input, tuple):batch_size = input[0].shape[0] if len(input[0].shape) == 4 else 1@@ -77,7 +77,7 @@ def apply_hflip(input: torch.Tensor, params: Dict[str, torch.Tensor], return_traArgs:params (dict): A dict that must have {'batch_prob': torch.Tensor}. Can be generated from- kornia.augmentation.param_gen._random_prob_gen+ kornia.augmentation.param_gen._random_prob_gen.return_transform (bool): if ``True`` return the matrix describing the transformation applied to eachinput tensor.@@ -136,7 +136,7 @@ def apply_vflip(input: torch.Tensor, params: Dict[str, torch.Tensor], return_traArgs:params (dict): A dict that must have {'batch_prob': torch.Tensor}. Can be generated from- kornia.augmentation.param_gen._random_prob_gen+ kornia.augmentation.param_gen._random_prob_gen.return_transform (bool): if ``True`` return the matrix describing the transformation applied to eachinput tensor.@@ -188,6 +188,7 @@ def apply_vflip(input: torch.Tensor, params: Dict[str, torch.Tensor], return_tradef apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False) -> UnionType:"""Apply Color Jitter 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)`.+Args:params (dict): A dict that must have {'brightness_factor': torch.Tensor,@@ -197,6 +198,7 @@ def apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor], ret}. Can be generated from kornia.augmentation.param_gen._random_color_jitter_genreturn_transform (bool): if ``True`` return the matrix describing the transformation applied to eachinput tensor.+Returns:torch.Tensor: The color jitterred inputtorch.Tensor: The applied transformation matrix :math: `(*, 3, 3)` if return_transform flag@@ -245,11 +247,13 @@ def apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor], retdef apply_grayscale(input: torch.Tensor, params: Dict[str, torch.Tensor], return_transform: bool = False) -> UnionType:"""Apply Gray Scale on a tensor image or a batch of tensor images with given random parameters.Input should be a tensor of shape (3, H, W) or a batch of tensors :math:`(*, 3, H, W)`.+Args:params (dict): A dict that must have {'batch_prob': torch.Tensor}. Can be generated fromkornia.augmentation.param_gen._random_prob_genreturn_transform (bool): if ``True`` return the matrix describing the transformation applied to eachinput tensor.+Returns:torch.Tensor: The grayscaled inputtorch.Tensor: The applied transformation matrix :math: `(*, 3, 3)` if return_transform flagdiff --git a/kornia/augmentation/param_gen.py b/kornia/augmentation/param_gen.pyindex a512a9e7b..1db3a1132 100644--- a/kornia/augmentation/param_gen.py+++ b/kornia/augmentation/param_gen.py@@ -26,9 +26,7 @@ def _random_color_jitter_gen(batch_size: int, brightness: FloatUnionType = 0.,"""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:+ bounds: Tuple[float, float] = (0, float('inf'))) -> torch.Tensor:r"""Check inputs and compute the corresponding factor bounds"""@@ -67,7 +65,7 @@ def _random_color_jitter_gen(batch_size: int, brightness: FloatUnionType = 0.,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)+ return factor_boundbrightness_bound: torch.Tensor = _check_and_bound(brightness, 'brightness', bounds=(