Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(io): keep RGB and grayscale opaque when loading as RGBA (#5077)

NIKHIL27933334a791
diff --git a/changelog.d/5077.breaking.md b/changelog.d/5077.breaking.md
new file mode 100644
index 000000000..9aa8a9b66
--- /dev/null
+++ b/changelog.d/5077.breaking.md
@@ -0,0 +1,3 @@
+`load_image` with `ImageLoadType.RGBA8` now fills the alpha channel it adds to RGB and grayscale images with 255, so
+they load opaque. It used to fill that channel with 0, which made them fully transparent. Images that already have an
+alpha channel keep their own.
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 245198060..2a81e2342 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -156,9 +156,9 @@ def _convert_image_type(image: torch.Tensor, desired_type: ImageLoadType) -> tor
case (ImageLoadType.RGBA8, 4):
return image
case (ImageLoadType.RGBA8, 3):
- return _to_uint8(kornia.color.rgb_to_rgba(_to_float32(image), 0.0))
+ return _to_uint8(kornia.color.rgb_to_rgba(_to_float32(image), 1.0))
case (ImageLoadType.RGBA8, 1):
- return _to_uint8(kornia.color.rgb_to_rgba(kornia.color.grayscale_to_rgb(_to_float32(image)), 0.0))
+ return _to_uint8(kornia.color.rgb_to_rgba(kornia.color.grayscale_to_rgb(_to_float32(image)), 1.0))
case (ImageLoadType.GRAY32, 1):
return _to_float32(image)
case (ImageLoadType.GRAY32, 3):
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index 24c02b35f..9fed97b17 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -132,6 +132,18 @@ class TestIoImage:
assert img.shape[0] == expected_channels
assert img.dtype == expected_type
+ @pytest.mark.parametrize("channels,mode", [(1, "mono"), (3, "rgb")])
+ def test_load_opaque_image_as_rgba(self, tmp_path: Path, channels: int, mode: str) -> None:
+ pixels = np.full((2, 2, channels), 64, dtype=np.uint8)
+ path = tmp_path / "image.png"
+ kornia_rs.io.write_image_png_u8(str(path), pixels, mode=mode)
+
+ rgba = load_image(path, ImageLoadType.RGBA8)
+
+ assert rgba.shape == (4, 2, 2)
+ assert torch.equal(rgba[:3], torch.full((3, 2, 2), 64, dtype=torch.uint8))
+ assert torch.equal(rgba[3], torch.full((2, 2), 255, dtype=torch.uint8))
+
@pytest.mark.parametrize("ext", ["jpg"])
@pytest.mark.parametrize("channels", [3])
def test_write_image(self, device, tmp_path, ext, channels):