Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(color): preserve RGBA conversion shape contracts (#5296)

Devulapalli Naga Sri Vaishnavid73a4d6cb013
diff --git a/changelog.d/5296.breaking.md b/changelog.d/5296.breaking.md
new file mode 100644
index 000000000..b8d5fc9d9
--- /dev/null
+++ b/changelog.d/5296.breaking.md
@@ -0,0 +1,6 @@
+`rgba_to_rgb` keeps the leading dimensions of its input when `background_color` is a tuple or list: a `(4, H, W)`
+image used to come back as `(1, 3, H, W)` and now returns `(3, H, W)` (#5323). `rgb_to_rgba`, `bgr_to_rgba`,
+`RgbToRgba` and `BgrToRgba` now raise `ValueError` unless a tensor `alpha_val` has the image's shape with one channel,
+`(*, 1, H, W)`. A multi-channel alpha used to be appended as is, so a `(B, 2, H, W)` alpha returned a five-channel
+`(B, 5, H, W)` image; an alpha whose batch or spatial size differed from the image's failed inside `torch.cat` with a
+`RuntimeError`.
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index 0aa3b1723..e95efe84e 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -81,8 +81,8 @@ def rgb_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> t
Args:
image: RGB Image to be converted to RGBA of shape :math:`(*,3,H,W)`.
- alpha_val (float, torch.Tensor): A float number for the alpha value or a torch.tensor
- of shape :math:`(*,1,H,W)`.
+ alpha_val (float, torch.Tensor): A float number for the alpha value or a torch.Tensor
+ of shape :math:`(*,1,H,W)` matching the image's leading and spatial dimensions.
Returns:
RGBA version of the image with shape :math:`(*,4,H,W)`.
@@ -110,6 +110,8 @@ def rgb_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> t
if isinstance(alpha_val, float):
a = torch.full_like(r, fill_value=float(alpha_val))
+ elif alpha_val.shape != r.shape:
+ raise ValueError(f"alpha_val must have shape {r.shape}. Got {alpha_val.shape}")
return torch.cat([r, g, b, a], dim=-3)
@@ -120,7 +122,7 @@ def bgr_to_rgba(image: torch.Tensor, alpha_val: Union[float, torch.Tensor]) -> t
Args:
image: BGR Image to be converted to RGBA of shape :math:`(*,3,H,W)`.
alpha_val: A float number for the alpha value or a torch.Tensor
- of shape :math:`(*,1,H,W)`.
+ of shape :math:`(*,1,H,W)` matching the image's leading and spatial dimensions.
Returns:
RGBA version of the image with shape :math:`(*,4,H,W)`.
@@ -183,7 +185,8 @@ def rgba_to_rgb(image: torch.Tensor, background_color: Optional[torch.Tensor] =
elif isinstance(background_color, (tuple, list)):
if len(background_color) != 3:
raise ValueError("background_color as a list/tuple must have 3 elements (R, G, B).")
- background_rgb = torch.as_tensor(background_color, device=image.device, dtype=image.dtype).view(-1, 3, 1, 1)
+ # A channel-first color broadcasts over any leading dimensions without adding a batch axis.
+ background_rgb = torch.as_tensor(background_color, device=image.device, dtype=image.dtype).view(3, 1, 1)
elif isinstance(background_color, torch.Tensor):
if background_color.shape[-3] != 3:
diff --git a/tests/color/test_rgb.py b/tests/color/test_rgb.py
index f7e02a521..cca638461 100644
--- a/tests/color/test_rgb.py
+++ b/tests/color/test_rgb.py
@@ -175,6 +175,39 @@ class TestRgbToRgba(BaseTester):
x_bgr_new = kornia.color.rgba_to_bgr(x_rgba)
self.assert_close(x_bgr, x_bgr_new)
+ @pytest.mark.parametrize("conversion", [kornia.color.rgb_to_rgba, kornia.color.bgr_to_rgba])
+ def test_alpha_tensor_must_be_single_channel(self, conversion, device, dtype):
+ image = torch.ones(3, 2, 2, device=device, dtype=dtype)
+ alpha = torch.ones(2, 2, 2, device=device, dtype=dtype)
+
+ with pytest.raises(ValueError, match="alpha"):
+ conversion(image, alpha)
+
+ @pytest.mark.parametrize("conversion", [kornia.color.rgb_to_rgba, kornia.color.bgr_to_rgba])
+ def test_alpha_tensor_must_match_image_batch(self, conversion, device, dtype):
+ image = torch.ones(2, 3, 2, 2, device=device, dtype=dtype)
+ alpha = torch.ones(1, 1, 2, 2, device=device, dtype=dtype)
+
+ with pytest.raises(ValueError, match="alpha"):
+ conversion(image, alpha)
+
+ @pytest.mark.parametrize("background", [(1.0, 0.0, 0.0), [1.0, 0.0, 0.0]])
+ @pytest.mark.parametrize("leading", [(), (2,), (2, 3)])
+ def test_rgba_custom_background_preserves_leading_dims(self, background, leading, device, dtype):
+ image = torch.tensor([0.2, 0.4, 0.6, 0.5], device=device, dtype=dtype).view(4, 1, 1)
+ expected = torch.tensor([0.6, 0.2, 0.3], device=device, dtype=dtype).view(3, 1, 1)
+ image = image.expand(*leading, 4, 1, 1)
+ expected = expected.expand(*leading, 3, 1, 1)
+
+ result = kornia.color.rgba_to_rgb(image, background)
+ assert result.shape == expected.shape
+ self.assert_close(result, expected)
+
+ def test_rgba_to_rgb_jit_with_default_background(self, device, dtype):
+ image = torch.rand(4, 2, 2, device=device, dtype=dtype)
+ scripted = torch.jit.script(kornia.color.rgba_to_rgb)
+ self.assert_close(scripted(image), kornia.color.rgba_to_rgb(image))
+
@pytest.mark.parametrize("aval", [0.4, 45.0])
def test_unit(self, device, dtype, aval):
data = torch.tensor(