Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add ``draw_line`` image utility (#1456)

Abdelrhman-Hosny3e1bcf65ad5c
diff --git a/docs/source/utils.rst b/docs/source/utils.rst
index b31a93904..b080b2fb5 100644
--- a/docs/source/utils.rst
+++ b/docs/source/utils.rst
@@ -3,13 +3,18 @@ kornia.utils
.. currentmodule:: kornia.utils
+Draw
+----
+
+.. autofunction:: draw_line
+.. autofunction:: draw_rectangle
+
Image
-----
.. autofunction:: tensor_to_image
.. autofunction:: image_to_tensor
.. autofunction:: image_list_to_tensor
-.. autofunction:: draw_rectangle
Grid
----
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index aae146d52..8ce5304f5 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -1,4 +1,4 @@
-from .draw import draw_rectangle
+from .draw import draw_line, draw_rectangle
from .grid import create_meshgrid, create_meshgrid3d
from .helpers import _extract_device_dtype, safe_inverse_with_mask, safe_solve_with_mask
from .image import image_list_to_tensor, image_to_tensor, ImageToTensor, tensor_to_image
@@ -18,6 +18,7 @@ __all__ = [
"save_pointcloud_ply",
"load_pointcloud_ply",
"draw_rectangle",
+ "draw_line",
"_extract_device_dtype",
"safe_inverse_with_mask",
"safe_solve_with_mask",
diff --git a/kornia/utils/draw.py b/kornia/utils/draw.py
index e296dc8c2..acae65e63 100644
--- a/kornia/utils/draw.py
+++ b/kornia/utils/draw.py
@@ -5,6 +5,134 @@ import torch
# TODO: implement width of the line
+def _draw_pixel(
+ image: torch.Tensor,
+ x: int,
+ y: int,
+ color: torch.Tensor,
+) -> None:
+ r"""Draws a pixel into an image.
+
+ Args:
+ image: the input image to where to draw the lines with shape :math`(C,H,W)`.
+ x: the x coordinate of the pixel.
+ y: the y coordinate of the pixel.
+ color: the color of the pixel with :math`(C)` where :math`C` is the number of channels of the image.
+
+ Return:
+ Nothing is returned.
+ """
+ image[:, y, x] = color
+
+
+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.
+
+ 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).
+ p2: the end point [x y] of the line with shape (2).
+ color: the color of the line with shape :math`(C)` where :math`C` is the number of channels of the image.
+
+ Return:
+ the image with containing the line.
+
+ Examples:
+ >>> image = torch.zeros(1, 8, 8)
+ >>> draw_line(image, torch.tensor([6, 4]), torch.tensor([1, 4]), torch.tensor([255]))
+ tensor([[[ 0., 0., 0., 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0., 0., 0., 0.],
+ [ 0., 255., 255., 255., 255., 255., 255., 0.],
+ [ 0., 0., 0., 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0., 0., 0., 0.]]])
+ """
+
+ if (len(p1) != 2) or (len(p2) != 2):
+ raise ValueError("p1 and p2 must have length 2.")
+
+ if len(image.size()) != 3:
+ raise ValueError("image must have 3 dimensions (C,H,W).")
+
+ if (color.size(0) != image.size(0)):
+ raise ValueError("color must have the same number of channels as the image.")
+
+ if (p1[0] >= image.size(2)) or (p1[1] >= image.size(1) or (p1[0] < 0) or (p1[1] < 0)):
+ raise ValueError("p1 is out of bounds.")
+
+ 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.")
+
+ # assign points
+ x1, y1 = p1
+ x2, y2 = p2
+
+ # calcullate coefficients A,B,C of line
+ # from equation Ax + By + C = 0
+ A = y2 - y1
+ B = x1 - x2
+ C = x2 * y1 - x1 * y2
+
+ # make sure A is positive to utilize the functiom properly
+ if (A < 0):
+ A = -A
+ B = -B
+ C = -C
+
+ # calculate the slope of the line
+ # check for division by zero
+ if (B != 0):
+ m = -A / B
+
+ # make sure you start drawing in the right direction
+ x1, x2 = min(x1, x2), max(x1, x2)
+ y1, y2 = min(y1, y2), max(y1, y2)
+
+ # line equation that determines the distance away from the line
+ def line_equation(x, y):
+ return A * x + B * y + C
+
+ # vertical line
+ if B == 0:
+ image[:, y1:y2 + 1, x1] = color
+ # horizontal line
+ elif A == 0:
+ image[:, y1, x1:x2 + 1] = color
+ # slope between 0 and 1
+ elif 0 < m < 1:
+ for i in range(x1, x2 + 1):
+ _draw_pixel(image, i, y1, color)
+ if line_equation(i + 1, y1 + 0.5) > 0:
+ y1 += 1
+ # slope greater than or equal to 1
+ elif m >= 1:
+ for j in range(y1, y2 + 1):
+ _draw_pixel(image, x1, j, color)
+ if line_equation(x1 + 0.5, j + 1) < 0:
+ x1 += 1
+ # slope less then -1
+ elif m <= -1:
+ for j in range(y1, y2 + 1):
+ _draw_pixel(image, x2, j, color)
+ if line_equation(x2 - 0.5, j + 1) > 0:
+ x2 -= 1
+ # slope between -1 and 0
+ elif -1 < m < 0:
+ for i in range(x1, x2 + 1):
+ _draw_pixel(image, i, y2, color)
+ if line_equation(i + 1, y2 - 0.5) > 0:
+ y2 -= 1
+
+ return image
+
+
def draw_rectangle(
image: torch.Tensor,
rectangle: torch.Tensor,
diff --git a/test/utils/test_draw.py b/test/utils/test_draw.py
index 3e352e2c6..061ab9434 100644
--- a/test/utils/test_draw.py
+++ b/test/utils/test_draw.py
@@ -2,6 +2,157 @@ import pytest
import torch
from kornia.utils import draw_rectangle
+from kornia.utils.draw import draw_line
+
+
+class TestDrawLine:
+ def test_draw_line_vertical(self, dtype, device):
+ """Test drawing a vertical line."""
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ img = draw_line(img, torch.tensor([6, 2]), torch.tensor([6, 0]), torch.tensor([255]))
+ img_mask = img == torch.tensor([[0., 0., 0., 0., 0., 0., 255., 0.],
+ [0., 0., 0., 0., 0., 0., 255., 0.],
+ [0., 0., 0., 0., 0., 0., 255., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.]])
+ assert torch.all(img_mask)
+
+ def test_draw_line_horizontal(self, dtype, device):
+ """Test drawing a horizontal line."""
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ img = draw_line(img, torch.tensor([6, 4]), torch.tensor([0, 4]), torch.tensor([255]))
+ img_mask = img == torch.tensor([[0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [255., 255., 255., 255., 255., 255., 255., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.]])
+ assert torch.all(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)
+ img = draw_line(img, torch.tensor([0, 7]), torch.tensor([6, 0]), torch.tensor([255]))
+ img_mask = img == torch.tensor([[0., 0., 0., 0., 0., 0., 255., 0.],
+ [0., 0., 0., 0., 0., 255., 0., 0.],
+ [0., 0., 0., 0., 255., 0., 0., 0.],
+ [0., 0., 0., 255., 0., 0., 0., 0.],
+ [0., 0., 0., 255., 0., 0., 0., 0.],
+ [0., 0., 255., 0., 0., 0., 0., 0.],
+ [0., 255., 0., 0., 0., 0., 0., 0.],
+ [255., 0., 0., 0., 0., 0., 0., 0.]])
+ assert torch.all(img_mask)
+
+ def test_draw_line_m_lt_0_gte_neg1(self, dtype, device):
+ """Test drawing a line with -1 < m < 0."""
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ img = draw_line(img, torch.tensor([1, 5]), torch.tensor([7, 0]), torch.tensor([255]))
+ img_mask = img == torch.tensor([[0., 0., 0., 0., 0., 0., 0., 255.],
+ [0., 0., 0., 0., 0., 0., 255., 0.],
+ [0., 0., 0., 0., 0., 255., 0., 0.],
+ [0., 0., 0., 255., 255., 0., 0., 0.],
+ [0., 0., 255., 0., 0., 0., 0., 0.],
+ [0., 255., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.]])
+ assert torch.all(img_mask)
+
+ def test_draw_line_m_gt_0_lt_1(self, dtype, device):
+ """Test drawing a line with 0 < m < 1."""
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ img = draw_line(img, torch.tensor([0, 0]), torch.tensor([6, 2]), torch.tensor([255]))
+ img_mask = img == torch.tensor([[255., 255., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 255., 255., 255., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 255., 255., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.]])
+ assert torch.all(img_mask)
+
+ def test_draw_line_m_gte_1(self, dtype, device):
+ """Test drawing a line with m >= 1."""
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ img = draw_line(img, torch.tensor([3, 7]), torch.tensor([1, 4]), torch.tensor([255]))
+ img_mask = img == torch.tensor([[0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 255., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 255., 0., 0., 0., 0., 0.],
+ [0., 0., 255., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 255., 0., 0., 0., 0.]])
+ assert torch.all(img_mask)
+
+ @pytest.mark.parametrize('p1',
+ [
+ torch.tensor([-1, 0]),
+ torch.tensor([0, -1]),
+ torch.tensor([8, 0]),
+ torch.tensor([0, 8]),
+ ])
+ def test_p1_out_of_bounds(self, p1, dtype, device):
+ """Tests that an exception is raised if p1 is out of bounds."""
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ with pytest.raises(ValueError) as excinfo:
+ draw_line(img, p1, torch.tensor([0, 0]), torch.tensor([255]))
+
+ assert 'p1 is out of bounds.' == str(excinfo.value)
+
+ @pytest.mark.parametrize('p2',
+ [
+ torch.tensor([-1, 0]),
+ torch.tensor([0, -1]),
+ torch.tensor([8, 0]),
+ torch.tensor([0, 8]),
+ ])
+ def test_p2_out_of_bounds(self, p2, dtype, device):
+ """Tests that an exception is raised if p2 is out of bounds."""
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ with pytest.raises(ValueError) as excinfo:
+ draw_line(img, torch.tensor([0, 0]), p2, torch.tensor([255]))
+
+ assert 'p2 is out of bounds.' == str(excinfo.value)
+
+ @pytest.mark.parametrize('img_size', [(200, 100), (32, 3, 20, 20)])
+ def test_image_size(self, img_size, dtype, device):
+ img = torch.zeros(*img_size, dtype=dtype, device=device)
+ with pytest.raises(ValueError) as excinfo:
+ draw_line(img, torch.tensor([0, 0]), torch.tensor([1, 1]), torch.tensor([255]))
+
+ assert 'image must have 3 dimensions (C,H,W).' == str(excinfo.value)
+
+ @pytest.mark.parametrize('img_size,color',
+ [
+ ((1, 8, 8), torch.tensor([23, 53])),
+ ((3, 8, 8), torch.tensor([255]))
+ ])
+ def test_color_image_channel_size(self, img_size, color, dtype, device):
+ img = torch.zeros(*img_size, dtype=dtype, device=device)
+ with pytest.raises(ValueError) as excinfo:
+ draw_line(img, torch.tensor([0, 0]), torch.tensor([1, 1]), color)
+
+ assert 'color must have the same number of channels as the image.' == str(excinfo.value)
+
+ @pytest.mark.parametrize('p1,p2',
+ [
+ ((0, 1), (1, 5, 2)),
+ ((0, 1, 2), (1, 5)),
+ (torch.tensor([0, 1]), torch.tensor([0, 2, 3])),
+ (torch.tensor([0, 1, 5]), torch.tensor([0, 2])),
+ ])
+ def test_point_size(self, p1, p2, dtype, device):
+ img = torch.zeros(1, 8, 8, dtype=dtype, device=device)
+ with pytest.raises(ValueError) as excinfo:
+ draw_line(img, p1, p2, torch.tensor([255]))
+
+ assert 'p1 and p2 must have length 2.' == str(excinfo.value)
class TestDrawRectangle:
@@ -65,8 +216,8 @@ class TestDrawRectangle:
random_w_rectangle[
b,
:,
- points_list[b][n][1] : points_list[b][n][3] + 1,
- points_list[b][n][0] : points_list[b][n][2] + 1,
+ points_list[b][n][1]: points_list[b][n][3] + 1,
+ points_list[b][n][0]: points_list[b][n][2] + 1,
].sum()
== (points_list[b][n][3] - points_list[b][n][1] + 1)
* (points_list[b][n][2] - points_list[b][n][0] + 1)
@@ -75,25 +226,25 @@ class TestDrawRectangle:
else:
assert (
random_w_rectangle[
- b, :, points_list[b][n][1] : points_list[b][n][3] + 1, points_list[b][n][0]
+ b, :, points_list[b][n][1]: points_list[b][n][3] + 1, points_list[b][n][0]
].sum()
== (points_list[b][n][3] - points_list[b][n][1] + 1) * 3
)
assert (
random_w_rectangle[
- b, :, points_list[b][n][1] : points_list[b][n][3] + 1, points_list[b][n][2]
+ b, :, points_list[b][n][1]: points_list[b][n][3] + 1, points_list[b][n][2]
].sum()
== (points_list[b][n][3] - points_list[b][n][1] + 1) * 3
)
assert (
random_w_rectangle[
- b, :, points_list[b][n][1], points_list[b][n][0] : points_list[b][n][2] + 1
+ b, :, points_list[b][n][1], points_list[b][n][0]: points_list[b][n][2] + 1
].sum()
== (points_list[b][n][2] - points_list[b][n][0] + 1) * 3
)
assert (
random_w_rectangle[
- b, :, points_list[b][n][1], points_list[b][n][0] : points_list[b][n][2] + 1
+ b, :, points_list[b][n][1], points_list[b][n][0]: points_list[b][n][2] + 1
].sum()
== (points_list[b][n][2] - points_list[b][n][0] + 1) * 3
)