Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

grayscale to rgb for torch.uint8 (#1705)

Edgar Ribaec4e1135474c
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index 6a0843919..317e21219 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -1,10 +1,13 @@
+from typing import Optional
+
import torch
-import torch.nn as nn
from kornia.color.rgb import bgr_to_rgb
+from kornia.core import Module, Tensor, concatenate
+from kornia.testing import KORNIA_CHECK_IS_TENSOR
-def grayscale_to_rgb(image: torch.Tensor) -> torch.Tensor:
+def grayscale_to_rgb(image: Tensor) -> Tensor:
r"""Convert a grayscale image to RGB version of image.
.. image:: _static/img/grayscale_to_rgb.png
@@ -21,24 +24,15 @@ def grayscale_to_rgb(image: torch.Tensor) -> torch.Tensor:
>>> input = torch.randn(2, 1, 4, 5)
>>> gray = grayscale_to_rgb(input) # 2x3x4x5
"""
- if not isinstance(image, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. " f"Got {type(image)}")
+ KORNIA_CHECK_IS_TENSOR(image)
if image.dim() < 3 or image.size(-3) != 1:
raise ValueError(f"Input size must have a shape of (*, 1, H, W). " f"Got {image.shape}.")
- rgb: torch.Tensor = torch.cat([image, image, image], dim=-3)
-
- # TODO: we should find a better way to raise this kind of warnings
- # if not torch.is_floating_point(image):
- # warnings.warn(f"Input image is not of float dtype. Got {image.dtype}")
+ return concatenate([image, image, image], -3)
- return rgb
-
-def rgb_to_grayscale(
- image: torch.Tensor, rgb_weights: torch.Tensor = torch.tensor([0.299, 0.587, 0.114])
-) -> torch.Tensor:
+def rgb_to_grayscale(image: Tensor, rgb_weights: Optional[Tensor] = None) -> Tensor:
r"""Convert a RGB image to grayscale version of image.
.. image:: _static/img/rgb_to_grayscale.png
@@ -60,28 +54,30 @@ def rgb_to_grayscale(
>>> input = torch.rand(2, 3, 4, 5)
>>> gray = rgb_to_grayscale(input) # 2x1x4x5
"""
- if not isinstance(image, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
+ KORNIA_CHECK_IS_TENSOR(image)
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- if not isinstance(rgb_weights, torch.Tensor):
- raise TypeError(f"rgb_weights is not a torch.Tensor. Got {type(rgb_weights)}")
-
- if rgb_weights.shape[-1] != 3:
- raise ValueError(f"rgb_weights must have a shape of (*, 3). Got {rgb_weights.shape}")
-
- r: torch.Tensor = image[..., 0:1, :, :]
- g: torch.Tensor = image[..., 1:2, :, :]
- b: torch.Tensor = image[..., 2:3, :, :]
-
- if not torch.is_floating_point(image) and (image.dtype != rgb_weights.dtype):
- raise TypeError(
- f"Input image and rgb_weights should be of same dtype. Got {image.dtype} and {rgb_weights.dtype}"
- )
-
- w_r, w_g, w_b = rgb_weights.to(image).unbind()
+ if rgb_weights is None:
+ # 8 bit images
+ if image.dtype == torch.uint8:
+ rgb_weights = torch.tensor([76, 150, 29], device=image.device, dtype=torch.uint8)
+ # floating point images
+ elif image.dtype in (torch.float16, torch.float32, torch.float64):
+ rgb_weights = torch.tensor([0.299, 0.587, 0.114], device=image.device, dtype=image.dtype)
+ else:
+ raise TypeError(f"Unknown data type: {image.dtype}")
+ else:
+ # is tensor that we make sure is in the same device/dtype
+ rgb_weights = rgb_weights.to(image)
+
+ # unpack the color image channels with RGB order
+ r: Tensor = image[..., 0:1, :, :]
+ g: Tensor = image[..., 1:2, :, :]
+ b: Tensor = image[..., 2:3, :, :]
+
+ w_r, w_g, w_b = rgb_weights.unbind()
return w_r * r + w_g * g + w_b * b
@@ -100,17 +96,16 @@ def bgr_to_grayscale(image: torch.Tensor) -> torch.Tensor:
>>> input = torch.rand(2, 3, 4, 5)
>>> gray = bgr_to_grayscale(input) # 2x1x4x5
"""
- if not isinstance(image, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
+ KORNIA_CHECK_IS_TENSOR(image)
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- image_rgb = bgr_to_rgb(image)
+ image_rgb: Tensor = bgr_to_rgb(image)
return rgb_to_grayscale(image_rgb)
-class GrayscaleToRgb(nn.Module):
+class GrayscaleToRgb(Module):
r"""Module to convert a grayscale image to RGB version of image.
The image data is assumed to be in the range of (0, 1).
@@ -128,11 +123,11 @@ class GrayscaleToRgb(nn.Module):
>>> output = rgb(input) # 2x3x4x5
"""
- def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, image: Tensor) -> Tensor:
return grayscale_to_rgb(image)
-class RgbToGrayscale(nn.Module):
+class RgbToGrayscale(Module):
r"""Module to convert a RGB image to grayscale version of image.
The image data is assumed to be in the range of (0, 1).
@@ -150,15 +145,15 @@ class RgbToGrayscale(nn.Module):
>>> output = gray(input) # 2x1x4x5
"""
- def __init__(self, rgb_weights: torch.Tensor = torch.tensor([0.299, 0.587, 0.114])) -> None:
+ def __init__(self, rgb_weights: Optional[Tensor] = None) -> None:
super().__init__()
self.rgb_weights = rgb_weights
- def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, image: Tensor) -> Tensor:
return rgb_to_grayscale(image, rgb_weights=self.rgb_weights)
-class BgrToGrayscale(nn.Module):
+class BgrToGrayscale(Module):
r"""Module to convert a BGR image to grayscale version of image.
The image data is assumed to be in the range of (0, 1). First flips to RGB, then converts.
@@ -176,5 +171,5 @@ class BgrToGrayscale(nn.Module):
>>> output = gray(input) # 2x1x4x5
"""
- def forward(self, image: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, image: Tensor) -> Tensor:
return bgr_to_grayscale(image)
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 995d7ec53..35cb4db24 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -73,8 +73,8 @@ def load_image(path_file: str, desired_type: ImageLoadType, device: str = "cpu")
if image.shape[0] == 1 and image.dtype == torch.uint8:
return image
elif image.shape[0] == 3 and image.dtype == torch.uint8:
- gray32 = rgb_to_grayscale(to_float32(image))
- return to_uint8(gray32)
+ gray8 = rgb_to_grayscale(image)
+ return gray8
elif image.shape[0] == 4 and image.dtype == torch.uint8:
gray32 = rgb_to_grayscale(rgba_to_rgb(to_float32(image)))
return to_uint8(gray32)
@@ -82,8 +82,8 @@ def load_image(path_file: str, desired_type: ImageLoadType, device: str = "cpu")
if image.shape[0] == 3 and image.dtype == torch.uint8:
return image
elif image.shape[0] == 1 and image.dtype == torch.uint8:
- rgb32 = grayscale_to_rgb(to_float32(image))
- return to_uint8(rgb32)
+ rgb8 = grayscale_to_rgb(image)
+ return rgb8
elif desired_type == ImageLoadType.RGBA8:
if image.shape[0] == 3 and image.dtype == torch.uint8:
rgba32 = rgb_to_rgba(to_float32(image), 0.0)
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index b155eb318..490c6698e 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -189,7 +189,7 @@ def KORNIA_CHECK_SHAPE(x, shape: List[str]) -> None:
KORNIA_CHECK_IS_TENSOR(x)
if '*' == shape[0]:
start_idx: int = 1
- x_shape_to_check = x.shape[-len(shape) - 1:]
+ x_shape_to_check = x.shape[-len(shape) - 1 :]
else:
start_idx = 0
x_shape_to_check = x.shape
diff --git a/test/color/test_gray.py b/test/color/test_gray.py
index a42313061..a9134c67c 100644
--- a/test/color/test_gray.py
+++ b/test/color/test_gray.py
@@ -108,7 +108,16 @@ class TestRgbToGrayscale(BaseTester):
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
- assert isinstance(kornia.color.rgb_to_grayscale(img), torch.Tensor)
+ out = kornia.color.rgb_to_grayscale(img)
+ assert out.device == img.device
+ assert out.dtype == img.dtype
+
+ def test_smoke_byte(self, device):
+ C, H, W = 3, 4, 5
+ img = torch.randint(0, 255, (C, H, W), device=device, dtype=torch.uint8)
+ out = kornia.color.rgb_to_grayscale(img)
+ assert out.device == img.device
+ assert out.dtype == img.dtype
@pytest.mark.parametrize("batch_size, height, width", [(1, 3, 4), (2, 2, 4), (3, 4, 1)])
def test_cardinality(self, device, dtype, batch_size, height, width):
@@ -127,10 +136,6 @@ class TestRgbToGrayscale(BaseTester):
img = torch.ones(2, 1, 1, device=device, dtype=dtype)
assert kornia.color.rgb_to_grayscale(img)
- with pytest.raises(TypeError):
- img = torch.ones(1, 3, 1, 1, device=device, dtype=torch.uint8)
- 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])