Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

RandomGrayscale

Pau Riba84d5b92d94c8
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 845dc798d..fec68da1e 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -84,6 +84,7 @@ from kornia.augmentation import (
random_hflip,
random_vflip,
color_jitter,
+ random_grayscale,
)
from kornia.geometry import *
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 5425899bf..182628485 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -8,6 +8,8 @@ __all__ = [
"RandomVerticalFlip",
"color_jitter",
"ColorJitter",
- "RandomRectangleErasing",
"random_rectangle_erase",
+ "RandomRectangleErasing",
+ "random_grayscale",
+ "RandomGrayscale",
]
diff --git a/kornia/augmentation/augmentations.py b/kornia/augmentation/augmentations.py
index 59fcf4020..2de6dc43a 100644
--- a/kornia/augmentation/augmentations.py
+++ b/kornia/augmentation/augmentations.py
@@ -6,6 +6,7 @@ from torch.distributions import Uniform
from kornia.geometry.transform.flips import hflip, vflip
from kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHue
+from kornia.color.gray import rgb_to_grayscale
from kornia.geometry import pi
UnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
@@ -178,6 +179,41 @@ class ColorJitter(nn.Module):
return color_jitter(input, self.brightness, self.contrast, self.saturation, self.hue, self.return_transform)
+class RandomGrayscale(nn.Module):
+ r"""Random Grayscale transformation according to a probability p value
+
+ Args:
+ p (float): probability of the image to be transformed to grayscale. 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
+ """
+
+ def __init__(self, p: float = 0.5, return_transform: bool = False) -> None:
+ super(RandomGrayscale, 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):
+
+ output: torch.Tensor = cast(
+ torch.Tensor,
+ random_grayscale(
+ input[0],
+ p=self.p,
+ return_transform=False))
+
+ return output, input[1]
+
+ return random_grayscale(input, p=self.p, return_transform=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)`.
@@ -386,3 +422,42 @@ def color_jitter(input: torch.Tensor, brightness: FloatUnionType = 0.,
return jittered, identity
return jittered
+
+
+def random_grayscale(input: torch.Tensor, p: float = .5, return_transform: bool = False) -> UnionType:
+ r"""Random grayscale of an image or batch of images.
+
+ See :class:`~kornia.augmentation.RandomGrayscale` for details.
+ """
+
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+
+ if len(input.shape) > 3 and input.shape[-3] != 3:
+ raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {input.shape}")
+
+ 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_gray: torch.Tensor = probs < p
+ grayscale: torch.Tensor = input.clone()
+
+ grayscale[to_gray] = rgb_to_grayscale(input[to_gray])
+ if return_transform:
+
+ identity: torch.Tensor = torch.eye(3, device=device, dtype=dtype).repeat(input.shape[0], 1, 1)
+
+ return grayscale, identity
+
+ return grayscale
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index a2b416e83..fbafc74d3 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -7,7 +7,8 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
-from kornia.augmentation import RandomHorizontalFlip, RandomVerticalFlip, ColorJitter, RandomRectangleErasing
+from kornia.augmentation import RandomHorizontalFlip, RandomVerticalFlip, ColorJitter, \
+ RandomRectangleErasing, RandomGrayscale
from kornia.augmentation.random_erasing import get_random_rectangles_params, erase_rectangles
from test.common import device
@@ -754,6 +755,7 @@ class TestColorJitter:
expected_transform = torch.eye(3).unsqueeze(0).expand((2, 3, 3)) # 2 x 3 x 3
assert_allclose(f(input)[0], expected, atol=1e-4, rtol=1e-5)
+ assert_allclose(f(input)[0], expected)
assert_allclose(f(input)[1], expected_transform)
def test_gradcheck(self):
@@ -872,3 +874,183 @@ class TestRectangleRandomErasing:
)(img)
actual = op_script(img)
assert_allclose(actual, expected)
+
+
+class TestRandomGrayscale:
+
+ def smoke_test(self):
+ f = RandomGrayscale()
+ repr = "RandomGrayscale(p=0.5, return_transform=False)"
+ assert str(f) == repr
+
+ def test_random_grayscale(self):
+
+ f = RandomGrayscale(return_transform=True)
+
+ input = torch.rand(3, 5, 5) # 3 x 5 x 5
+
+ expected_transform = torch.eye(3).unsqueeze(0) # 3 x 3
+
+ assert_allclose(f(input)[1], expected_transform)
+
+ def test_opencv_true(self, device):
+ data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
+
+ [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
+
+ [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]])
+ data = data.to(device)
+
+ # Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
+ expected = torch.tensor([[[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
+
+ [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
+
+ [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]]])
+ expected = expected.to(device)
+
+ img_gray = kornia.random_grayscale(data, p=1.)
+ assert_allclose(img_gray, expected)
+
+ def test_opencv_false(self, device):
+ data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
+
+ [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
+
+ [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]])
+ data = data.to(device)
+
+ expected = data
+
+ img_gray = kornia.random_grayscale(data, p=0.)
+ assert_allclose(img_gray, expected)
+
+ def test_opencv_true_batch(self, device):
+ data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
+
+ [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
+
+ [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]])
+ data = data.to(device)
+ data = data.unsqueeze(0).repeat(4, 1, 1, 1)
+
+ # Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
+ expected = torch.tensor([[[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
+
+ [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
+
+ [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]]])
+ expected = expected.to(device)
+ expected = expected.unsqueeze(0).repeat(4, 1, 1, 1)
+
+ img_gray = kornia.random_grayscale(data, p=1.)
+ assert_allclose(img_gray, expected)
+
+ def test_opencv_true_batch(self, device):
+ data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
+
+ [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
+
+ [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]])
+ data = data.to(device)
+ data = data.unsqueeze(0).repeat(4, 1, 1, 1)
+
+ expected = data
+
+ img_gray = kornia.random_grayscale(data, p=0.)
+ assert_allclose(img_gray, expected)
+
+ def test_random_grayscale_sequential_batch(self):
+ f = nn.Sequential(
+ RandomGrayscale(p=0., return_transform=True),
+ RandomGrayscale(p=0., return_transform=True),
+ )
+
+ input = torch.rand(2, 3, 5, 5) # 2 x 3 x 5 x 5
+ expected = input
+
+ expected_transform = torch.eye(3).unsqueeze(0).expand((2, 3, 3)) # 2 x 3 x 3
+
+ assert_allclose(f(input)[0], expected)
+ assert_allclose(f(input)[1], expected_transform)
+
+ def test_gradcheck(self):
+
+ input = torch.rand((3, 5, 5)).double() # 3 x 3
+
+ input = utils.tensor_to_gradcheck_var(input) # to var
+
+ assert gradcheck(kornia.random_grayscale, (input, 0.), raise_exception=True)
+ assert gradcheck(kornia.random_grayscale, (input, 1.), raise_exception=True)