Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Raise error if converting to unit8 image to gray with float weights (#1057)

Dmytro Mishkin2e217bd140d1
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index 011b12421..949d39afe 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -38,8 +38,13 @@ def rgb_to_grayscale(
r: torch.Tensor = image[..., 0:1, :, :]
g: torch.Tensor = image[..., 1:2, :, :]
b: torch.Tensor = image[..., 2:3, :, :]
- if image.dtype not in [torch.float16, torch.float32, torch.float64]:
+ image_is_float: bool = torch.is_floating_point(image)
+ if not image_is_float:
warnings.warn("Input image is not of float dtype. Got {}".format(image.dtype))
+ if (image.dtype != rgb_weights.dtype) and not image_is_float:
+ raise TypeError(
+ "Input image and rgb_weights should be of same dtype. Got {} and {}".format(image.dtype, rgb_weights.dtype)
+ )
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
diff --git a/test/color/test_gray.py b/test/color/test_gray.py
index 66a9104dc..e9a835372 100644
--- a/test/color/test_gray.py
+++ b/test/color/test_gray.py
@@ -30,6 +30,10 @@ 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])