Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Implement color space conversion in Image and add tests (#3217)

Sidd7898ccbfc802
diff --git a/kornia/image/image.py b/kornia/image/image.py
index 673c1323d..7f253dbf9 100644
--- a/kornia/image/image.py
+++ b/kornia/image/image.py
@@ -23,6 +23,7 @@ from typing import Any
import torch
from torch.utils.dlpack import from_dlpack, to_dlpack
+import kornia.color
from kornia.core import Device, Dtype, Tensor
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.image.base import ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormat
@@ -186,10 +187,90 @@ class Image:
self._data = self.data.float()
return self
- # TODO implement this
- def to_color_space(self, color_space: ColorSpace) -> Image:
- """Convert the image to a different color space."""
- raise NotImplementedError
+ def to_gray(self) -> Image:
+ """Converts the image to grayscale."""
+ src = self._pixel_format.color_space
+ data = self._data
+
+ if src == ColorSpace.GRAY:
+ return self
+
+ is_channels_last = self._layout.channels_order == ChannelsOrder.CHANNELS_LAST
+ if is_channels_last:
+ data = data.permute(0, 3, 1, 2) if data.ndim == 4 else data.permute(2, 0, 1)
+
+ # Perform the color space conversion
+ if src == ColorSpace.RGB:
+ out = kornia.color.rgb_to_grayscale(data)
+ elif src == ColorSpace.BGR:
+ out = kornia.color.bgr_to_grayscale(data)
+ else:
+ raise ValueError(f"Unsupported source color space for to_gray(): {src}")
+
+ if is_channels_last:
+ if out.ndim == 4:
+ out = out.permute(0, 2, 3, 1)
+ elif out.ndim == 3:
+ out = out.permute(1, 2, 0)
+ else:
+ raise ValueError(f"Unexpected shape after grayscale conversion: {out.shape}")
+
+ new_pf = PixelFormat(color_space=ColorSpace.GRAY, bit_depth=self._pixel_format.bit_depth)
+ new_layout = ImageLayout(self._layout.image_size, channels=1, channels_order=self._layout.channels_order)
+ return Image(out, new_pf, new_layout)
+
+ def to_rgb(self) -> Image:
+ """Converts the image to RGB."""
+ src = self._pixel_format.color_space
+ data = self._data
+
+ if src == ColorSpace.RGB:
+ return self
+
+ is_channels_last = self._layout.channels_order == ChannelsOrder.CHANNELS_LAST
+ if is_channels_last:
+ data = data.permute(0, 3, 1, 2) if data.ndim == 4 else data.permute(2, 0, 1)
+
+ if src == ColorSpace.GRAY:
+ out = kornia.color.grayscale_to_rgb(data)
+ elif src == ColorSpace.BGR:
+ out = data[:, [2, 1, 0], ...] if data.ndim == 4 else data[[2, 1, 0], ...]
+ else:
+ raise ValueError(f"Unsupported source color space for to_rgb(): {src}")
+
+ if is_channels_last:
+ out = out.permute(0, 2, 3, 1) if out.ndim == 4 else out.permute(1, 2, 0)
+
+ new_pf = PixelFormat(color_space=ColorSpace.RGB, bit_depth=self._pixel_format.bit_depth)
+ new_layout = ImageLayout(self._layout.image_size, channels=3, channels_order=self._layout.channels_order)
+ return Image(out, new_pf, new_layout)
+
+ def to_bgr(self) -> Image:
+ """Converts the image to BGR."""
+ src = self._pixel_format.color_space
+ data = self._data
+
+ if src == ColorSpace.BGR:
+ return self
+
+ is_channels_last = self._layout.channels_order == ChannelsOrder.CHANNELS_LAST
+ if is_channels_last:
+ data = data.permute(0, 3, 1, 2) if data.ndim == 4 else data.permute(2, 0, 1)
+
+ if src == ColorSpace.GRAY:
+ rgb_data = kornia.color.grayscale_to_rgb(data)
+ out = rgb_data[:, [2, 1, 0], ...] if rgb_data.ndim == 4 else rgb_data[[2, 1, 0], ...]
+ elif src == ColorSpace.RGB:
+ out = data[:, [2, 1, 0], ...] if data.ndim == 4 else data[[2, 1, 0], ...]
+ else:
+ raise ValueError(f"Unsupported source color space for to_bgr(): {src}")
+
+ if is_channels_last:
+ out = out.permute(0, 2, 3, 1) if out.ndim == 4 else out.permute(1, 2, 0)
+
+ new_pf = PixelFormat(color_space=ColorSpace.BGR, bit_depth=self._pixel_format.bit_depth)
+ new_layout = ImageLayout(self._layout.image_size, channels=3, channels_order=self._layout.channels_order)
+ return Image(out, new_pf, new_layout)
@classmethod
def from_numpy(
diff --git a/tests/image/test_image.py b/tests/image/test_image.py
index 3ead7ee61..1026330c6 100644
--- a/tests/image/test_image.py
+++ b/tests/image/test_image.py
@@ -98,3 +98,51 @@ class TestImage:
data = np.ones((4, 5, 3), dtype=np.uint8)
img = Image.from_numpy(data, color_space=ColorSpace.RGB, channels_order=ChannelsOrder.CHANNELS_LAST)
img.write(tmp_path / "image.jpg")
+
+
+def make_image(data: torch.Tensor, cs: ColorSpace, order: ChannelsOrder) -> Image:
+ if order not in [ChannelsOrder.CHANNELS_FIRST, ChannelsOrder.CHANNELS_LAST]:
+ pytest.skip(f"Skipping unsupported channels_order: {order}")
+ if order == ChannelsOrder.CHANNELS_FIRST:
+ C, H, W = data.shape
+ else:
+ H, W, C = data.shape
+ pf = PixelFormat(color_space=cs, bit_depth=data.element_size() * 8)
+ layout = ImageLayout(image_size=ImageSize(H, W), channels=C, channels_order=order)
+ return Image(data.clone(), pf, layout)
+
+
[email protected]("order", [ChannelsOrder.CHANNELS_FIRST, ChannelsOrder.CHANNELS_LAST])
+def test_color_space_conversions(order):
+ rgb_val = torch.tensor([0.5, 0.2, 0.1], dtype=torch.float32)
+ bgr_val = rgb_val.flip(0)
+
+ if order == ChannelsOrder.CHANNELS_FIRST:
+ rgb_data = rgb_val.view(3, 1, 1)
+ bgr_data = bgr_val.view(3, 1, 1)
+ else:
+ rgb_data = rgb_val.view(1, 1, 3)
+ bgr_data = bgr_val.view(1, 1, 3)
+
+ # Create images
+ img_rgb = make_image(rgb_data, ColorSpace.RGB, order)
+ img_bgr = make_image(bgr_data, ColorSpace.BGR, order)
+
+ # 1) RGB -> Gray -> RGB
+ gray = img_rgb.to_gray()
+ lum = 0.299 * rgb_val[0] + 0.587 * rgb_val[1] + 0.114 * rgb_val[2]
+ assert pytest.approx(gray.data.squeeze().item(), rel=1e-3) == lum
+ rgb_back = gray.to_rgb().data.squeeze()
+ expected = torch.tensor([lum, lum, lum])
+ assert torch.allclose(rgb_back, expected)
+
+ # 2) BGR -> Gray -> BGR
+ gray2 = img_bgr.to_gray()
+ assert pytest.approx(gray2.data.squeeze().item(), rel=1e-3) == lum
+ bgr_back = gray2.to_bgr().data.squeeze()
+ expected_bgr = expected.flip(0)
+ assert torch.allclose(bgr_back, expected_bgr)
+
+ # 3) RGB <-> BGR swap
+ assert torch.allclose(img_rgb.to_bgr().data.squeeze(), bgr_val)
+ assert torch.allclose(img_bgr.to_rgb().data.squeeze(), rgb_val)