Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(image): print one-channel images in image_to_string (#5259)

Mohammad Hijjawi31fe69eba69c
diff --git a/changelog.d/5259.fixed.md b/changelog.d/5259.fixed.md
new file mode 100644
index 000000000..51cc36562
--- /dev/null
+++ b/changelog.d/5259.fixed.md
@@ -0,0 +1 @@
+`image_to_string`, `print_image` and `Image.print` now print one-channel (grayscale) images instead of raising `RuntimeError` or `IndexError`. For `Image.print` this covers channels-first data; channels-last grayscale images print once #5232 is merged.
diff --git a/kornia/image/image_print.py b/kornia/image/image_print.py
index 01adc3e87..916e4dc0e 100644
--- a/kornia/image/image_print.py
+++ b/kornia/image/image_print.py
@@ -361,7 +361,7 @@ def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
The torch.Tensor shall be either 0~1 float type or 0~255 long type.
Args:
- image: an RGB image with shape :math:`3HW`.
+ image: an RGB image with shape :math:`3HW` or a grayscale image with shape :math:`1HW`.
max_width: maximum width of the input image.
"""
KORNIA_CHECK_IS_IMAGE(image, None, raises=True)
@@ -376,6 +376,10 @@ def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
image = (image * 255).clamp(0, 255).long()
+ if image.shape[0] == 1:
+ # a grey value is the same colour in each of the three terminal components
+ image = image.expand(3, -1, -1)
+
H, W = image.shape[-2:]
flat = image.permute(1, 2, 0).reshape(-1, 3)
diff --git a/tests/image/test_print.py b/tests/image/test_print.py
index 77681b3e2..bc534aea1 100644
--- a/tests/image/test_print.py
+++ b/tests/image/test_print.py
@@ -42,6 +42,19 @@ class TestImageToString:
)
assert out == expected
+ @pytest.mark.parametrize("max_width", [256, 3])
+ @pytest.mark.parametrize("shape", [(1, 5, 6), (1, 4, 4), (1, 1, 2), (1, 7, 1)])
+ @pytest.mark.parametrize("input_dtype", [torch.float32, torch.float64, torch.uint8, torch.int64])
+ def test_grayscale_matches_its_rgb_copy(self, shape, input_dtype, max_width):
+ generator = torch.Generator().manual_seed(0)
+ if input_dtype.is_floating_point:
+ gray = torch.rand(shape, generator=generator, dtype=input_dtype)
+ else:
+ gray = torch.randint(0, 256, shape, generator=generator).to(input_dtype)
+ out = image_to_string(gray, max_width)
+ assert out # an empty string would make the comparison below vacuous
+ assert out == image_to_string(gray.repeat(3, 1, 1), max_width)
+
def test_exception(self):
img = torch.rand(3, 15, 15)
image_to_string(img)