Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(image): add rectangle outline width (#5093)

NIKHILa37ddc0ee9a3
diff --git a/changelog.d/5093.added.md b/changelog.d/5093.added.md
new file mode 100644
index 000000000..aa69fdd54
--- /dev/null
+++ b/changelog.d/5093.added.md
@@ -0,0 +1,2 @@
+`kornia.image.draw_rectangle` now accepts `line_width` to draw outlines thicker than one pixel. The outline grows
+inward from each edge, so it stays inside the rectangle, and the part of it outside the image is not drawn.
diff --git a/kornia/image/draw.py b/kornia/image/draw.py
index cfe871cc7..5fc7e2710 100644
--- a/kornia/image/draw.py
+++ b/kornia/image/draw.py
@@ -257,14 +257,20 @@ def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: to
def draw_rectangle(
- image: torch.Tensor, rectangle: torch.Tensor, color: Optional[torch.Tensor] = None, fill: Optional[bool] = None
+ image: torch.Tensor,
+ rectangle: torch.Tensor,
+ color: Optional[torch.Tensor] = None,
+ fill: Optional[bool] = None,
+ line_width: int = 1,
) -> torch.Tensor:
r"""Draw N rectangles on a batch of image tensors.
Convention:
- A rectangle is ``[x1, y1, x2, y2]``, its two corners in either order and both included, with the
- coordinates rounded as in :func:`~kornia.image.draw_line`. A side that lies outside the image is not drawn
- and a fill is clipped to the image; neither raises.
+ coordinates rounded as in :func:`~kornia.image.draw_line`. Each side of the outline is ``line_width`` pixels
+ thick and grows inward, so the outline stays inside the rectangle; a side thicker than the rectangle covers
+ it. The outline and a fill are clipped to the image: the part of a side that lies outside the image is not
+ drawn, and neither raises.
- The corners are rounded and the vertices of :func:`~kornia.image.draw_convex_polygon` are not, so a filled
rectangle and the same polygon always agree for integer corners; for fractional ones each side can be one
row or column apart, so a polygon thinner than a pixel can fill nothing.
@@ -276,10 +282,13 @@ def draw_rectangle(
color: the colour, :math:`(C)` or :math:`(B, N, C)`, or a single value (0-d, :math:`(1)` or
:math:`(B, N, 1)`). Black by default.
fill: whether to fill the rectangles instead of drawing their outlines.
+ line_width: the thickness of each side of the outline in pixels, a positive integer. Ignored when
+ ``fill=True``.
Raises:
ShapeError: if the image is not ``(B, C, H, W)``. It is also a ``ValueError``.
ValueError: if ``rectangle`` is not ``(B, N, 4)``, or its batch size differs from the image's.
+ ValueError: if ``line_width`` is not a positive ``int``.
Returns:
This operation modifies image inplace but also returns the drawn tensor for
@@ -289,8 +298,12 @@ def draw_rectangle(
>>> img = torch.rand(2, 3, 10, 12)
>>> rect = torch.tensor([[[0, 0, 4, 4]], [[4, 4, 11, 9]]])
>>> out = draw_rectangle(img, rect)
+ >>> thick_out = draw_rectangle(img.clone(), rect, line_width=2)
"""
+ if not isinstance(line_width, int) or isinstance(line_width, bool) or line_width < 1:
+ raise ValueError("line_width must be a positive integer")
+
KORNIA_CHECK_SHAPE(image, ["B", "C", "H", "W"])
batch, c, h, w = image.shape
batch_rect, num_rectangle, num_points = rectangle.shape
@@ -319,7 +332,7 @@ def draw_rectangle(
color = color.expand(batch, num_rectangle, c)
# one host read for the bands of every rectangle
- bands: List[List[List[List[int]]]] = _rectangle_bands(x1, y1, x2, y2, h, w, 1, fill).tolist()
+ bands: List[List[List[List[int]]]] = _rectangle_bands(x1, y1, x2, y2, h, w, line_width, fill).tolist()
for b in range(batch):
for n in range(num_rectangle):
for band in bands[b][n]:
diff --git a/tests/image/test_draw.py b/tests/image/test_draw.py
index e0b49f95a..5796c282c 100644
--- a/tests/image/test_draw.py
+++ b/tests/image/test_draw.py
@@ -575,6 +575,101 @@ class TestDrawRectangle(BaseTester):
with pytest.raises(ShapeError):
draw_rectangle(torch.zeros(3, 6, 5, device=device), torch.tensor([[[0, 0, 2, 2]]], device=device))
+ @pytest.mark.parametrize("line_width", [1, 2, 4])
+ def test_outline_width(self, dtype, device, line_width):
+ image = torch.zeros(1, 1, 7, 9, dtype=dtype, device=device)
+ rectangle = torch.tensor([[[1, 1, 7, 5]]], device=device)
+
+ out = draw_rectangle(image, rectangle, color=torch.tensor([1.0], device=device), line_width=line_width)
+
+ expected = torch.zeros_like(image)
+ expected[:, :, 1:6, 1:8] = 1
+ if line_width == 1:
+ expected[:, :, 2:5, 2:7] = 0
+ elif line_width == 2:
+ expected[:, :, 3:4, 3:6] = 0
+ assert out is image
+ self.assert_close(out, expected)
+
+ def test_outline_width_clips_and_preserves_interior(self, dtype, device):
+ image = torch.zeros(1, 1, 6, 6, dtype=dtype, device=device)
+ rectangle = torch.tensor([[[-2, -2, 4, 4]]], device=device)
+
+ draw_rectangle(image, rectangle, color=torch.tensor([1.0], device=device), line_width=2)
+
+ # the top (rows -2..-1) and left (columns -2..-1) bands lie outside the image and are not drawn;
+ # the bottom and right bands keep their parts inside it
+ expected = torch.zeros_like(image)
+ expected[:, :, 3:5, :5] = 1
+ expected[:, :, :5, 3:5] = 1
+ self.assert_close(image, expected)
+
+ def test_outline_width_reversed_and_fractional_corners(self, dtype, device):
+ expected = draw_rectangle(
+ torch.zeros(1, 1, 8, 10, dtype=dtype, device=device),
+ torch.tensor([[[1, 1, 8, 6]]], device=device),
+ color=torch.tensor([1.0], device=device),
+ line_width=3,
+ )
+ for corners in ([8, 6, 1, 1], [1, 6, 8, 1], [8.4, 0.6, 0.5, 5.6]):
+ out = draw_rectangle(
+ torch.zeros(1, 1, 8, 10, dtype=dtype, device=device),
+ torch.tensor([[corners]], device=device),
+ color=torch.tensor([1.0], device=device),
+ line_width=3,
+ )
+ self.assert_close(out, expected)
+
+ def test_outline_width_wider_than_box_stays_inside(self, dtype, device):
+ image = torch.zeros(1, 1, 8, 10, dtype=dtype, device=device)
+ rectangle = torch.tensor([[[4, 3, 6, 4]]], device=device)
+
+ draw_rectangle(image, rectangle, color=torch.tensor([1.0], device=device), line_width=4)
+
+ expected = torch.zeros_like(image)
+ expected[:, :, 3:5, 4:7] = 1
+ self.assert_close(image, expected)
+
+ def test_outline_width_keeps_batch_colors_separate(self, dtype, device):
+ image = torch.zeros(2, 3, 6, 6, dtype=dtype, device=device)
+ rectangle = torch.tensor([[[1, 1, 4, 4]], [[1, 1, 4, 4]]], device=device)
+ color = torch.tensor([[[1.0, 0.0, 0.0]], [[0.0, 1.0, 0.0]]], dtype=dtype, device=device)
+
+ draw_rectangle(image, rectangle, color=color, line_width=2)
+
+ assert torch.all(image[0, 0, 1:5, 1:5] == 1)
+ assert torch.all(image[1, 1, 1:5, 1:5] == 1)
+ assert torch.count_nonzero(image[0, 1:]) == 0
+ assert torch.count_nonzero(image[1, ::2]) == 0
+
+ def test_fill_ignores_outline_width(self, dtype, device):
+ image = torch.zeros(1, 1, 6, 6, dtype=dtype, device=device)
+ rectangle = torch.tensor([[[1, 1, 4, 4]]], device=device)
+
+ draw_rectangle(image, rectangle, color=torch.tensor([1.0], device=device), fill=True, line_width=2)
+
+ expected = torch.zeros_like(image)
+ expected[:, :, 1:5, 1:5] = 1
+ self.assert_close(image, expected)
+
+ def test_outline_width_torchscript(self, dtype, device):
+ image = torch.zeros(1, 1, 5, 5, dtype=dtype, device=device)
+ rectangle = torch.tensor([[[0, 0, 4, 4]]], device=device)
+
+ scripted = torch.jit.script(draw_rectangle)
+ out = scripted(image, rectangle, color=torch.tensor([1.0], device=device), line_width=2)
+
+ expected = torch.ones_like(image)
+ expected[:, :, 2, 2] = 0
+ self.assert_close(out, expected)
+
+ @pytest.mark.parametrize("line_width", [0, -1, 1.5, True])
+ def test_outline_width_must_be_positive_integer(self, line_width, device):
+ image = torch.zeros(1, 1, 5, 5, device=device)
+ rectangle = torch.tensor([[[1, 1, 3, 3]]], device=device)
+ with pytest.raises(ValueError, match="line_width must be a positive integer"):
+ draw_rectangle(image, rectangle, line_width=line_width)
+
@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):
@@ -811,15 +906,15 @@ class TestDrawRectangle(BaseTester):
not torch_version_ge(2, 14),
reason="slices with data-dependent bounds export from torch 2.14 (2.9.1 fails to export, 2.6 bakes the input)",
)
- @pytest.mark.parametrize("fill", [False, True])
- def test_onnx_export_draws_the_rectangles_given_at_run_time(self, fill):
+ @pytest.mark.parametrize(("fill", "line_width"), [(False, 1), (True, 1), (False, 3)])
+ def test_onnx_export_draws_the_rectangles_given_at_run_time(self, fill, line_width):
pytest.importorskip("onnx")
pytest.importorskip("onnxscript")
ort = pytest.importorskip("onnxruntime")
class Draw(torch.nn.Module):
def forward(self, image, rectangle, color):
- return draw_rectangle(image.clone(), rectangle, color, fill=fill)
+ return draw_rectangle(image.clone(), rectangle, color, fill=fill, line_width=line_width)
model = Draw()
image = torch.zeros(1, 3, 6, 9)