Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: keep an 8-bit grayscale conversion from wrapping (#5090)

Sashfc6af39a4e7b
diff --git a/changelog.d/5090.fixed.md b/changelog.d/5090.fixed.md
new file mode 100644
index 000000000..9a1470239
--- /dev/null
+++ b/changelog.d/5090.fixed.md
@@ -0,0 +1 @@
+`rgb_to_grayscale` and `bgr_to_grayscale` on a uint8 image no longer wrap the weighted sum modulo 256 (white came back as 1 and pure red as 180), which also garbled `load_image(..., ImageLoadType.GRAY8)` of a colour file. The uint8 result now matches `cv2.cvtColor(..., cv2.COLOR_RGB2GRAY)` bit for bit.
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index 953af9532..f07cde333 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -84,11 +84,15 @@ def rgb_to_grayscale(image: torch.Tensor, rgb_weights: Optional[torch.Tensor] =
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
if rgb_weights is None:
- # 8 bit images
+ # 8 bit images: OpenCV's fixed-point COLOR_RGB2GRAY weights, 0.299, 0.587 and 0.114 scaled by 2**15 and
+ # summing to 2**15, so a flat grey maps to itself and the result matches cv2.cvtColor bit for bit. A uint8
+ # multiply wraps (white came back as 1, pure red as 180), so accumulate in int32 and round back.
if image.dtype == torch.uint8:
- rgb_weights = torch.tensor([76, 150, 29], device=image.device, dtype=torch.uint8)
+ r, g, b = image.unbind(dim=-3)
+ acc = r.to(torch.int32) * 9798 + g.to(torch.int32) * 19235 + b.to(torch.int32) * 3735
+ return ((acc + 16384) // 32768).to(dtype=torch.uint8).unsqueeze(-3)
# floating point images
- elif image.dtype in (torch.bfloat16, torch.float16, torch.float32, torch.float64):
+ if image.dtype in (torch.bfloat16, 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}")
diff --git a/tests/color/test_gray.py b/tests/color/test_gray.py
index f1e6e62c5..9eac4cebe 100644
--- a/tests/color/test_gray.py
+++ b/tests/color/test_gray.py
@@ -136,6 +136,32 @@ class TestRgbToGrayscale(BaseTester):
assert out.device == img.device
assert out.dtype == img.dtype
+ def test_uint8_primaries(self, device):
+ white = torch.full((3, 1, 1), 255, device=device, dtype=torch.uint8)
+ red = torch.tensor([[[255]], [[0]], [[0]]], device=device, dtype=torch.uint8)
+ green = torch.tensor([[[0]], [[255]], [[0]]], device=device, dtype=torch.uint8)
+ blue = torch.tensor([[[0]], [[0]], [[255]]], device=device, dtype=torch.uint8)
+ assert kornia.color.rgb_to_grayscale(white).item() == 255
+ assert kornia.color.rgb_to_grayscale(red).item() == 76
+ assert kornia.color.rgb_to_grayscale(green).item() == 150
+ assert kornia.color.rgb_to_grayscale(blue).item() == 29
+
+ def test_uint8_opencv(self, device):
+ # Generated with OpenCV 4.10.0 and 5.0.0 (identical):
+ # cv2.cvtColor(np.array(rgb, dtype=np.uint8), cv2.COLOR_RGB2GRAY) on the HxWx3 rows below.
+ # (12, 250, 9) is 151 in OpenCV but 152 with the 8-bit weights 76/150/29 over 255; (0, 1, 1) and
+ # (100, 150, 50) need round-to-nearest rather than floor.
+ rgb = [
+ [[[255, 255, 255], [255, 0, 0], [0, 255, 0]], [[0, 0, 255], [0, 1, 1], [12, 250, 9]]],
+ [[[100, 150, 50], [33, 66, 99], [12, 0, 8]], [[37, 14, 37], [0, 12, 4], [12, 37, 28]]],
+ ]
+ expected = [[[[255, 76, 150], [29, 1, 151]]], [[[124, 60, 5], [23, 8, 28]]]]
+ img = torch.tensor(rgb, device=device, dtype=torch.uint8).permute(0, 3, 1, 2)
+ out = kornia.color.rgb_to_grayscale(img)
+ assert out.shape == (2, 1, 2, 3)
+ assert out.dtype == torch.uint8
+ assert torch.equal(out, torch.tensor(expected, device=device, dtype=torch.uint8))
+
@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):
img = torch.ones(batch_size, 3, height, width, device=device, dtype=dtype)