Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix draw_line crash on a 0-d scalar color (#4850)

Mohammad Hijjawibce41351c83b
diff --git a/changelog.d/4850.fixed.md b/changelog.d/4850.fixed.md
new file mode 100644
index 000000000..1a8b21b21
--- /dev/null
+++ b/changelog.d/4850.fixed.md
@@ -0,0 +1 @@
+`draw_line` accepts a 0-d scalar color for single-channel images instead of raising `IndexError` on `color.size(0)`.
diff --git a/kornia/image/draw.py b/kornia/image/draw.py
index 5d95a9b87..cd7a4c2c0 100644
--- a/kornia/image/draw.py
+++ b/kornia/image/draw.py
@@ -91,7 +91,8 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
image: the input image to where to draw the lines with shape :math`(C,H,W)`.
p1: the start point [x y] of the line with shape (2, ) or (B, 2).
p2: the end point [x y] of the line, with the same shape as ``p1``.
- color: the color of the line with shape :math`(C)` where :math`C` is the number of channels of the image.
+ color: the color of the line with shape :math`(C)` where :math`C` is the number of channels
+ of the image. A 0-d scalar is accepted when the image has a single channel.
Return:
The image containing the line. This operation modifies image inplace but also returns
@@ -133,6 +134,11 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
if len(image.size()) != 3:
raise ValueError("image must have 3 dimensions (C,H,W).")
+ # A 0-d scalar (e.g. torch.tensor(255) for grayscale) is a common call shape;
+ # color.size(0) used to IndexError. Treat it as a length-1 channel vector.
+ if color.ndim == 0:
+ color = color.unsqueeze(0)
+
if color.size(0) != image.size(0):
raise ValueError("color must have the same number of channels as the image.")
diff --git a/tests/image/test_draw.py b/tests/image/test_draw.py
index 4b94a08cc..d0696fde0 100644
--- a/tests/image/test_draw.py
+++ b/tests/image/test_draw.py
@@ -420,6 +420,12 @@ class TestDrawLine(BaseTester):
expected = draw_line(expected, a, b, color)
self.assert_close(batched, expected, rtol=0.0, atol=0.0)
+ def test_draw_line_accepts_0d_scalar_color(self, dtype, device):
+ # torch.tensor(255) is a natural grayscale color; color.size(0) used to IndexError.
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ out = draw_line(img, torch.tensor([1, 4]), torch.tensor([6, 4]), torch.tensor(255, dtype=dtype, device=device))
+ assert out[0, 4, 1:7].tolist() == [255.0] * 6
+
class TestDrawRectangle(BaseTester):
@pytest.mark.parametrize("batch", (4, 17))