🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Autoaugment functions. (#571)
shijianjian4eda8fef22f8
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 251b07149..5166984c5 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -16,6 +16,10 @@ __all__ = ["RandomRotation","CenterCrop","ColorJitter",+ "RandomSolarize",+ "RandomPosterize",+ "RandomSharpness",+ "RandomEqualize","Normalize","Denormalize"]diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex ca855d477..c249e36a3 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -21,6 +21,16 @@ from .types import (class AugmentationBase(nn.Module):+ r"""AugmentationBase base class for customized augmentation implementations. For any augmentation,+ the implementation of "generate_parameters" and "apply_transform" are required while the+ "compute_transformation" is only required when passing "return_transform" as True.++ Args:+ return_transform (bool): if ``True`` return the matrix describing the geometric transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation+ wont be concatenated.++ """def __init__(self, return_transform: bool = False) -> None:super(AugmentationBase, self).__init__()self.return_transform = return_transform@@ -65,7 +75,7 @@ class AugmentationBase(nn.Module):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)`.+ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, 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 modulewill Horizontally flip the tensors and concatenate the corresponding transformation matrix to the@@ -117,7 +127,7 @@ class RandomHorizontalFlip(AugmentationBase):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)`.+ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, 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 modulewill Vertically flip the tensors and concatenate the corresponding transformation matrix to the@@ -166,7 +176,7 @@ class RandomVerticalFlip(AugmentationBase):class ColorJitter(AugmentationBase):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)`.+ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.Args:brightness (float or tuple): Default value is 0@@ -491,7 +501,7 @@ class CenterCrop(AugmentationBase):class RandomRotation(AugmentationBase):r"""Rotate a tensor image or a batch of tensor images a random amount of degrees.- Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.+ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, 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 modulewill rotate the tensors and concatenate the corresponding transformation matrix to the@@ -726,11 +736,11 @@ class RandomMotionBlur(AugmentationBase):>>> input = torch.rand(1, 1, 5, 5)>>> motion_blur = RandomMotionBlur(3, 35., 0.5)>>> motion_blur(input)- tensor([[[[0.2724, 0.5235, 0.3796, 0.2433, 0.2210],- [0.3233, 0.5494, 0.5746, 0.5407, 0.3910],- [0.2101, 0.3865, 0.3072, 0.2510, 0.1902],- [0.2973, 0.6174, 0.6530, 0.4360, 0.2797],- [0.3804, 0.6217, 0.5535, 0.4855, 0.4249]]]])+ tensor([[[[0.2761, 0.5200, 0.3753, 0.2423, 0.2193],+ [0.3275, 0.5502, 0.5738, 0.5400, 0.3883],+ [0.2132, 0.3857, 0.3056, 0.2520, 0.1890],+ [0.3016, 0.6172, 0.6487, 0.4331, 0.2770],+ [0.3865, 0.6221, 0.5538, 0.4862, 0.4206]]]])"""def __init__(@@ -753,10 +763,216 @@ class RandomMotionBlur(AugmentationBase):def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:# TODO: Enable batch mode- return rg.motion_blur_param_generator(1, self.kernel_size, self.angle, self.direction, self.border_type)+ return rg.random_motion_blur_generator(1, self.kernel_size, self.angle, self.direction, self.border_type)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.compute_intensity_transformation(input, params)def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.apply_motion_blur(input, params)+++class RandomSolarize(AugmentationBase):+ r""" Solarize given tensor image or a batch of tensor images randomly.++ Args:+ thresholds (float or tuple): Default value is 0.1.+ If float x, threshold will be generated from (0.5 - x, 0.5 + x).+ If tuple (x, y), threshold will be generated from (x, y).+ additions (float or tuple): Default value is 0.1.+ If float x, addition will be generated from (-x, x).+ If tuple (x, y), addition will be generated from (x, y).+ same_on_batch (bool): apply the same transformation across the batch. Default: False+ 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+ Shape:+ - Input: :math:`(B, C, H, W)`+ - Output: :math:`(B, C, H, W)`++ Examples:+ >>> rng = torch.manual_seed(0)+ >>> input = torch.rand(1, 1, 5, 5)+ >>> solarize = RandomSolarize(0.1, 0.1)+ >>> solarize(input)+ tensor([[[[0.4132, 0.1412, 0.1790, 0.2226, 0.3980],+ [0.2754, 0.4194, 0.0130, 0.4538, 0.2771],+ [0.4394, 0.4923, 0.1129, 0.2594, 0.3844],+ [0.3909, 0.2118, 0.1094, 0.2516, 0.3728],+ [0.2278, 0.0000, 0.4876, 0.0353, 0.5100]]]])+ """++ def __init__(+ self, thresholds: FloatUnionType = 0.1, additions: FloatUnionType = 0.1,+ same_on_batch: bool = False, return_transform: bool = False+ ) -> None:+ super(RandomSolarize, self).__init__(return_transform)+ self.thresholds = thresholds+ self.additions = additions+ self.same_on_batch = same_on_batch++ def __repr__(self) -> str:+ return f"{self.__class__.__name__}(thresholds={self.thresholds}, additions={self.additions}, " \+ f"same_on_batch={self.same_on_batch}, return_transform={self.return_transform})"++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return rg.random_solarize_generator(batch_shape[0], self.thresholds, self.additions, self.same_on_batch)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_intensity_transformation(input, params)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.apply_solarize(input, params)+++class RandomPosterize(AugmentationBase):+ r""" Posterize given tensor image or a batch of tensor images randomly.++ Args:+ bits (int or tuple): Integer that ranged from (0, 8], in which 0 gives black image and 8 gives the original.+ If int x, bits will be generated from (x, 8).+ If tuple (x, y), bits will be generated from (x, y).+ Default value is 3.+ same_on_batch (bool): apply the same transformation across the batch. Default: False+ 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+ Shape:+ - Input: :math:`(B, C, H, W)`+ - Output: :math:`(B, C, H, W)`++ Examples::+ >>> rng = torch.manual_seed(0)+ >>> input = torch.rand(1, 1, 5, 5)+ >>> posterize = RandomPosterize(3)+ >>> posterize(input)+ tensor([[[[0.4706, 0.7529, 0.0627, 0.1255, 0.2824],+ [0.6275, 0.4706, 0.8784, 0.4392, 0.6275],+ [0.3451, 0.3765, 0.0000, 0.1569, 0.2824],+ [0.5020, 0.6902, 0.7843, 0.1569, 0.2510],+ [0.6588, 0.9098, 0.3765, 0.8471, 0.4078]]]])+ """++ def __init__(+ self, bits: Union[int, Tuple[int, int], torch.Tensor] = 3,+ same_on_batch: bool = False, return_transform: bool = False+ ) -> None:+ super(RandomPosterize, self).__init__(return_transform)+ self.bits = bits+ self.same_on_batch = same_on_batch++ def __repr__(self) -> str:+ return f"{self.__class__.__name__}(bits={self.bits}, same_on_batch={self.same_on_batch}, " \+ f"return_transform={self.return_transform})"++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return rg.random_posterize_generator(batch_shape[0], self.bits, self.same_on_batch)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_intensity_transformation(input, params)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.apply_posterize(input, params)+++class RandomSharpness(AugmentationBase):+ r""" Sharpen given tensor image or a batch of tensor images randomly.++ Args:+ sharpness (float or tuple): factor of sharpness strength. Must be above 0. Default value is 0.5.+ same_on_batch (bool): apply the same transformation across the batch. Default: False+ 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+ Shape:+ - Input: :math:`(B, C, H, W)`+ - Output: :math:`(B, C, H, W)`++ Examples::+ >>> rng = torch.manual_seed(0)+ >>> input = torch.rand(1, 1, 5, 5)+ >>> sharpness = RandomSharpness(1.)+ >>> sharpness(input)+ tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],+ [0.6341, 0.7720, 0.9537, 0.7566, 0.6323],+ [0.3489, 0.7325, 0.5629, 0.6284, 0.2939],+ [0.5185, 0.8648, 0.9106, 0.6249, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]],+ <BLANKLINE>+ [[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],+ [0.6341, 0.7720, 0.9537, 0.7566, 0.6323],+ [0.3489, 0.7325, 0.5629, 0.6284, 0.2939],+ [0.5185, 0.8648, 0.9106, 0.6249, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]],+ <BLANKLINE>+ [[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],+ [0.6341, 0.7720, 0.9537, 0.7566, 0.6323],+ [0.3489, 0.7325, 0.5629, 0.6284, 0.2939],+ [0.5185, 0.8648, 0.9106, 0.6249, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])+ """++ def __init__(+ self, sharpness: Union[float, Tuple[float, float], torch.Tensor] = 0.5, same_on_batch: bool = False,+ return_transform: bool = False+ ) -> None:+ super(RandomSharpness, self).__init__(return_transform)+ self.sharpness = sharpness+ self.same_on_batch = same_on_batch++ def __repr__(self) -> str:+ return f"{self.__class__.__name__}(sharpness={self.sharpness}, return_transform={self.return_transform})"++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return rg.random_sharpness_generator(batch_shape[0], self.sharpness, self.same_on_batch)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_intensity_transformation(input, params)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.apply_sharpness(input, params)+++class RandomEqualize(AugmentationBase):+ r""" Equalize given tensor image or a batch of tensor images randomly.++ Args:+ p (float): Probability to equalize an image. Default value is 0.5+ same_on_batch (bool): apply the same transformation across the batch. Default: False+ 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+ Shape:+ - Input: :math:`(B, C, H, W)`+ - Output: :math:`(B, C, H, W)`++ Examples::+ >>> rng = torch.manual_seed(0)+ >>> input = torch.rand(1, 1, 5, 5)+ >>> equalize = RandomEqualize(1.)+ >>> equalize(input)+ tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],+ [0.6341, 0.4901, 0.8964, 0.4556, 0.6323],+ [0.3489, 0.4017, 0.0223, 0.1689, 0.2939],+ [0.5185, 0.6977, 0.8000, 0.1610, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])+ """++ def __init__(+ self, p: float = 0.5, same_on_batch: bool = False, return_transform: bool = False+ ) -> None:+ super(RandomEqualize, self).__init__(return_transform)+ self.p = p+ self.same_on_batch = same_on_batch++ def __repr__(self) -> str:+ return f"{self.__class__.__name__}(p={self.p}, return_transform={self.return_transform})"++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return rg.random_prob_generator(batch_shape[0], self.p, self.same_on_batch)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_intensity_transformation(input, params)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.apply_equalize(input, params)diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.pyindex bf05f7bee..9ee5dabc6 100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@ -22,7 +22,11 @@ from kornia.color import (adjust_saturation,adjust_hue,adjust_gamma,- rgb_to_grayscale+ rgb_to_grayscale,+ solarize,+ equalize,+ posterize,+ sharpness)from kornia.filters import motion_blurfrom kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center@@ -195,10 +199,10 @@ def random_rotation(input: torch.Tensor, degrees: FloatUnionType, return_transfodef apply_hflip(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:r"""Apply Horizontally flip 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)`.+ Input should be a tensor of shape (H, W), (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.@@ -221,7 +225,7 @@ def compute_hflip_transformation(input: torch.Tensor, params: Dict[str, torch.Ter"""Compute the applied transformation matrix :math: `(*, 3, 3)`.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.@@ -243,10 +247,10 @@ def compute_hflip_transformation(input: torch.Tensor, params: Dict[str, torch.Tedef apply_vflip(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:r"""Apply vertically flip 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)`.+ Input should be a tensor of shape (H, W), (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.@@ -269,7 +273,7 @@ def compute_vflip_transformation(input: torch.Tensor, params: Dict[str, torch.Ter"""Compute the applied transformation matrix :math: `(*, 3, 3)`.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.@@ -293,17 +297,17 @@ def compute_vflip_transformation(input: torch.Tensor, params: Dict[str, torch.Tedef apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:r"""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)`.+ Input should be a tensor of shape (H, W), (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['brightness_factor']: The brightness factor.- params['contrast_factor']: The contrast factor.- params['hue_factor']: The hue factor.- params['saturation_factor']: The saturation factor.- params['order']: The order of applying color transforms.- 0 is brightness, 1 is contrast, 2 is saturation, 4 is hue.+ 0 is brightness, 1 is contrast, 2 is saturation, 4 is hue.Returns:torch.Tensor: The color jitterred input@@ -332,7 +336,7 @@ def compute_intensity_transformation(input: torch.Tensor, params: Dict[str, torcr"""Compute the applied transformation matrix :math: `(*, 3, 3)`.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['batch_prob']: A boolean tensor that indicating whether if to transform an image in a batch.@@ -350,7 +354,7 @@ def apply_grayscale(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torInput should be a tensor of shape (3, H, W) or a batch of tensors :math:`(*, 3, H, W)`.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['batch_prob']: A boolean tensor that indicating whether if to transform an image in a batch.@@ -378,13 +382,13 @@ def apply_perspective(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> tr"""Perform perspective transform of the given torch.Tensor or batch of tensors.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.- params['start_points']: Tensor containing [top-left, top-right, bottom-right,- bottom-left] of the orignal image with shape Bx4x2.+ bottom-left] of the orignal image with shape Bx4x2.- params['end_points']: Tensor containing [top-left, top-right, bottom-right,- bottom-left] of the transformed image with shape Bx4x2.+ bottom-left] of the transformed image with shape Bx4x2.- params['interpolation']: Integer tensor. NEAREST = 0, BILINEAR = 1.- params['align_corners']: Boolean tensor.@@ -429,13 +433,13 @@ def compute_perspective_transformation(input: torch.Tensor, params: Dict[str, tor"""Compute the applied transformation matrix :math: `(*, 3, 3)`.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['batch_prob']: A boolean tensor thatindicating whether if to transform an image in a batch.- params['start_points']: Tensor containing [top-left, top-right, bottom-right,- bottom-left] of the orignal image with shape Bx4x2.+ bottom-left] of the orignal image with shape Bx4x2.- params['end_points']: Tensor containing [top-left, top-right, bottom-right,- bottom-left] of the transformed image with shape Bx4x2.+ bottom-left] of the transformed image with shape Bx4x2.Returns:torch.Tensor: The applied transformation matrix :math: `(*, 3, 3)`@@ -451,7 +455,7 @@ def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.r"""Random affine transformation of the image keeping center invariant.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['angle']: Degrees of rotation.- params['translations']: Horizontal and vertical translations.@@ -493,7 +497,7 @@ def compute_affine_transformation(input: torch.Tensor, params: Dict[str, torch.Tr"""Compute the applied transformation matrix :math: `(*, 3, 3)`.Args:- input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['angle']: Degrees of rotation.- params['translations']: Horizontal and vertical translations.@@ -518,10 +522,10 @@ def compute_affine_transformation(input: torch.Tensor, params: Dict[str, torch.Tdef apply_rotation(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:r"""Rotate a tensor image or a batch of tensor images a random amount of degrees.- Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.+ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.Args:- input (torch.Tensor): input image.+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['degrees']: degree to be applied.@@ -544,7 +548,7 @@ def compute_rotate_tranformation(input: torch.Tensor, params: Dict[str, torch.Ter"""Compute the applied transformation matrix :math: `(*, 3, 3)`.Args:- input (torch.Tensor): input image.+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['degrees']: degree to be applied.@@ -572,7 +576,7 @@ def apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.TeOrder: top-left, top-right, bottom-right and bottom-left. The coordinates must be in the x, y order.Args:- input (torch.Tensor): input image.+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['src']: The applied cropping src matrix :math: `(*, 4, 2)`.- params['dst']: The applied cropping dst matrix :math: `(*, 4, 2)`.@@ -596,7 +600,7 @@ def compute_crop_transformation(input: torch.Tensor, params: Dict[str, torch.Tenr"""Compute the applied transformation matrix :math: `(*, 3, 3)`.Args:- input (torch.Tensor): input image.+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['src']: The applied cropping src matrix :math: `(*, 4, 2)`.- params['dst']: The applied cropping dst matrix :math: `(*, 4, 2)`.@@ -617,7 +621,7 @@ def apply_erase_rectangles(input: torch.Tensor, params: Dict[str, torch.Tensor])and size by input.size()Args:- input (torch.Tensor): input image.+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['widths']: widths tensor- params['heights']: heights tensor@@ -630,7 +634,9 @@ def apply_erase_rectangles(input: torch.Tensor, params: Dict[str, torch.Tensor])"""if not (params['widths'].size() == params['heights'].size() == params['xs'].size() == params['ys'].size()):raise TypeError(- "rectangle params components must have same shape"+ "rectangle params components must have same shape. "+ f"Got ({params['widths'].size()}, {params['heights'].size()}) "+ f"and ({params['xs'].size()}, {params['ys'].size()})")input = _transform_input(input)@@ -660,11 +666,11 @@ def apply_adjust_brightness(input: torch.Tensor, params: Dict[str, torch.Tensor]""" Wrapper for adjust_brightness for Torchvision-like param settings.Args:- input (torch.Tensor): Image/Input to be adjusted in the shape of (*, N).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['brightness_factor']: Brightness adjust factor per element- in the batch. 0 gives a black image, 1 does not modify the input image and 2 gives a- white image, while any other number modify the brightness.+ in the batch. 0 gives a black image, 1 does not modify the input image and 2 gives a+ white image, while any other number modify the brightness.Returns:torch.Tensor: Adjusted image.@@ -681,11 +687,11 @@ def apply_adjust_contrast(input: torch.Tensor, params: Dict[str, torch.Tensor])"""Wrapper for adjust_contrast for Torchvision-like param settings.Args:- input (torch.Tensor): Image to be adjusted in the shape of (*, N).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['contrast_factor']: Contrast adjust factor per element in the batch.- 0 generates a compleatly black image, 1 does not modify the input image while any other- non-negative number modify the brightness by this factor.+ 0 generates a compleatly black image, 1 does not modify the input image while any other+ non-negative number modify the brightness by this factor.Returns:torch.Tensor: Adjusted image.@@ -702,11 +708,11 @@ def apply_adjust_saturation(input: torch.Tensor, params: Dict[str, torch.Tensor]"""Wrapper for adjust_saturation for Torchvision-like param settings.Args:- input (torch.Tensor): Image/Tensor to be adjusted in the shape of (*, N).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['saturation_factor']: How much to adjust the saturation. 0 will give a black- and white image, 1 will give the original image while 2 will enhance the saturation- by a factor of 2.+ and white image, 1 will give the original image while 2 will enhance the saturation+ by a factor of 2.Returns:torch.Tensor: Adjusted image.@@ -723,12 +729,12 @@ def apply_adjust_hue(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> to"""Wrapper for adjust_hue for Torchvision-like param settings.Args:- input (torch.Tensor): Image/Tensor to be adjusted in the shape of (*, N).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['hue_factor']: How much to shift the hue channel. Should be in [-0.5, 0.5].- 0.5 and -0.5 give complete reversal of hue channel in HSV space in positive and negative- direction respectively. 0 means no shift. Therefore, both -0.5 and 0.5 will give an- image with complementary colors while 0 gives the original image.+ 0.5 and -0.5 give complete reversal of hue channel in HSV space in positive and negative+ direction respectively. 0 means no shift. Therefore, both -0.5 and 0.5 will give an+ image with complementary colors while 0 gives the original image.Returns:torch.Tensor: Adjusted image.@@ -745,11 +751,11 @@ def apply_adjust_gamma(input: torch.Tensor, params: Dict[str, torch.Tensor]) ->r"""Perform gamma correction on an image.Args:- input (torch.Tensor): Image/Tensor to be adjusted in the shape of (\*, N).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['gamma_factor']: Non negative real number, same as γ\gammaγ in the equation.- gamma larger than 1 make the shadows darker, while gamma smaller than 1 make- dark regions lighter.+ gamma larger than 1 make the shadows darker, while gamma smaller than 1 make+ dark regions lighter.Returns:torch.Tensor: Adjusted image.@@ -768,7 +774,7 @@ def apply_motion_blur(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> tThe input image is expected to be in the range of [0, 1].Args:- input (torch.Tensor): Image/Tensor to be adjusted in the shape of (\*, C, H, W).+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):- params['ksize_factor']: motion kernel width and height (odd and positive).- params['angle_factor']: angle of the motion blur in degrees (anti-clockwise rotation).@@ -793,3 +799,85 @@ def apply_motion_blur(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> tborder_type: str = cast(str, BorderType(params['border_type'].item()).name.lower())return motion_blur(input, kernel_size, angle, direction, border_type)+++def apply_solarize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Solarize an image.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).+ params (Dict[str, torch.Tensor]):+ - params['thresholds_factor']: thresholds ranged from 0 ~ 1.+ - params['additions_factor']: additions to add on before solarizing.++ Returns:+ torch.Tensor: Adjusted image.+ """+ input = _transform_input(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])++ thresholds = params['thresholds_factor']+ additions: Optional[torch.Tensor]+ if 'additions_factor' in params:+ additions = params['additions_factor']+ else:+ additions = None+ return solarize(input, thresholds, additions)+++def apply_posterize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Posterize an image.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).+ params (Dict[str, torch.Tensor]):+ - params['bits_factor']: uint8 bits number ranged from 0 to 8.++ Returns:+ torch.Tensor: Adjusted image.+ """+ input = _transform_input(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])++ bits = params['bits_factor']++ return posterize(input, bits)+++def apply_sharpness(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Sharpen an image.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).+ params (Dict[str, torch.Tensor]):+ - params['sharpness_factor']: Sharpness strength. Must be above 0.++ Returns:+ torch.Tensor: Adjusted image.+ """+ input = _transform_input(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])++ factor = params['sharpness_factor']++ return sharpness(input, factor)+++def apply_equalize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Equalize an image.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).+ params (Dict[str, torch.Tensor]):+ - params['p']: Probability.++ Returns:+ torch.Tensor: Adjusted image.+ """+ input = _transform_input(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])++ res = []+ for image, prob in zip(input, params['batch_prob']):+ res.append(equalize(image) if prob else image)+ return torch.cat(res, dim=0)diff --git a/kornia/augmentation/random_generator.py b/kornia/augmentation/random_generator.pyindex 84c911732..abe5aef15 100644--- a/kornia/augmentation/random_generator.py+++ b/kornia/augmentation/random_generator.py@@ -482,11 +482,11 @@ def random_rectangles_params_generator("""if not (isinstance(scale[0], float) and isinstance(scale[1], float) and scale[0] > 0. and scale[1] > 0.):raise TypeError(- "'erase_scale_range' must be a Tuple[float, float] with positive values"+ f"'erase_scale_range' must be a Tuple[float, float] with positive values. Got {scale}.")if not (isinstance(ratio[0], float) and isinstance(ratio[1], float) and ratio[0] > 0. and ratio[1] > 0.):raise TypeError(- "'ratio' must be a Tuple[float, float] with positive values"+ f"'ratio' must be a Tuple[float, float] with positive values. Got {ratio}.")batch_prob = random_prob_generator(batch_size, p, same_on_batch)['batch_prob']@@ -589,7 +589,7 @@ def center_crop_params_generator(align_corners=torch.tensor(align_corners))-def motion_blur_param_generator(+def random_motion_blur_generator(batch_size: int,kernel_size: Union[int, Tuple[int, int]],angle: UnionFloat,@@ -611,12 +611,116 @@ def motion_blur_param_generator(raise TypeError(f"Unsupported type: {type(kernel_size)}")angle_factor = _adapted_uniform(- (batch_size,), angle_bound[0], angle_bound[1], same_on_batch)+ (batch_size,), angle_bound[0].float(), angle_bound[1].float(), same_on_batch)direction_factor = _adapted_uniform(- (batch_size,), direction_bound[0], direction_bound[1], same_on_batch)+ (batch_size,), direction_bound[0].float(), direction_bound[1].float(), same_on_batch)return dict(ksize_factor=ksize_factor,angle_factor=angle_factor,direction_factor=direction_factor,border_type=torch.tensor(BorderType.get(border_type).value))+++def random_solarize_generator(+ batch_size: int,+ thresholds: FloatUnionType = 0.1,+ additions: FloatUnionType = 0.1,+ same_on_batch: bool = False+) -> Dict[str, torch.Tensor]:+ r"""Generator random solarize parameters for a batch of images. For each pixel in the image less than threshold,+ we add 'addition' amount to it and then clip the pixel value to be between 0 and 1.0++ Args:+ batch_size (int): the number of images.+ thresholds (float or tuple): Pixels less than threshold will selected. Otherwise, subtract 1.0 from the pixel.+ Default value is 0.1+ additions (float or tuple): The value is between -0.5 and 0.5. Default value is 0.1+ same_on_batch (bool): apply the same transformation across the batch. Default: False++ Returns:+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.+ """++ thresholds_bound: torch.Tensor = _check_and_bound(+ thresholds, 'thresholds', center=0.5, bounds=(0., 1.))+ additions_bound: torch.Tensor = _check_and_bound(additions, 'additions', bounds=(-0.5, 0.5))++ thresholds_factor = _adapted_uniform(+ (batch_size,), thresholds_bound[0].float(), thresholds_bound[1].float(), same_on_batch)++ additions_factor = _adapted_uniform(+ (batch_size,), additions_bound[0].float(), additions_bound[1].float(), same_on_batch)++ return dict(+ thresholds_factor=thresholds_factor,+ additions_factor=additions_factor+ )+++def random_posterize_generator(+ batch_size: int,+ bits: Union[int, Tuple[int, int], torch.Tensor] = 3,+ same_on_batch: bool = False+) -> Dict[str, torch.Tensor]:+ r"""Generator random posterize parameters for a batch of images.++ Args:+ batch_size (int): the number of images.+ bits (int or tuple): Default value is 3. Integer that ranged from 0 ~ 8.+ same_on_batch (bool): apply the same transformation across the batch. Default: False++ Returns:+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.+ """+ if not isinstance(bits, torch.Tensor):+ bits = torch.tensor(bits)++ if len(bits.size()) == 0:+ lower = bits+ upper = torch.tensor(8)+ elif len(bits.size()) == 1 and bits.size(0) == 2:+ lower = bits[0]+ upper = bits[1]+ else:+ raise ValueError(f"Expect float or tuple. Got {bits}.")++ bits_factor = _adapted_uniform((batch_size,), lower.float(), upper.float(), same_on_batch).int()++ return dict(+ bits_factor=bits_factor+ )+++def random_sharpness_generator(+ batch_size: int,+ sharpness: Union[float, Tuple[float, float], torch.Tensor] = 1.,+ same_on_batch: bool = False+) -> Dict[str, torch.Tensor]:+ r"""Generator random sharpness parameters for a batch of images.++ Args:+ batch_size (int): the number of images.+ sharpness (float or tuple): Default value is 1. Must be above 0.+ same_on_batch (bool): apply the same transformation across the batch. Default: False++ Returns:+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.+ """+ if not isinstance(sharpness, torch.Tensor):+ sharpness = torch.tensor(sharpness)++ if len(sharpness.size()) == 0:+ lower = torch.tensor(0)+ upper = sharpness+ elif len(sharpness.size()) == 1 and sharpness.size(0) == 2:+ lower = sharpness[0]+ upper = sharpness[1]+ else:+ raise ValueError(f"Expect float or tuple. Got {sharpness}.")++ sharpness_factor = _adapted_uniform((batch_size,), lower.float(), upper.float(), same_on_batch)++ return dict(+ sharpness_factor=sharpness_factor+ )diff --git a/kornia/augmentation/types.py b/kornia/augmentation/types.pyindex 27463b902..2608d9bf8 100644--- a/kornia/augmentation/types.py+++ b/kornia/augmentation/types.py@@ -8,4 +8,5 @@ UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]UnionShape = Union[Tuple, torch.Size]FloatUnionType = Union[torch.Tensor, float, Tuple[float, float], List[float]]+IntUnionType = Union[torch.Tensor, int, Tuple[int, int], List[int]]BoarderUnionType = Union[int, Tuple[int, int], Tuple[int, int, int, int]]diff --git a/kornia/augmentation/utils.py b/kornia/augmentation/utils.pyindex f3a807afb..b726bc0f6 100644--- a/kornia/augmentation/utils.py+++ b/kornia/augmentation/utils.py@@ -2,6 +2,8 @@ from typing import Tuple, Union, Listimport torchfrom torch.distributions import Uniform++from kornia.utils.image import _to_bchwfrom .types import (FloatUnionType,UnionType,@@ -27,20 +29,8 @@ def _transform_input(input: torch.Tensor) -> torch.Tensor:Returns:torch.Tensor"""- if not torch.is_tensor(input):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")-- if len(input.shape) not in [2, 3, 4]:- raise ValueError(- f"Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}")-- if len(input.shape) == 2:- input = input.unsqueeze(0)-- if len(input.shape) == 3:- input = input.unsqueeze(0)- return input+ return _to_bchw(input)def _validate_input_dtype(input: torch.Tensor, accepted_dtypes: List) -> None:@@ -87,6 +77,10 @@ def _adapted_uniform(shape: Union[Tuple, torch.Size], low, high, same_on_batch=FIf same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]).By default, same_on_batch is set to False."""+ if not isinstance(low, torch.Tensor):+ low = torch.tensor(low).float()+ if not isinstance(high, torch.Tensor):+ high = torch.tensor(high).float()dist = Uniform(low, high)if same_on_batch:return dist.rsample((1, *shape[1:])).repeat(shape[0])diff --git a/kornia/color/__init__.py b/kornia/color/__init__.pyindex 3a89153c4..ee17a7129 100644--- a/kornia/color/__init__.py+++ b/kornia/color/__init__.py@@ -24,7 +24,7 @@ from .adjust import ()from .adjust import (adjust_brightness, adjust_contrast, adjust_gamma, adjust_hue, adjust_saturation,- adjust_hue_raw, adjust_saturation_raw+ adjust_hue_raw, adjust_saturation_raw, solarize, equalize, posterize, sharpness)@@ -58,6 +58,10 @@ __all__ = ["adjust_saturation","adjust_hue_raw","adjust_saturation_raw",+ "solarize",+ "equalize",+ "posterize",+ "sharpness","add_weighted","AddWeighted","RgbToGrayscale",diff --git a/kornia/color/adjust.py b/kornia/color/adjust.pyindex 7c6d185f7..767383ab5 100644--- a/kornia/color/adjust.py+++ b/kornia/color/adjust.py@@ -1,9 +1,11 @@-from typing import Union+from typing import Union, Optionalimport torchimport torch.nn as nn+import torch.nn.functional as Ffrom kornia.color.hsv import rgb_to_hsv, hsv_to_rgb+from kornia.utils.image import _to_bchwfrom kornia.constants import pi@@ -225,6 +227,248 @@ def adjust_brightness(input: torch.Tensor,return out+def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5) -> torch.Tensor:+ r""" For each pixel in the image, select the pixel if the value is less than the threshold.+ Otherwise, subtract 1.0 from the pixel.+ Args:+ input (torch.Tensor): image or batched images to solarize.+ thresholds (float or torch.Tensor): solarize thresholds.+ If int or one element tensor, input will be solarized across the whole batch.+ If 1-d tensor, input will be solarized element-wise, len(thresholds) == len(input).+ Returns:+ torch.Tensor: Solarized images.+ """+ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if not isinstance(thresholds, (float, torch.Tensor,)):+ raise TypeError(f"The factor should be either a float or torch.Tensor. "+ f"Got {type(thresholds)}")++ if isinstance(thresholds, torch.Tensor) and len(thresholds.shape) != 0:+ assert input.size(0) == len(thresholds) and len(thresholds.shape) == 1, \+ f"threshholds must be a 1-d vector of shape ({input.size(0)},). Got {thresholds}"+ # TODO: I am not happy about this line, but no easy to do batch-wise operation+ thresholds = torch.stack([x.expand(*input.shape[1:]) for x in thresholds])++ return torch.where(input < thresholds, input, 1.0 - input)+++def solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5,+ additions: Optional[Union[float, torch.Tensor]] = None) -> torch.Tensor:+ r""" For each pixel in the image less than threshold, we add 'addition' amount to it and then clip the+ pixel value to be between 0 and 1.0. The value of 'addition' is between -0.5 and 0.5.+ Args:+ input (torch.Tensor): image tensor with shapes like (C, H, W) or (B, C, H, W) to solarize.+ thresholds (float or torch.Tensor): solarize thresholds.+ If int or one element tensor, input will be solarized across the whole batch.+ If 1-d tensor, input will be solarized element-wise, len(thresholds) == len(input).+ additions (optional, float or torch.Tensor): between -0.5 and 0.5. Default None.+ If None, no addition will be performed.+ If int or one element tensor, same addition will be added across the whole batch.+ If 1-d tensor, additions will be added element-wisely, len(additions) == len(input).+ Returns:+ torch.Tensor: Solarized images.+ """+ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if not isinstance(thresholds, (float, torch.Tensor,)):+ raise TypeError(f"The factor should be either a float or torch.Tensor. "+ f"Got {type(thresholds)}")++ if isinstance(thresholds, float):+ thresholds = torch.tensor(thresholds)++ if additions is not None:+ if not isinstance(additions, (float, torch.Tensor,)):+ raise TypeError(f"The factor should be either a float or torch.Tensor. "+ f"Got {type(additions)}")++ if isinstance(additions, float):+ additions = torch.tensor(additions)++ assert torch.all((additions < 0.5) * (additions > -0.5)), \+ f"The value of 'addition' is between -0.5 and 0.5. Got {additions}."++ if isinstance(additions, torch.Tensor) and len(additions.shape) != 0:+ assert input.size(0) == len(additions) and len(additions.shape) == 1, \+ f"additions must be a 1-d vector of shape ({input.size(0)},). Got {additions}"+ # TODO: I am not happy about this line, but no easy to do batch-wise operation+ additions = torch.stack([x.expand(*input.shape[1:]) for x in additions])++ input = input + additions+ input = input.clamp(0., 1.)++ return _solarize(input, thresholds)+++def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensor:+ r"""Reduce the number of bits for each color channel. Non-differentiable function, uint8 involved.+ Args:+ input (torch.Tensor): image tensor with shapes like (C, H, W) or (B, C, H, W) to posterize.+ bits (int or torch.Tensor): number of high bits. Must be in range [0, 8].+ If int or one element tensor, input will be posterized by this bits.+ If 1-d tensor, input will be posterized element-wisely, len(bits) == input.shape[1].+ If n-d tensor, input will be posterized element-channel-wisely, bits.shape == input.shape[:len(bits.shape)]+ Returns:+ torch.Tensor: Image with reduced color channels.+ """+ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")++ if isinstance(bits, int):+ bits = torch.tensor(bits)++ if not torch.all((bits >= 0) * (bits <= 8)) and bits.dtype == torch.int:+ raise ValueError(f"bits must be integers within range [0, 8]. Got {bits}.")++ # TODO: Make a differentiable version+ # Current version:+ # Ref: https://github.com/open-mmlab/mmcv/pull/132/files#diff-309c9320c7f71bedffe89a70ccff7f3bR19+ # Ref: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L222+ # Potential approach: implementing kornia.LUT with floating points+ # https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/functional.py#L472+ def _left_shift(input: torch.Tensor, shift: torch.Tensor):+ return ((input * 255).to(torch.uint8) * (2 ** shift)).to(input.dtype) / 255.++ def _right_shift(input: torch.Tensor, shift: torch.Tensor):+ return (input * 255).to(torch.uint8) / (2 ** shift).to(input.dtype) / 255.++ def _posterize_one(input: torch.Tensor, bits: torch.Tensor):+ # Single bits value condition+ if bits == 0:+ return torch.zeros_like(input)+ if bits == 8:+ return input.clone()+ bits = 8 - bits+ return _left_shift(_right_shift(input, bits), bits)++ if len(bits.shape) == 0 or (len(bits.shape) == 1 and len(bits) == 1):+ return _posterize_one(input, bits)++ res = []+ if len(bits.shape) == 1:+ input = _to_bchw(input)++ assert bits.shape[0] == input.shape[0], \+ f"Batch size must be equal between bits and input. Got {bits.shape[0]}, {input.shape[0]}."++ for i in range(input.shape[0]):+ res.append(_posterize_one(input[i], bits[i]))+ return torch.stack(res, dim=0)++ assert bits.shape == input.shape[:len(bits.shape)], \+ f"Batch and channel must be equal between bits and input. Got {bits.shape}, {input.shape[:len(bits.shape)]}."+ _input = input.view(-1, *input.shape[len(bits.shape):])+ _bits = bits.flatten()+ for i in range(input.shape[0]):+ res.append(_posterize_one(_input[i], _bits[i]))+ return torch.stack(res, dim=0).reshape(*input.shape)+++def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:+ r"""Implements Sharpness function from PIL using torch ops.+ Args:+ input (torch.Tensor): image tensor with shapes like (C, H, W) or (B, C, H, W) to sharpen.+ factor (float or torch.Tensor): factor of sharpness strength. Must be above 0.+ If float or one element tensor, input will be sharpened by the same factor across the whole batch.+ If 1-d tensor, input will be sharpened element-wisely, len(factor) == len(input).+ Returns:+ torch.Tensor: Sharpened image or images.+ """+ input = _to_bchw(input)+ if isinstance(factor, torch.Tensor):+ factor = factor.squeeze()+ if len(factor.size()) != 0:+ assert input.size(0) == factor.size(0), \+ f"Input batch size shall match with factor size if 1d array. Got {input.size(0)} and {factor.size(0)}"+ else:+ factor = float(factor)+ kernel = torch.tensor([+ [1, 1, 1],+ [1, 5, 1],+ [1, 1, 1]+ ], dtype=input.dtype).view(1, 1, 3, 3).repeat(3, 1, 1, 1)++ # This shall be equivalent to depthwise conv2d:+ # Ref: https://discuss.pytorch.org/t/depthwise-and-separable-convolutions-in-pytorch/7315/2+ degenerate = torch.nn.functional.conv2d(input, kernel, bias=None, stride=1, groups=input.size(1))+ degenerate = torch.clamp(degenerate, 0., 1.)++ mask = torch.ones_like(degenerate)+ padded_mask = torch.nn.functional.pad(mask, [1, 1, 1, 1])+ padded_degenerate = torch.nn.functional.pad(degenerate, [1, 1, 1, 1])+ result = torch.where(padded_mask == 1, padded_degenerate, input)++ def _blend_one(input1: torch.Tensor, input2: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:+ if isinstance(factor, torch.Tensor):+ factor = factor.squeeze()+ assert len(factor.size()) == 0, f"Factor shall be a float or single element tensor. Got {factor}"+ if factor == 0.:+ return input1+ if factor == 1.:+ return input2+ diff = (input2 - input1) * factor+ res = input1 + diff+ if factor > 0. and factor < 1.:+ return res+ return torch.clamp(res, 0, 1)+ if isinstance(factor, (float)) or len(factor.size()) == 0:+ return _blend_one(input, result, factor)+ return torch.stack([_blend_one(input[i], result[i], factor[i]) for i in range(len(factor))])+++def equalize(input: torch.Tensor) -> torch.Tensor:+ """Implements Equalize function from PIL using PyTorch ops based on uint8 format:+ https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352+ Args:+ input (torch.Tensor): image tensor with shapes like (C, H, W) or (B, C, H, W) to equalize.+ Returns:+ torch.Tensor: Sharpened image or images.+ """+ input = _to_bchw(input) * 255++ # Code taken from: https://github.com/pytorch/vision/pull/796+ def scale_channel(im, c):+ """Scale the data in the channel to implement equalize."""+ im = im[c, :, :]+ # Compute the histogram of the image channel.+ histo = torch.histc(im, bins=256, min=0, max=255)+ # For the purposes of computing the step, filter out the nonzeros.+ nonzero_histo = torch.reshape(histo[histo != 0], [-1])+ step = (torch.sum(nonzero_histo) - nonzero_histo[-1]) // 255++ def build_lut(histo, step):+ # Compute the cumulative sum, shifting by step // 2+ # and then normalization by step.+ lut = (torch.cumsum(histo, 0) + (step // 2)) // step+ # Shift lut, prepending with 0.+ lut = torch.cat([torch.zeros(1), lut[:-1]])+ # Clip the counts to be in range. This is done+ # in the C code for image.point.+ return torch.clamp(lut, 0, 255)++ # If step is zero, return the original image. Otherwise, build+ # lut from the full histogram and step and then index from it.+ if step == 0:+ result = im+ else:+ # can't index using 2d index. Have to flatten and then reshape+ result = torch.gather(build_lut(histo, step), 0, im.flatten().long())+ result = result.reshape_as(im)++ return result / 255.++ res = []+ for image in input:+ # Assumes RGB for now. Scales each channel independently+ # and then stacks the result.+ scaled_image = torch.stack([scale_channel(image, i) for i in range(len(image))])+ res.append(scaled_image)+ return torch.stack(res)++class AdjustSaturation(nn.Module):r"""Adjust color saturation of an image.diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.pyindex 05f637700..3ef418840 100644--- a/kornia/geometry/camera/pinhole.py+++ b/kornia/geometry/camera/pinhole.py@@ -52,7 +52,7 @@ class PinholeCamera:def _check_valid_params(data: torch.Tensor,data_name: str) -> bool:- if len(data.shape) not in (3, 4,) and data.shape[-2:] != (4, 4):+ if len(data.shape) not in (3, 4,) and data.shape[-2:] != (4, 4): # Shouldn't this be an OR logic than AND?raise ValueError("Argument {0} shape must be in the following shape"" Bx4x4 or BxNx4x4. Got {1}".format(data_name,data.shape))diff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop.pyindex bc07e60c0..4e813baa9 100644--- a/kornia/geometry/transform/crop.py+++ b/kornia/geometry/transform/crop.py@@ -16,6 +16,7 @@ __all__ = [def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int, int],interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:r"""Extracts crops from the input tensor and resizes them.+Args:tensor (torch.Tensor): the reference tensor of shape BxCxHxW.boxes (torch.Tensor): a tensor containing the coordinates of the@@ -26,7 +27,7 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,size (Tuple[int, int]): a tuple with the height and width that will beused to resize the extracted patches.align_corners (bool): mode for grid_generation. Default: False. See- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detailsReturns:torch.Tensor: tensor containing the patches with shape BxN1xN2Example:@@ -89,7 +90,7 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],size (Tuple[int, int]): a tuple with the expected height and widthof the output patch.align_corners (bool): mode for grid_generation. Default: False. See- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detailsReturns:torch.Tensor: the output tensor with patches.diff --git a/kornia/utils/image.py b/kornia/utils/image.pyindex 62716e724..525e2abc7 100644--- a/kornia/utils/image.py+++ b/kornia/utils/image.py@@ -1,20 +1,19 @@+from typing import Optional+import numpy as npimport torchdef image_to_tensor(image: np.ndarray, keepdim: bool = True) -> torch.Tensor:"""Converts a numpy image to a PyTorch 4d tensor image.-Args:image (numpy.ndarray): image of the form :math:`(H, W, C)`, :math:`(H, W)` or:math:`(B, H, W, C)`.keepdim (bool): If ``False`` unsqueeze the input image to match the shape:math:`(B, H, W, C)`. Default: ``True``-Returns:torch.Tensor: tensor of the form :math:`(B, C, H, W)` if keepdim is ``False``,:math:`(C, H, W)` otherwise.-"""if not isinstance(image, (np.ndarray,)):raise TypeError("Input type must be a numpy.ndarray. Got {}".format(@@ -44,6 +43,35 @@ def image_to_tensor(image: np.ndarray, keepdim: bool = True) -> torch.Tensor:return tensor.unsqueeze(0) if not keepdim else tensor+def _to_bchw(tensor: torch.Tensor, color_channel_num: Optional[int] = None) -> torch.Tensor:+ """Converts a PyTorch tensor image to BCHW format.++ Args:+ tensor (torch.Tensor): image of the form :math:`(H, W)`, :math:`(C, H, W)`, :math:`(H, W, C)` or+ :math:`(B, C, H, W)`.+ color_channel_num (Optional[int]): Color channel of the input tensor.+ If None, it will not alter the input channel.++ Returns:+ torch.Tensor: input tensor of the form :math:`(B, H, W, C)`.+ """+ if not torch.is_tensor(tensor):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")++ if len(tensor.shape) > 4 or len(tensor.shape) < 2:+ raise ValueError(f"Input size must be a two, three or four dimensional tensor. Got {tensor.shape}")++ if len(tensor.shape) == 2:+ tensor = tensor.unsqueeze(0)+ if len(tensor.shape) == 3:+ tensor = tensor.unsqueeze(0)+ if color_channel_num is not None and color_channel_num != 1:+ channel_list = [0, 1, 2, 3]+ channel_list.insert(1, channel_list.pop(color_channel_num))+ tensor = tensor.permute(*channel_list)+ return tensor++def tensor_to_image(tensor: torch.Tensor) -> np.array:"""Converts a PyTorch tensor image to a numpy image. In case the tensor is in the GPU,it will be copied back to CPU.