Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement rgb_to_grayscale

edgarriba2fa2175de05a
diff --git a/docs/source/image.rst b/docs/source/image.rst
index 90ebbc130..bf1243723 100644
--- a/docs/source/image.rst
+++ b/docs/source/image.rst
@@ -6,5 +6,7 @@ torchgeometry.image
.. autofunction:: get_gaussian_kernel
.. autofunction:: get_gaussian_kernel2d
.. autofunction:: gaussian_blur
+.. autofunction:: rgb_to_grayscale
.. autoclass:: GaussianBlur
+.. autoclass:: RgbToGrayscale
diff --git a/test/test_image.py b/test/test_image.py
index 5bda49848..019bb04ff 100644
--- a/test/test_image.py
+++ b/test/test_image.py
@@ -48,3 +48,22 @@ class TestGaussianBlur:
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(image.gaussian_blur, (input, kernel_size, sigma,),
raise_exception=True)
+
+
+class TestRgbToGrayscale:
+ def test_rgb_to_grayscale(self):
+ channels, height, width = 3, 4, 5
+ img = torch.ones(channels, height, width)
+ assert image.RgbToGrayscale()(img).shape == (1, height, width)
+
+ def test_rgb_to_grayscale_batch(self):
+ batch_size, channels, height, width = 2, 3, 4, 5
+ img = torch.ones(batch_size, channels, height, width)
+ assert image.RgbToGrayscale()(img).shape == \
+ (batch_size, 1, height, width)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 2, 3, 4, 5
+ img = torch.ones(batch_size, channels, height, width)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(image.rgb_to_grayscale, (img,), raise_exception=True)
diff --git a/torchgeometry/image/__init__.py b/torchgeometry/image/__init__.py
index a645b85ce..675d962e0 100644
--- a/torchgeometry/image/__init__.py
+++ b/torchgeometry/image/__init__.py
@@ -1,2 +1,3 @@
from .gaussian import get_gaussian_kernel, get_gaussian_kernel2d
from .gaussian import GaussianBlur, gaussian_blur
+from .color import rgb_to_grayscale, RgbToGrayscale
diff --git a/torchgeometry/image/color.py b/torchgeometry/image/color.py
new file mode 100644
index 000000000..a5c780b57
--- /dev/null
+++ b/torchgeometry/image/color.py
@@ -0,0 +1,53 @@
+import torch
+import torch.nn as nn
+
+
+class RgbToGrayscale(nn.Module):
+ r"""Convert image to grayscale version of image.
+
+ Args:
+ input (torch.Tensor): Image to be converted to grayscale.
+
+ Returns:
+ torch.Tensor: Grayscale version of the image.
+
+ Shape:
+ - Input: :math:`(*, 3, H, W)`
+ - Output: :math:`(*, 1, H, W)`
+
+ Examples::
+
+ >>> input = torch.rand(2, 3, 4, 5)
+ >>> gray = tgm.image.RgbToGrayscale()
+ >>> output = gray(input) # 2x1x4x5
+ """
+ def __init__(self) -> None:
+ super(RgbToGrayscale, self).__init__()
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ return rgb_to_grayscale(input)
+
+
+def rgb_to_grayscale(input: torch.Tensor) -> torch.Tensor:
+ r"""Convert an RGB image to grayscale.
+
+ See :class:`~torchgeometry.image.RgbToGrayscale` for details.
+
+ Args:
+ input (torch.Tensor): Image to be converted to grayscale.
+
+ Returns:
+ torch.Tensor: Grayscale version of the image.
+ """
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(input)))
+
+ if len(input.shape) < 3 and input.shape[-3] != 3:
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
+ .format(input.shape))
+
+ # https://docs.opencv.org/4.0.1/de/d25/imgproc_color_conversions.html
+ r, g, b = torch.chunk(input, chunks=3, dim=-3)
+ gray: torch.Tensor = 0.299 * r + 0.587 * g + 0.110 * b
+ return gray