π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix draw_convex_polygon crash on an empty polygon batch (#4895)
Mohammad Hijjawi79e24d133e8f
diff --git a/changelog.d/4895.fixed.md b/changelog.d/4895.fixed.mdnew file mode 100644index 000000000..e1faa9a49--- /dev/null+++ b/changelog.d/4895.fixed.md@@ -0,0 +1 @@+`draw_convex_polygon` returns the input image unchanged for an empty `(B, 0, 2)` polygon batch instead of raising `IndexError` when closing the polygon loop.diff --git a/kornia/image/draw.py b/kornia/image/draw.pyindex cd7a4c2c0..a43db573a 100644--- a/kornia/image/draw.py+++ b/kornia/image/draw.py@@ -360,6 +360,9 @@ def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], cKORNIA_CHECK(xy == 2, "Polygon vertices must be xy, i.e. 2-dimensional")KORNIA_CHECK(b_i == b_p == b_c, "Image, polygon, and color must have same batch dimension")KORNIA_CHECK(device == device_p == device_c, "Image, polygon, and color must have same device")+ # A polygon without vertices has nothing to fill, and closing its loop below needs a vertex.+ if polygons.shape[1] == 0:+ return imagesx_left, x_right = _get_convex_edges(polygons, h_i, w_i)ws = torch.arange(w_i, device=device, dtype=dtype_p)[None, None, :]diff --git a/tests/image/test_draw.py b/tests/image/test_draw.pyindex d0696fde0..33cbf51be 100644--- a/tests/image/test_draw.py+++ b/tests/image/test_draw.py@@ -662,3 +662,19 @@ class TestFillConvexPolygon(BaseTester):rect = torch.cat((pts[..., 0, :], pts[..., 2, :]), dim=-1)[:, None]rect_im = draw_rectangle(im.clone(), rect, color[:, None], fill=True)self.assert_close(rect_im, poly_im)++ def test_empty_polygon_leaves_image_unchanged(self, device, dtype):+ """An empty (B, 0, 2) polygon batch must not IndexError on loop close."""+ im = torch.rand(1, 3, 12, 16, device=device, dtype=dtype)+ pts = torch.zeros(1, 0, 2, device=device, dtype=dtype)+ color = torch.tensor([[0.5, 0.5, 0.5]], device=device, dtype=dtype)+ out = draw_convex_polygon(im.clone(), pts, color)+ self.assert_close(out, im)++ def test_empty_polygon_is_still_validated(self, device, dtype):+ im = torch.rand(1, 3, 12, 16, device=device, dtype=dtype)+ color = torch.tensor([[0.5, 0.5, 0.5]], device=device, dtype=dtype)+ with pytest.raises(BaseError, match="same batch dimension"):+ draw_convex_polygon(im, torch.zeros(2, 0, 2, device=device, dtype=dtype), color)+ with pytest.raises(BaseError, match="xy"):+ draw_convex_polygon(im, torch.zeros(1, 0, 3, device=device, dtype=dtype), color)