π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(image): accept a 0-d color in draw_point2d, draw_rectangle and draw_convex_polygon (#4910)
Mohammad Hijjawie43788dbcd5f
diff --git a/changelog.d/4910.fixed.md b/changelog.d/4910.fixed.mdnew file mode 100644index 000000000..b9b1502fc--- /dev/null+++ b/changelog.d/4910.fixed.md@@ -0,0 +1 @@+`draw_point2d`, `draw_rectangle` and `draw_convex_polygon` now accept a 0-d color such as `torch.tensor(9.0)`, like `draw_line`, instead of raising `IndexError` or `ValueError`.diff --git a/kornia/image/draw.py b/kornia/image/draw.pyindex a43db573a..1aa07530c 100644--- a/kornia/image/draw.py+++ b/kornia/image/draw.py@@ -34,12 +34,16 @@ def draw_point2d(image: Tensor, points: Tensor, color: Tensor) -> Tensor:points: the [x, y] points to be drawn on the image with shape :math`(N, 2)`, a singlepoint with shape :math`(2,)`, or an empty tensor with shape :math`(0, 2)`.color: the color of the pixel with :math`(C)` where :math`C` is the number of channels of the image.+ A 0-d scalar is accepted when the image has a single channel or is :math`(H,W)`.Return:The image with points set to the color. This operation modifies image inplace but alsoreturns the drawn tensor for convenience. An empty point set leaves the image unchanged."""+ # A 0-d scalar has no channel dimension for the check below to read; treat it as one channel, as draw_line does.+ if color.ndim == 0:+ color = color.unsqueeze(0)KORNIA_CHECK((len(image.shape) == 2 and len(color.shape) == 1) or (image.shape[0] == color.shape[0]),"Color dim must match the channel dims of the provided image",@@ -191,7 +195,7 @@ def draw_rectangle(rectangle: represents number of rectangles to draw in BxNx4N 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: a size 1, size 3, BxNx1, or BxNx3 tensor.+ color: a 0-d, size 1, size 3, BxNx1, or BxNx3 tensor.If C is 3, and color is 1 channel it will be broadcasted.fill: is a flag used to fill the boxes with color if True.@@ -225,7 +229,7 @@ def draw_rectangle(if fill is None:fill = False- if len(color.shape) == 1:+ if len(color.shape) <= 1:color = color.expand(batch, num_rectangle, c)b, n, color_channels = color.shape@@ -331,7 +335,7 @@ def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], cpolygons: represents polygons as points, either BxNx2 or List of variable length polygons.N is the number of points.2 is (x, y).- colors: a B x 3 tensor or 3 tensor with color to fill in.+ colors: a B x 3 tensor, 3 tensor, or 0-d scalar with color to fill in.Returns:This operation modifies image inplace but also returns the drawn tensor for@@ -354,7 +358,7 @@ def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], cif isinstance(polygons, List):polygons = _batch_polygons(polygons)b_p, _, xy, device_p, dtype_p = *polygons.shape, polygons.device, polygons.dtype- if len(colors.shape) == 1:+ if len(colors.shape) <= 1:colors = colors.expand(b_i, c_i)b_c, _, device_c = *colors.shape, colors.deviceKORNIA_CHECK(xy == 2, "Polygon vertices must be xy, i.e. 2-dimensional")diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.pyindex 9940131de..3d4731ca6 100644--- a/testing/half_precision_eager_rng.py+++ b/testing/half_precision_eager_rng.py@@ -199,7 +199,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(),*_audited("tests/image/test_draw.py",- 354,+ 366,"torch.rand",4,("tests/image/test_draw.py::TestDrawLine::test_point_size",),diff --git a/tests/image/test_draw.py b/tests/image/test_draw.pyindex 33cbf51be..0c601d106 100644--- a/tests/image/test_draw.py+++ b/tests/image/test_draw.py@@ -138,6 +138,18 @@ class TestDrawPoint(BaseTester):with pytest.raises(BaseError, match=match):draw_point2d(img, points, color)+ @pytest.mark.parametrize("shape", [(1, 4, 4), (4, 4)])+ def test_draw_point2d_accepts_0d_scalar_color(self, shape, dtype, device):+ """A 0-d color used to IndexError reading its channel dimension, as draw_line did before."""+ img = torch.zeros(shape, dtype=dtype, device=device)+ out = draw_point2d(img, torch.tensor([[1, 1]], device=device), torch.tensor(9, dtype=dtype, device=device))+ assert out[..., 1, 1].flatten().tolist() == [9.0]++ def test_draw_point2d_0d_color_on_multichannel_image_fails_the_channel_check(self, dtype, device):+ img = torch.zeros(3, 4, 4, dtype=dtype, device=device)+ with pytest.raises(BaseError, match="Color dim must match"):+ draw_point2d(img, torch.tensor([[1, 1]], device=device), torch.tensor(9, dtype=dtype, device=device))+class TestDrawLine(BaseTester):def test_draw_line_vertical(self, dtype, device):@@ -564,6 +576,25 @@ class TestDrawRectangle(BaseTester):<= 0.0001)+ @pytest.mark.parametrize("fill", [False, True])+ def test_0d_scalar_color_matches_one_channel_color(self, fill, dtype, device):+ """A 0-d color used to fail unpacking (b, n, c); it now draws like a size-1 color."""+ rect = torch.tensor([[[1, 1, 3, 3]]], device=device)+ out = draw_rectangle(+ torch.zeros(1, 1, 5, 5, dtype=dtype, device=device),+ rect,+ torch.tensor(9.0, dtype=dtype, device=device),+ fill=fill,+ )+ expected = draw_rectangle(+ torch.zeros(1, 1, 5, 5, dtype=dtype, device=device),+ rect,+ torch.tensor([9.0], dtype=dtype, device=device),+ fill=fill,+ )+ self.assert_close(out, expected)+ assert out.count_nonzero() > 0+class TestFillConvexPolygon(BaseTester):def test_circle(self, device, dtype):@@ -678,3 +709,12 @@ class TestFillConvexPolygon(BaseTester):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)++ 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)+ im = torch.zeros(1, 1, 5, 5, device=device, dtype=dtype)+ out = draw_convex_polygon(im.clone(), square, torch.tensor(9.0, device=device, dtype=dtype))+ expected = draw_convex_polygon(im.clone(), square, torch.tensor([9.0], device=device, dtype=dtype))+ self.assert_close(out, expected)+ assert out.count_nonzero() > 0