Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Added custom weights option for rgb2gray (#944)

MrParoskb0140e4ffdd8
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index d853389ed..8072666f1 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -4,14 +4,16 @@ import torch.nn as nn
from kornia.color.rgb import bgr_to_rgb
-def rgb_to_grayscale(image: torch.Tensor) -> torch.Tensor:
+def rgb_to_grayscale(image: torch.Tensor,
+ rgb_weights: torch.Tensor = torch.tensor([0.299, 0.587, 0.114])) -> torch.Tensor:
r"""Convert a RGB image to grayscale version of image.
The image data is assumed to be in the range of (0, 1).
Args:
image (torch.Tensor): RGB image to be converted to grayscale with shape :math:`(*,3,H,W)`.
-
+ rgb_weights (torch.Tensor): Weights that will be applied on each channel (RGB).
+ The sum of the weights should add up to one.
Returns:
torch.Tensor: grayscale version of the image with shape :math:`(*,1,H,W)`.
@@ -27,11 +29,20 @@ def rgb_to_grayscale(image: torch.Tensor) -> torch.Tensor:
raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
.format(image.shape))
+ if not isinstance(rgb_weights, torch.Tensor):
+ raise TypeError("rgb_weights is not a torch.Tensor. Got {}".format(
+ type(rgb_weights)))
+
+ if rgb_weights.shape[-1] != 3:
+ raise ValueError("rgb_weights must have a shape of (*, 3). Got {}"
+ .format(rgb_weights.shape))
+
r: torch.Tensor = image[..., 0:1, :, :]
g: torch.Tensor = image[..., 1:2, :, :]
b: torch.Tensor = image[..., 2:3, :, :]
- gray: torch.Tensor = 0.299 * r + 0.587 * g + 0.114 * b
+ w_tmp: torch.Tensor = rgb_weights.to(image.device, image.dtype)
+ gray: torch.Tensor = w_tmp[..., 0] * r + w_tmp[..., 1] * g + w_tmp[..., 2] * b
return gray
@@ -81,11 +92,12 @@ class RgbToGrayscale(nn.Module):
>>> output = gray(input) # 2x1x4x5
"""
- def __init__(self) -> None:
+ def __init__(self, rgb_weights: torch.Tensor = torch.tensor([0.299, 0.587, 0.114])) -> None:
super(RgbToGrayscale, self).__init__()
+ self.rgb_weights = rgb_weights
def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore
- return rgb_to_grayscale(image)
+ return rgb_to_grayscale(image, rgb_weights=self.rgb_weights)
class BgrToGrayscale(nn.Module):
diff --git a/test/color/test_gray.py b/test/color/test_gray.py
index ee3013453..a3f3c147e 100644
--- a/test/color/test_gray.py
+++ b/test/color/test_gray.py
@@ -32,6 +32,11 @@ class TestRgbToGrayscale(BaseTester):
img = torch.ones(2, 1, 1, device=device, dtype=dtype)
assert kornia.color.rgb_to_grayscale(img)
+ with pytest.raises(ValueError):
+ img = torch.ones(3, 1, 1, device=device, dtype=dtype)
+ rgb_weights = torch.tensor([0.2, 0.8])
+ assert kornia.color.rgb_to_grayscale(img, rgb_weights=rgb_weights)
+
def test_opencv(self, device, dtype):
data = torch.tensor([
[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
@@ -65,6 +70,15 @@ class TestRgbToGrayscale(BaseTester):
img_gray = kornia.rgb_to_grayscale(data)
assert_allclose(img_gray, expected)
+ def test_custom_rgb_weights(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+
+ rgb_weights = torch.tensor([0.5, 0.25, 0.25])
+ img_gray = kornia.rgb_to_grayscale(img, rgb_weights=rgb_weights)
+ assert img_gray.device == device
+ assert img_gray.dtype == dtype
+
@pytest.mark.grad
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4