π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Keep list padding empty in box masks (#4390)
SHILIN KONGc1500866e910
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex debbdbe02..3ead07170 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -369,6 +369,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `Boxes.to_mask` leaves list-padding channels empty, including after coordinate transforms,+ instead of treating padding entries as real boxes. (#4390)* Fixed fixture teardown between files when running half-precision tests with`--isolate-half-precision`, including reporting parent fixture finalizer errors. (#4388)* Corrected the matrix-shape checks shared by `PinholeCamera` and `PinholeCamerasList`, thediff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex 441884d5e..055b147db 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -790,16 +790,14 @@ class Boxes:rounded to the nearest integer, and filled over the half-open ranges ``[xmin, xmax)`` and``[ymin, ymax)``, so a box entirely outside the image fills nothing and a fractional box can fill adifferent area than :func:`~kornia.geometry.bbox.bbox_to_mask` gives for the same vertices. A- list-backed object also fills a mask channel for each padding entry, whose zero row exports as a- one-pixel box at the origin. The loop taken on CPU and MPS and the vectorized path taken on CUDA and- under graph capture produce the same mask. A box tensor that requires grad is rejected with- ``RuntimeError``.+ list-backed object keeps an empty mask channel for each padding entry. The loop taken on CPU and+ MPS and the vectorized path taken on CUDA and under graph capture produce the same mask. A box tensor+ that requires grad is rejected with ``RuntimeError``... warning::The argument-order split with :func:`~kornia.geometry.bbox.bbox_to_mask` is tracked in`#4014 <https://github.com/kornia/kornia/issues/4014>`_ and the rounding split in- `#4015 <https://github.com/kornia/kornia/issues/4015>`_. The padding-entry pixel is tracked in- `#4252 <https://github.com/kornia/kornia/issues/4252>`_.+ `#4015 <https://github.com/kornia/kornia/issues/4015>`_.Args:height: height of the masked image/images.@@ -836,6 +834,15 @@ class Boxes:dtype = self.dtypedevice = self.device+ # Boxes coordinates can be outside the image size after transforms. Clamp values to the image size.+ clipped_boxes_xyxy = cast(torch.Tensor, self.to_tensor("xyxy", as_padded_sequence=True))+ clipped_boxes_xyxy[..., ::2].clamp_(0, width)+ clipped_boxes_xyxy[..., 1::2].clamp_(0, height)+ if self._N is not None:+ # Padding is not a box, even when its coordinates have been changed by a transform.+ for i, n in enumerate(self._N):+ clipped_boxes_xyxy[i, clipped_boxes_xyxy.shape[1] - n :] = 0+# -----------------# CPU Hotpath (loop)# -----------------@@ -848,11 +855,6 @@ class Boxes:else: # (N, 4, 2)mask = torch.zeros((self._data.shape[0], height, width), dtype=self.dtype, device=self.device)- # Boxes coordinates can be outside the image size after transforms. Clamp values to the image size- clipped_boxes_xyxy = cast(torch.Tensor, self.to_tensor("xyxy", as_padded_sequence=True))- clipped_boxes_xyxy[..., ::2].clamp_(0, width)- clipped_boxes_xyxy[..., 1::2].clamp_(0, height)-# Reshape mask to (BxN, H, W) and boxes to (BxN, 4) to iterate over all of them.# Cast boxes coordinates to be integer to use them as indexes. Use round to handle decimal values.for mask_channel, box_xyxy in zip(@@ -872,10 +874,6 @@ class Boxes:else:out_shape = (self.shape[0], height, width)- clipped_boxes_xyxy = cast(torch.Tensor, self.to_tensor("xyxy", as_padded_sequence=True))- clipped_boxes_xyxy[..., ::2].clamp_(0, width)- clipped_boxes_xyxy[..., 1::2].clamp_(0, height)-xyxy = clipped_boxes_xyxy.view(-1, 4).round().long()x1, y1, x2, y2 = xyxy[:, 0], xyxy[:, 1], xyxy[:, 2], xyxy[:, 3]diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.pyindex ba865aac1..474361104 100644--- a/tests/geometry/test_boxes.py+++ b/tests/geometry/test_boxes.py@@ -882,18 +882,26 @@ class TestBoxes2D(BaseTester):with pytest.raises(RuntimeError, match="differentiable"):Boxes(boxes.clone().requires_grad_()).to_mask(5, 6)- def test_wart_to_mask_fills_the_origin_pixel_for_list_padding_rows_4252(self, device, dtype):- # Wart pin for kornia#4252: a list-backed object exports its zero padding rows as the exclusive xyxy box- # [0, 0, 1, 1] (see the padding note on the class), so to_mask marks pixel (0, 0) in the- # mask channel of every padding entry instead of leaving it empty.+ @pytest.mark.parametrize("export_path", [False, True])+ @pytest.mark.parametrize("offset", [0, 2])+ def test_convention_to_mask_leaves_list_padding_empty_4252(self, export_path, offset, device, dtype, monkeypatch):+ # Padding must stay empty even after transforms, while a real point box still covers one pixel.+ point = torch.zeros(1, 4, 2, device=device, dtype=dtype)box = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)- boxes = Boxes([box, torch.cat([box, box + 2.0])])- mask = boxes.to_mask(5, 5)- assert mask.shape == (2, 2, 5, 5)- expected_padding = torch.zeros(5, 5, device=device, dtype=dtype)- expected_padding[0, 0] = 1.0- self.assert_close(mask[0, 1], expected_padding, atol=0.0, rtol=0.0)- self.assert_close(mask[0, 0], mask[1, 0], atol=0.0, rtol=0.0)+ boxes = Boxes([point[:0], point, torch.cat([point, box])])+ if offset:+ transform = torch.eye(3, device=device, dtype=dtype)+ transform[:2, 2] = offset+ boxes = boxes.transform_boxes(transform.expand(3, -1, -1))+ original_data = boxes.data.clone()+ if export_path:+ monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)+ mask = boxes.to_mask(6, 6)+ expected = torch.zeros(3, 2, 6, 6, device=device, dtype=dtype)+ expected[1:, 0, offset, offset] = 1.0+ expected[2, 1, offset + 1 : offset + 3, offset + 1 : offset + 3] = 1.0+ self.assert_close(mask, expected, atol=0.0, rtol=0.0)+ self.assert_close(boxes.data, original_data, atol=0.0, rtol=0.0)@pytest.mark.parametrize("case", ["fractional", "outside", "negative", "rotated", "batched"])def test_convention_to_mask_export_path_matches_loop_path(self, case, device, dtype, monkeypatch):