Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix `draw_line` produce wrong output for coordinates larger than uint8 (#1564)

Hoàng Tùng Lâm (Linus)ea4d22d129d2
diff --git a/kornia/utils/draw.py b/kornia/utils/draw.py
index 89deea241..93ba98db6 100644
--- a/kornia/utils/draw.py
+++ b/kornia/utils/draw.py
@@ -60,8 +60,11 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
if (p2[0] >= image.size(2)) or (p2[1] >= image.size(1) or (p2[0] < 0) or (p2[1] < 0)):
raise ValueError("p2 is out of bounds.")
- # make move arguments to same device and dtype as the input image
- p1, p2, color = p1.to(image), p2.to(image), color.to(image)
+ # move p1 and p2 to the same device as the input image
+ # move color to the same device and dtype as the input image
+ p1 = p1.to(image.device).to(torch.int64)
+ p2 = p2.to(image.device).to(torch.int64)
+ color = color.to(image)
# assign points
x1, y1 = p1
diff --git a/test/utils/test_draw.py b/test/utils/test_draw.py
index 1daadd2ba..cab2e116f 100644
--- a/test/utils/test_draw.py
+++ b/test/utils/test_draw.py
@@ -39,6 +39,14 @@ class TestDrawLine:
]], device=device, dtype=dtype)
assert_close(img, img_mask)
+ def test_draw_line_with_big_coordinates(self, dtype, device):
+ """Test drawing a line with big coordinates."""
+ img = torch.zeros(1, 500, 500, dtype=dtype, device=device)
+ img = draw_line(img, torch.tensor([200, 200]), torch.tensor([400, 200]), torch.tensor([255]))
+ img_mask = torch.zeros(1, 500, 500, dtype=dtype, device=device)
+ img_mask[:, 200, 200:401] = 255
+ assert_close(img, img_mask)
+
def test_draw_line_m_lte_neg1(self, dtype, device):
"""Test drawing a line with m <= -1."""
img = torch.zeros(1, 8, 8, dtype=dtype, device=device)