Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Simple draw rectangle implementation for feat #607 https://github.com… (#737)

DoubleMathewf2987d09d489
diff --git a/docs/source/utils.rst b/docs/source/utils.rst
index 49e258f54..cd857d6e5 100644
--- a/docs/source/utils.rst
+++ b/docs/source/utils.rst
@@ -8,6 +8,7 @@ Image
.. autofunction:: tensor_to_image
.. autofunction:: image_to_tensor
+.. autofunction:: draw_rectangle
Grid
----
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index b05d4a1fd..dbc777cc4 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -2,6 +2,7 @@ from .one_hot import one_hot
from .grid import create_meshgrid, create_meshgrid3d
from .image import tensor_to_image, image_to_tensor
from .pointcloud_io import save_pointcloud_ply, load_pointcloud_ply
+from .draw import draw_rectangle
from .helpers import _extract_device_dtype
from kornia.utils.metrics import *
@@ -14,5 +15,6 @@ __all__ = [
"image_to_tensor",
"save_pointcloud_ply",
"load_pointcloud_ply",
+ "draw_rectangle",
"_extract_device_dtype",
]
diff --git a/kornia/utils/draw.py b/kornia/utils/draw.py
new file mode 100644
index 000000000..1c7fa8002
--- /dev/null
+++ b/kornia/utils/draw.py
@@ -0,0 +1,73 @@
+from typing import Optional, Union
+import torch
+
+
+def draw_rectangle(
+ image: torch.Tensor,
+ rectangle: torch.Tensor,
+ color: Optional[torch.Tensor] = None,
+ fill: Optional[bool] = None,
+ width: int = 1
+) -> torch.Tensor:
+ """Draws N rectangles on a batch of image tensors
+ Args:
+ image (torch.Tensor): is tensor of BxCxHxW.
+ rectangle (torch.Tensor): represents number of rectangles to draw in BxNx4
+ N is the number of boxes to draw per batch index[x1, y1, x2, y2]
+ 4 is in (top_left.x, top_left.y, bot_right.x, bot_right.y).
+ color (torch.Tensor, optional): a size 1, size 3, BxNx1, or BxNx3 tensor.
+ If C is 3, and color is 1 channel it will be broadcasted Default: None (black).
+ fill (bool, optional): is a flag used to fill the boxes with color if True. Default: False.
+ width (int): The line width. Default: 1. (Not implemented yet).
+ Returns:
+ torch.Tensor: This operation modifies image inplace but also returns
+ the drawn tensor for convenience with same shape the of the input BxCxHxW.
+
+ Example:
+ >>> img = torch.rand(2, 3, 10, 12)
+ >>> rect = torch.tensor([[[0, 0, 4, 4]], [[4, 4, 10, 10]]])
+ >>> out = draw_rectangle(img, rect)
+ """
+
+ batch, c, h, w = image.shape
+ batch_rect, num_rectangle, num_points = rectangle.shape
+ assert batch == batch_rect, "Image batch and rectangle batch must be equal"
+ assert num_points == 4, "Number of points in rectangle must be 4"
+
+ # clone rectangle, in case it's been expanded assignment from clipping causes problems
+ rectangle = rectangle.long().clone()
+
+ # clip rectangle to hxw bounds
+ rectangle[:, :, 1::2] = torch.clamp(rectangle[:, :, 1::2], 0, h - 1)
+ rectangle[:, :, ::2] = torch.clamp(rectangle[:, :, ::2], 0, w - 1)
+
+ if color is None:
+ color = torch.tensor([0.0] * c).expand(batch, num_rectangle, c)
+
+ if fill is None:
+ fill = False
+
+ if len(color.shape) == 1:
+ color = color.expand(batch, num_rectangle, c)
+
+ b, n, color_channels = color.shape
+
+ if color_channels == 1 and c == 3:
+ color = color.expand(batch, num_rectangle, c)
+
+ for b in range(batch):
+ for n in range(num_rectangle):
+ if fill:
+ image[b, :, int(rectangle[b, n, 1]):int(rectangle[b, n, 3] + 1),
+ int(rectangle[b, n, 0]):int(rectangle[b, n, 2] + 1)] = color[b, n, :, None, None]
+ else:
+ image[b, :, int(rectangle[b, n, 1]):int(rectangle[b, n, 3] + 1),
+ rectangle[b, n, 0]] = color[b, n, :, None]
+ image[b, :, int(rectangle[b, n, 1]):int(rectangle[b, n, 3] + 1),
+ rectangle[b, n, 2]] = color[b, n, :, None]
+ image[b, :, rectangle[b, n, 1], int(rectangle[b, n, 0]):int(
+ rectangle[b, n, 2] + 1)] = color[b, n, :, None]
+ image[b, :, rectangle[b, n, 3], int(rectangle[b, n, 0]):int(
+ rectangle[b, n, 2] + 1)] = color[b, n, :, None]
+
+ return image
diff --git a/test/utils/test_draw.py b/test/utils/test_draw.py
new file mode 100644
index 000000000..475c06ae0
--- /dev/null
+++ b/test/utils/test_draw.py
@@ -0,0 +1,116 @@
+import pytest
+
+import torch
+import kornia.testing as utils
+from kornia.utils import draw_rectangle
+
+
+class TestDrawRectangle:
+ @pytest.mark.parametrize('batch', (4, 17))
+ @pytest.mark.parametrize('color', (torch.Tensor([1.0]), torch.Tensor([0.5])))
+ def test_smoke(self, device, batch, color):
+ black_image = torch.zeros(batch, 1, 3, 3, device=device) # 1 channel 3x3 black_image
+ points = torch.tensor([1., 1., 1., 1.]).to(device).expand(batch, 1, 4) # single pixel rectangle
+
+ draw_rectangle(black_image, points, color=color)
+
+ target = torch.zeros(batch, 1, 3, 3, device=device)
+ target[:, :, 1, 1] = color
+
+ assert torch.all(black_image == target)
+
+ @pytest.mark.parametrize('batch', (8, 11))
+ @pytest.mark.parametrize('fill', (True, False))
+ @pytest.mark.parametrize('height', (12, 106, 298))
+ @pytest.mark.parametrize('width', (7, 123, 537))
+ def test_fill_and_edges(self, device, batch, fill, height, width):
+ black_image = torch.zeros(batch, 3, height, width, device=device)
+ # we should pass height - 1 and width - 1 but rectangle should clip correctly
+ points = torch.tensor([0, 0, width, height]).to(device).expand(batch, 1, 4)
+
+ image_w_rectangle = draw_rectangle(black_image, points, color=torch.tensor([1.0]), fill=fill)
+
+ assert image_w_rectangle is black_image
+ if fill:
+ assert image_w_rectangle.sum() == batch * 3 * height * width
+ else:
+ # corners are double counted
+ assert image_w_rectangle.sum() == batch * 3 * (2 * height + 2 * width - 4)
+
+ @pytest.mark.parametrize('batch', (4, 6))
+ @pytest.mark.parametrize('N', (5, 12))
+ @pytest.mark.parametrize('fill', (True, False))
+ def test_n_rectangles(self, device, batch, N, fill):
+ points_list = []
+ h, w = 20, 20
+ for b in range(batch):
+ points_list.append([])
+ for n in range(N):
+ points_list[b].append([])
+ points_list[b][n].append(int(torch.randint(0, w - 1, (1,))))
+ points_list[b][n].append(int(torch.randint(0, h - 1, (1,))))
+ points_list[b][n].append(int(torch.randint(points_list[b][n][-2] + 1, w, (1,))))
+ points_list[b][n].append(int(torch.randint(points_list[b][n][-2] + 1, h, (1,))))
+
+ points = torch.tensor(points_list).to(device)
+
+ random_background = torch.rand(batch, 3, h, w, device=device)
+ random_w_rectangle = random_background.clone()
+
+ draw_rectangle(random_w_rectangle, points, color=torch.tensor([1.0, 1.0, 1.0]), fill=fill)
+
+ for b in range(batch):
+ for n in range(N):
+ if fill:
+ assert 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].sum() \
+ == (points_list[b][n][3] - points_list[b][n][1] + 1) * \
+ (points_list[b][n][2] - points_list[b][n][0] + 1) * 3
+ else:
+ assert random_w_rectangle[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]].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].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].sum() \
+ == (points_list[b][n][2] - points_list[b][n][0] + 1) * 3
+
+ @pytest.mark.parametrize('color', (torch.tensor([.5, .3, .15]), torch.tensor([.23, .33, .8])))
+ def test_color_background(self, device, color):
+ image = torch.zeros(1, 3, 40, 40, device=device)
+ image[:, 0, :, :] = color[0]
+ image[:, 1, :, :] = color[1]
+ image[:, 2, :, :] = color[2]
+ image_w_rectangle = image.clone()
+ p1 = (1, 5)
+ p2 = (30, 39)
+ points = torch.tensor([[[p1[1], p1[0], p2[1], p2[0]]]], device=device)
+
+ draw_rectangle(image_w_rectangle, points, color=torch.tensor([1.0]))
+ assert torch.abs((image_w_rectangle - image).sum() -
+ (1 - color[0]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1] + 1) - 4) -
+ (1 - color[1]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1] + 1) - 4) -
+ (1 - color[2]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1] + 1) - 4)) \
+ <= 0.0001
+
+ @pytest.mark.parametrize('color', (torch.tensor([.34, .63, .16]), torch.tensor([.29, .13, .48])))
+ def test_color_foreground(self, device, color):
+ image = torch.zeros(1, 3, 50, 40, device=device)
+ image_w_rectangle = image.clone()
+ p1 = (10, 4)
+ p2 = (11, 40)
+ points = torch.tensor([[[p1[1], p1[0], p2[1], p2[0]]]], device=device)
+
+ draw_rectangle(image_w_rectangle, points, color=color)
+
+ # corners are double counted, no plus 1 for y since p2[1] of 40 already lies outside of the image
+ assert torch.abs((image_w_rectangle - image).sum() -
+ (color[0]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1]) - 4) -
+ (color[1]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1]) - 4) -
+ (color[2]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1]) - 4)) \
+ <= 0.0001