Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(image): draw degenerate polygons in draw_convex_polygon (#4909)

Mohammad Hijjawi5c6df73f8dde
diff --git a/changelog.d/4909.fixed.md b/changelog.d/4909.fixed.md
new file mode 100644
index 000000000..a863106af
--- /dev/null
+++ b/changelog.d/4909.fixed.md
@@ -0,0 +1 @@
+`draw_convex_polygon` now draws a one-vertex polygon as that point, leaves the image of an empty polygon in a list unchanged, and accepts an empty list with a zero-batch image, instead of raising PyTorch errors. The edge slope no longer divides by `dy + 1e-12`: in float16 that epsilon underflowed and left the scanline through a repeated vertex (including the padding of a shorter polygon in a list) unfilled, and in float64 it dropped pixels whose centre lies exactly on a sloped edge.
diff --git a/kornia/image/draw.py b/kornia/image/draw.py
index 1aa07530c..4bc0fb0c1 100644
--- a/kornia/image/draw.py
+++ b/kornia/image/draw.py
@@ -278,6 +278,11 @@ def _get_convex_edges(polygon: Tensor, h: int, w: int) -> Tuple[Tensor, Tensor]:
"""
dtype = polygon.dtype
+ # A single vertex is its own first and last point, so the loop below would leave no edge;
+ # draw it as a zero-length edge, like a two-vertex polygon whose vertices coincide.
+ if polygon.shape[-2] == 1:
+ polygon = torch.cat((polygon, polygon), dim=-2)
+
# Check if polygons are in loop closed format, if not -> make it so
if not torch.allclose(polygon[..., -1, :], polygon[..., 0, :]):
polygon = torch.cat((polygon, polygon[..., :1, :]), dim=-2) # (B, N+1, 2)
@@ -288,7 +293,11 @@ def _get_convex_edges(polygon: Tensor, h: int, w: int) -> Tuple[Tensor, Tensor]:
# Create scanlines, edge dx/dy, and produce x values
ys = torch.arange(h, device=polygon.device, dtype=dtype)
- dx = ((x_end - x_start) / (y_end - y_start + 1e-12)).clamp(-w, w)
+ # A horizontal or zero-length edge is active only on its own scanline, where xs is x_start for any finite dx,
+ # so its dx is set to 0. An epsilon added to dy instead underflows in float16 (0 / 0 blanks the scanline), and
+ # in float64 it shifts a sloped edge enough to drop a pixel centre lying exactly on it.
+ dy = y_end - y_start
+ dx = torch.where(dy == 0, 0.0, (x_end - x_start) / dy).clamp(-w, w)
xs = (ys[..., :, None] - y_start[..., None, :]) * dx[..., None, :] + x_start[..., None, :]
# Only count edge in their active regions (i.e between the vertices)
@@ -323,6 +332,9 @@ def _batch_polygons(polygons: List[Tensor]) -> Tensor:
B, N = len(polygons), len(max(polygons, key=len))
batched_polygons = torch.zeros(B, N, 2, dtype=polygons[0].dtype, device=polygons[0].device)
for b, p in enumerate(polygons):
+ if len(p) == 0:
+ # No last vertex to repeat; the row stays zero and the caller must not fill it.
+ continue
batched_polygons[b] = torch.cat((p, p[-1:].expand(N - len(p), 2))) if len(p) < N else p
return batched_polygons
@@ -355,8 +367,11 @@ def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], c
# TODO: implement optional linetypes for smooth edges
KORNIA_CHECK_SHAPE(images, ["B", "C", "H", "W"])
b_i, c_i, h_i, w_i, device = *images.shape, images.device
+ empty_polygons = None
if isinstance(polygons, List):
- polygons = _batch_polygons(polygons)
+ empty_polygons = torch.tensor([len(p) == 0 for p in polygons], dtype=torch.bool, device=device)
+ # `[]` has no polygon to take a dtype or device from; an empty (0, 0, 2) batch returns below.
+ polygons = _batch_polygons(polygons) if polygons else images.new_zeros(0, 0, 2)
b_p, _, xy, device_p, dtype_p = *polygons.shape, polygons.device, polygons.dtype
if len(colors.shape) <= 1:
colors = colors.expand(b_i, c_i)
@@ -371,5 +386,7 @@ def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], c
x_left, x_right = _get_convex_edges(polygons, h_i, w_i)
ws = torch.arange(w_i, device=device, dtype=dtype_p)[None, None, :]
fill_region = (ws >= x_left[..., :, None]) & (ws <= x_right[..., :, None])
+ if empty_polygons is not None:
+ fill_region &= ~empty_polygons[:, None, None]
images.mul_(~fill_region[:, None]).add_(fill_region[:, None] * colors[..., None, None])
return images
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index de4381667..37857dc28 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -427,8 +427,6 @@ call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWar
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_y[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_y_large[cpu-float16]
call builtins.AssertionError tests/geometry/transform/test_imgwarp3d.py::TestWarpAffine3d::test_rotate_z[cpu-float16]
-call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_batch_color_no_batch[cpu-float16]
-call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_batch_variable_size[cpu-float16]
call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_circle[cpu-float16]
call builtins.AssertionError tests/image/test_draw.py::TestFillConvexPolygon::test_ellipse[cpu-float16]
call builtins.AssertionError tests/integration/test_conversions.py::TestAngleOfRotations::test_axis_angle[cpu-float16--45.0-x]
diff --git a/tests/image/test_draw.py b/tests/image/test_draw.py
index 0c601d106..eebdccdc9 100644
--- a/tests/image/test_draw.py
+++ b/tests/image/test_draw.py
@@ -710,6 +710,41 @@ class TestFillConvexPolygon(BaseTester):
with pytest.raises(BaseError, match="xy"):
draw_convex_polygon(im, torch.zeros(1, 0, 3, device=device, dtype=dtype), color)
+ def test_single_vertex_fills_its_pixel(self, device, dtype):
+ """A one-vertex polygon draws that point, like a zero-length two-vertex polygon."""
+ im = torch.rand(1, 3, 12, 16, device=device, dtype=dtype)
+ color = torch.tensor([[0.5, 0.5, 0.5]], device=device, dtype=dtype)
+ vertex = torch.tensor([[[4.0, 4.0]]], device=device, dtype=dtype)
+ out = draw_convex_polygon(im.clone(), vertex, color)
+ expected = draw_convex_polygon(im.clone(), vertex.expand(1, 2, 2), color)
+ self.assert_close(out, expected)
+ self.assert_close(out[..., 4, 4], color)
+
+ def test_empty_polygon_in_a_list_leaves_its_image_unchanged(self, device, dtype):
+ """An empty polygon has no vertex to pad with; the rest of the batch is still drawn."""
+ im = torch.rand(2, 3, 12, 16, device=device, dtype=dtype)
+ square = torch.tensor([[4, 4], [12, 4], [12, 8], [4, 8]], device=device, dtype=dtype)
+ color = torch.tensor([[0.5, 0.5, 0.5], [0.5, 0.5, 0.75]], device=device, dtype=dtype)
+ out = draw_convex_polygon(im.clone(), [torch.zeros(0, 2, device=device, dtype=dtype), square], color)
+ self.assert_close(out[:1], im[:1])
+ self.assert_close(out[1:], draw_convex_polygon(im[1:].clone(), square[None], color[1:]))
+
+ def test_empty_list_with_empty_batch(self, device, dtype):
+ im = torch.rand(0, 3, 12, 16, device=device, dtype=dtype)
+ color = torch.zeros(0, 3, device=device, dtype=dtype)
+ out = draw_convex_polygon(im.clone(), [], color)
+ assert out.shape == im.shape
+
+ def test_sloped_edge_fills_the_pixel_it_passes_through(self, device, dtype):
+ """The right edge of this triangle crosses x = 4 + 2 * (y - 4) exactly, and that pixel is inside."""
+ tri = torch.tensor([[[4.0, 4.0], [12.0, 8.0], [4.0, 8.0]]], device=device, dtype=dtype)
+ im = torch.zeros(1, 1, 12, 16, device=device, dtype=dtype)
+ out = draw_convex_polygon(im, tri, torch.ones(1, 1, device=device, dtype=dtype))
+ ys = torch.arange(12, device=device)[:, None]
+ xs = torch.arange(16, device=device)[None, :]
+ expected = (ys >= 4) & (ys <= 8) & (xs >= 4) & (xs <= 4 + 2 * (ys - 4))
+ assert out[0, 0].eq(expected).all()
+
def test_0d_scalar_color_matches_one_channel_color(self, device, dtype):
"""A 0-d color used to fail unpacking (b, c); it now fills like a size-1 color."""
square = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)