Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(image): prevent empty output for very wide images (#5264)

NiteeshGowda726d274bef0124
diff --git a/changelog.d/5264.fixed.md b/changelog.d/5264.fixed.md
new file mode 100644
index 000000000..57965fc7e
--- /dev/null
+++ b/changelog.d/5264.fixed.md
@@ -0,0 +1 @@
+Fix `image_to_string`, and with it `print_image` and `Image.print`, printing nothing for very wide images whose resized height rounds down to zero.
diff --git a/kornia/image/image_print.py b/kornia/image/image_print.py
index cd77a128e..01adc3e87 100644
--- a/kornia/image/image_print.py
+++ b/kornia/image/image_print.py
@@ -371,7 +371,7 @@ def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
image = image / 255.0
if image.shape[-1] > max_width:
- new_h = image.size(-2) * max_width // image.size(-1)
+ new_h = max(1, image.size(-2) * max_width // image.size(-1))
image = kornia.geometry.resize(image, (new_h, max_width))
image = (image * 255).clamp(0, 255).long()
diff --git a/tests/image/test_print.py b/tests/image/test_print.py
index aead4eba7..77681b3e2 100644
--- a/tests/image/test_print.py
+++ b/tests/image/test_print.py
@@ -22,6 +22,14 @@ from kornia.image import image_to_string, print_image
class TestImageToString:
+ @pytest.mark.parametrize(("height", "rows"), [(2, 1), (3, 1), (6, 1), (10, 2)])
+ def test_wide_image_keeps_at_least_one_row(self, height, rows, device, dtype):
+ # the resized height is max(1, H * max_width // W): a wide, short image keeps one row, taller ones are unchanged
+ image = torch.rand(3, height, 40, device=device, dtype=dtype)
+ out = image_to_string(image, max_width=10)
+ assert out.count("\n") == rows
+ assert out.count("\033[48;5;") == rows * 10
+
def test_value(self):
image = torch.arange(16).reshape(1, 4, 4).repeat(3, 1, 1).long() * 16
out = image_to_string(image)