Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(image): always draw both endpoints in draw_line, on the image's device (#4596)

Dipak Chaudhari8406a5a97a83
diff --git a/changelog.d/4596.fixed.md b/changelog.d/4596.fixed.md
new file mode 100644
index 000000000..d852fc22d
--- /dev/null
+++ b/changelog.d/4596.fixed.md
@@ -0,0 +1 @@
+`draw_line` now always draws both endpoints: it could stop one pixel short of `p2`, or pass a row or column off a pixel centre the line runs exactly through, because the minor coordinate was stepped in floating point. It is now placed at `ceil(t * minor / major)` in integers, one pixel per step along the major axis. `draw_line` also builds every line's pixels on the image's device instead of in Python loops over 0-d tensors, accepts an empty `(0, 2)` batch, and rejects a `p1` and `p2` of different shapes instead of broadcasting a `(2,)` point against a `(B, 2)` batch.
diff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.py
index 0b2cccf1e..27b164531 100644
--- a/docs/export_support/cases_models.py
+++ b/docs/export_support/cases_models.py
@@ -1478,7 +1478,7 @@ A(
"image",
K.image.draw_line,
[torch.zeros(3, 16, 24), torch.tensor([2, 3]), torch.tensor([20, 12]), torch.tensor([1.0, 0.5, 0.2])],
- note="Bresenham-like Python loop over max(|dx|,|dy|) computed from tensor values",
+ note="per-line pixels built on the device with nonzero; int(max) of the longest line reads a tensor value",
)
)
A(
diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.json
index cf8120055..f22a38b24 100644
--- a/docs/source/_data/export_support.json
+++ b/docs/source/_data/export_support.json
@@ -22651,7 +22651,7 @@
"export_detail": "a Python branch (if / while) tests tensor values at run time",
"graph_breaks": 15,
"name": "image.draw_line",
- "note": "Bresenham-like Python loop over max(|dx|,|dy|) computed from tensor values",
+ "note": "per-line pixels built on the device with nonzero; int(max) of the longest line reads a tensor value",
"onnx": "fail",
"onnx_detail": "a Python branch (if / while) tests tensor values at run time",
"operator": "draw_line",
diff --git a/kornia/image/draw.py b/kornia/image/draw.py
index e6269e332..a6b38a2e5 100644
--- a/kornia/image/draw.py
+++ b/kornia/image/draw.py
@@ -73,10 +73,14 @@ def _draw_pixel(image: torch.Tensor, x: int, y: int, color: torch.Tensor) -> Non
def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: torch.Tensor) -> torch.Tensor:
r"""Draw a single line into an image.
+ Each line is rasterized one pixel per step along its major axis, the one with the larger extent:
+ at step ``t = 0 .. major`` the minor coordinate advances by ``ceil(t * minor / major)``, computed in
+ integers. Both ``p1`` and ``p2`` are therefore always drawn.
+
Args:
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 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.
Return:
@@ -95,7 +99,8 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
[ 0., 0., 0., 0., 0., 0., 0., 0.]]])
"""
- if (p1.shape[0] != p2.shape[0]) or (p1.shape[-1] != 2 or p2.shape[-1] != 2):
+ # equal shapes, not just equal leading sizes: a (2,) p1 would otherwise broadcast against a (2, 2) p2
+ if (p1.shape != p2.shape) or (p1.shape[-1] != 2):
raise ValueError(
"Input points must be 2D points with shape (2, ) or (B, 2) and must have the same batch sizes."
)
@@ -126,81 +131,35 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
p2 = p2.to(image.device).to(torch.int64)
color = color.to(image)
- x1, y1 = p1[..., 0], p1[..., 1]
- x2, y2 = p2[..., 0], p2[..., 1]
- dx = x2 - x1
- dy = y2 - y1
+ p1 = p1.reshape(-1, 2)
+ p2 = p2.reshape(-1, 2)
+ x1, y1 = p1[:, 0:1], p1[:, 1:2]
+ dx = p2[:, 0:1] - x1
+ dy = p2[:, 1:2] - y1
dx_sign = torch.sign(dx)
dy_sign = torch.sign(dy)
dx, dy = torch.abs(dx), torch.abs(dy)
- dx_zero_mask = dx == 0
- dy_zero_mask = dy == 0
- dx_gt_dy_mask = (dx > dy) & ~(dx_zero_mask | dy_zero_mask)
- rest_mask = ~(dx_zero_mask | dy_zero_mask | dx_gt_dy_mask)
-
- dx_zero_x_coords, dx_zero_y_coords = [], []
- dy_zero_x_coords, dy_zero_y_coords = [], []
- dx_gt_dy_x_coords, dx_gt_dy_y_coords = [], []
- rest_x_coords, rest_y_coords = [], []
-
- if dx_zero_mask.any():
- dx_zero_x_coords = [
- x for x_i, dy_i in zip(x1[dx_zero_mask], dy[dx_zero_mask]) for x in x_i.repeat(int(dy_i.item() + 1))
- ]
- dx_zero_y_coords = [
- y
- for y_i, s, dy_ in zip(y1[dx_zero_mask], dy_sign[dx_zero_mask], dy[dx_zero_mask])
- for y in (y_i + s * torch.arange(0, dy_ + 1, 1, device=image.device))
- ]
-
- if dy_zero_mask.any():
- dy_zero_x_coords = [
- x
- for x_i, s, dx_i in zip(x1[dy_zero_mask], dx_sign[dy_zero_mask], dx[dy_zero_mask])
- for x in (x_i + s * torch.arange(0, dx_i + 1, 1, device=image.device))
- ]
- dy_zero_y_coords = [
- y for y_i, dx_i in zip(y1[dy_zero_mask], dx[dy_zero_mask]) for y in y_i.repeat(int(dx_i.item() + 1))
- ]
-
- if dx_gt_dy_mask.any():
- dx_gt_dy_x_coords = [
- x
- for x_i, s, dx_i in zip(x1[dx_gt_dy_mask], dx_sign[dx_gt_dy_mask], dx[dx_gt_dy_mask])
- for x in (x_i + s * torch.arange(0, dx_i + 1, 1, device=image.device))
- ]
- dx_gt_dy_y_coords = [
- y
- for y_i, s, dx_i, dy_i in zip(
- y1[dx_gt_dy_mask], dy_sign[dx_gt_dy_mask], dx[dx_gt_dy_mask], dy[dx_gt_dy_mask]
- )
- for y in (
- y_i + s * torch.arange(0, dy_i + 1, dy_i / dx_i, device=image.device)[: int(dx_i.item()) + 1].ceil()
- )
- ]
- if rest_mask.any():
- rest_x_coords = [
- x
- for x_i, s, dx_i, dy_ in zip(x1[rest_mask], dx_sign[rest_mask], dx[rest_mask], dy[rest_mask])
- for x in (
- x_i + s * torch.arange(0, dx_i + 1, dx_i / dy_, device=image.device)[: int(dy_.item()) + 1].ceil()
- )
- ]
- rest_y_coords = [
- y
- for y_i, s, dy_i in zip(y1[rest_mask], dy_sign[rest_mask], dy[rest_mask])
- for y in (y_i + s * torch.arange(0, dy_i + 1, 1, device=image.device))
- ]
- x_coords = torch.clamp(
- torch.tensor(dx_zero_x_coords + dy_zero_x_coords + dx_gt_dy_x_coords + rest_x_coords).long(),
- min=0,
- max=image.shape[-1] - 1,
- )
- y_coords = torch.clamp(
- torch.tensor(dx_zero_y_coords + dy_zero_y_coords + dx_gt_dy_y_coords + rest_y_coords).long(),
- min=0,
- max=image.shape[-2] - 1,
- )
+
+ # Every line steps one pixel at a time along its major axis and places the minor coordinate at
+ # ceil(t * minor / major). The (line, t) pairs with t <= major are taken first, so the work is one
+ # entry per drawn pixel rather than a (B, longest line) grid that pads every short line out. The
+ # ceiling is taken in integers: a float step lands just above an exact integer quotient and rounds
+ # it up a pixel. A vertical or horizontal line has minor = 0, and a single point has major = 0,
+ # which the clamp keeps from dividing by 0. An empty batch draws nothing.
+ x_major = dx > dy
+ major = torch.where(x_major, dx, dy)
+ minor = torch.where(x_major, dy, dx)
+ num_steps = int(major.max()) + 1 if major.numel() else 1
+ steps = torch.arange(num_steps, device=image.device).unsqueeze(0)
+ line, t = (steps <= major).nonzero(as_tuple=True)
+ divisor = major[line, 0].clamp_min(1)
+ t_minor = torch.div(t * minor[line, 0] + divisor - 1, divisor, rounding_mode="floor")
+ x_maj = x_major[line, 0]
+ x_coords = x1[line, 0] + dx_sign[line, 0] * torch.where(x_maj, t, t_minor)
+ y_coords = y1[line, 0] + dy_sign[line, 0] * torch.where(x_maj, t_minor, t)
+
+ x_coords = torch.clamp(x_coords, min=0, max=image.shape[-1] - 1)
+ y_coords = torch.clamp(y_coords, min=0, max=image.shape[-2] - 1)
image[:, y_coords, x_coords] = color.view(-1, 1)
return image
diff --git a/tests/image/test_draw.py b/tests/image/test_draw.py
index 2afd38dff..4f7e0387c 100644
--- a/tests/image/test_draw.py
+++ b/tests/image/test_draw.py
@@ -312,6 +312,57 @@ class TestDrawLine(BaseTester):
excinfo.value
)
+ # The tests below sit after test_point_size on purpose: its parametrize arguments call torch.rand at
+ # import time, and testing/half_precision_eager_rng.py audits that call by line number (305).
+ # Moving them above it shifts that line and fails the audit.
+ def test_draw_line_lights_both_endpoints(self, dtype, device):
+ # The integer ceiling reaches minor exactly at t = major, so p1 and p2 are both drawn. The float
+ # step this replaced left p2 dark on about 7% of random lines.
+ generator = torch.Generator().manual_seed(0)
+ height, width = 37, 91
+ xs = torch.randint(0, width, (300, 2), generator=generator)
+ ys = torch.randint(0, height, (300, 2), generator=generator)
+ color = torch.tensor([1.0])
+ for (x1, x2), (y1, y2) in zip(xs.tolist(), ys.tolist()):
+ img = torch.zeros(1, height, width, dtype=dtype, device=device)
+ img = draw_line(img, torch.tensor([x1, y1]), torch.tensor([x2, y2]), color)
+ assert img[0, y1, x1] == 1.0, ((x1, y1), (x2, y2))
+ assert img[0, y2, x2] == 1.0, ((x1, y1), (x2, y2))
+ assert img.sum() == max(abs(x2 - x1), abs(y2 - y1)) + 1, ((x1, y1), (x2, y2))
+
+ def test_draw_line_empty_batch_draws_nothing(self, dtype, device):
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ empty = torch.zeros(0, 2, dtype=torch.long)
+ out = draw_line(img, empty, empty, torch.tensor([1.0]))
+ assert out.shape == (1, 8, 8)
+ assert out.count_nonzero() == 0
+
+ def test_draw_line_rejects_points_of_different_shapes(self, dtype, device):
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ with pytest.raises(ValueError, match="must have the same batch sizes"):
+ draw_line(img, torch.tensor([1, 1]), torch.tensor([[2, 2], [3, 3]]), torch.tensor([1.0]))
+
+ def test_draw_line_passes_through_its_exact_lattice_points(self, dtype, device):
+ # The segment from (0, 0) to (117, 18) passes exactly through (13k, 2k). The minor coordinate
+ # is ceil(t * 18 / 117), and a float step landed just above the exact integer at some of
+ # these points, which rounded the pixel up a row: (26, 5) instead of (26, 4).
+ img = torch.zeros(1, 19, 118, dtype=dtype, device=device)
+ img = draw_line(img, torch.tensor([0, 0]), torch.tensor([117, 18]), torch.tensor([1.0]))
+ for k in range(10):
+ assert img[0, 2 * k, 13 * k] == 1.0, (13 * k, 2 * k)
+ assert img[0, :, 13 * k].sum() == 1.0, 13 * k
+
+ def test_draw_lines_batched_matches_drawing_each_line(self, dtype, device):
+ # One batch mixing a vertical, a horizontal, a single point and both slope regimes.
+ p1 = torch.tensor([[3, 1], [0, 9], [5, 5], [1, 2], [30, 0], [7, 18]])
+ p2 = torch.tensor([[3, 17], [31, 9], [5, 5], [29, 11], [2, 19], [26, 3]])
+ color = torch.tensor([1.0, 2.0])
+ batched = draw_line(torch.zeros(2, 20, 32, dtype=dtype, device=device), p1, p2, color)
+ expected = torch.zeros(2, 20, 32, dtype=dtype, device=device)
+ for a, b in zip(p1, p2):
+ expected = draw_line(expected, a, b, color)
+ self.assert_close(batched, expected, rtol=0.0, atol=0.0)
+
class TestDrawRectangle(BaseTester):
@pytest.mark.parametrize("batch", (4, 17))