π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): keep a singleton box axis when indexing an unbatched box with a scalar (#6484)
niukanen142b42c4f3cf9
diff --git a/changelog.d/6484.fixed.md b/changelog.d/6484.fixed.mdnew file mode 100644index 000000000..099ca31a0--- /dev/null+++ b/changelog.d/6484.fixed.md@@ -0,0 +1 @@+Selecting one box of an unbatched `Boxes` or `Boxes3D` with an integer, including a negative one, or a 0-d integer tensor returns a one-box container of shape `(1, 4, 2)` or `(1, 8, 3)`, a view of the stored tensor, and `Boxes` keeps that box's validity. It used to raise a `ValueError`, because tensor indexing dropped the box axis.diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex 4d80acd27..14116203f 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -292,6 +292,8 @@ class Boxes:update and return ``self``. :meth:`pad` and :meth:`unpad` always shift ``self``. The constructor wraps afloating-point tensor without copying it, so item assignment and the in-place updates of :meth:`pad`,:meth:`unpad`, :meth:`clamp`, :meth:`filter_boxes_by_area` and :meth:`index_put` reach the caller's tensor.+ - Integer indexing selects one image's box set for batched input, or one box with shape ``(1, 4, 2)`` for+ unbatched input. Scalar integer tensors follow the same rule... warning::The inclusive ``+1`` differs from torchvision, COCO and albumentations:@@ -363,9 +365,13 @@ class Boxes:self._valid = torch.ones(self._data.shape[:-2], device=self._data.device, dtype=torch.bool)def __getitem__(self, key: slice | int | torch.Tensor) -> Boxes:- new_box = type(self)(self._data[key], False)+ data = self._data[key]+ # an integer or 0-d integer tensor selects one box of unbatched boxes: keep the box axis+ one_box = data.ndim == 2 and not isinstance(key, tuple)+ new_box = type(self)(data.unsqueeze(0) if one_box else data, False)new_box._mode = self._mode- new_box._valid = self._valid[key]+ valid = self._valid[key]+ new_box._valid = valid.unsqueeze(0) if one_box else valid# Select padding metadata with the same key as the box batch, including boolean masks.if self._N is not None:selected = torch.as_tensor(self._N, device=self._data.device)[key]@@ -1358,6 +1364,8 @@ class Boxes3D:or ``float64`` when that is the default dtype.- :meth:`transform_boxes` returns a new object labelled ``'xyzxyz_plus'``; :meth:`transform_boxes_`rebinds the internal tensor of ``self`` and keeps the label.+ - Integer indexing selects one image's box set for batched input, or one box with shape ``(1, 8, 3)`` for+ unbatched input. Scalar integer tensors follow the same rule... warning::The inclusive ``+1`` is `#3934 <https://github.com/kornia/kornia/issues/3934>`_ and the ``'vertices'``@@ -1402,7 +1410,11 @@ class Boxes3D:self._mode = modedef __getitem__(self, key: slice | int | torch.Tensor) -> Boxes3D:- new_box = Boxes3D(self._data[key], False, mode="xyzxyz_plus")+ data = self._data[key]+ if data.ndim == 2 and not isinstance(key, tuple):+ # an integer or 0-d integer tensor selects one box of unbatched boxes: keep the box axis+ data = data.unsqueeze(0)+ new_box = Boxes3D(data, False, mode="xyzxyz_plus")new_box._mode = self._modereturn new_boxdiff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.pyindex a2a27f04c..b277523f7 100644--- a/tests/geometry/test_boxes.py+++ b/tests/geometry/test_boxes.py@@ -57,6 +57,180 @@ def _unbatched_geometry_data(device: torch.device, dtype: torch.dtype) -> torch.)+ "container,vertices,coordinates,mode", [(Boxes, 4, 2, "xyxy_plus"), (Boxes3D, 8, 3, "xyzxyz_plus")]+)+class TestBoxesIndexing(BaseTester):+ @staticmethod+ def _key(kind: str, device: torch.device) -> int | torch.Tensor:+ return {"first": 0, "last": -1, "scalar_tensor": torch.tensor(-1, device=device, dtype=torch.long)}[kind]++ @pytest.mark.parametrize("num_boxes", [1, 3])+ @pytest.mark.parametrize("key_kind", ["first", "last", "scalar_tensor"])+ @pytest.mark.parametrize("strided", [False, True])+ def test_scalar_unbatched_6478(+ self,+ container: type[Boxes] | type[Boxes3D],+ vertices: int,+ coordinates: int,+ mode: str,+ num_boxes: int,+ key_kind: str,+ strided: bool,+ device: torch.device,+ dtype: torch.dtype,+ ) -> None:+ # #6478: an integer or scalar tensor index on an unbatched container keeps a singleton box axis.+ source = torch.arange(num_boxes * 2 * coordinates, device=device, dtype=dtype).reshape(+ num_boxes, 2, coordinates+ )+ boxes = container.from_tensor(source.reshape(num_boxes, -1).clone(), mode=mode)+ if strided:+ data = boxes.data.transpose(1, 2).contiguous().transpose(1, 2)+ boxes = container(data, mode=mode)+ key = self._key(key_kind, device)++ selected = boxes[key]++ assert type(selected) is container+ assert selected.shape == (1, vertices, coordinates)+ assert not selected._is_batched+ assert selected.mode == boxes.mode+ assert selected.data.device == device+ assert selected.data.dtype == dtype+ self.assert_close(selected.data, boxes.data[key].unsqueeze(0), atol=0, rtol=0)+ if container is Boxes:+ assert selected._N is None+ assert selected._valid.shape == (1,)+ self.assert_close(selected._valid, torch.ones(1, device=device, dtype=torch.bool))+ self.assert_close(selected.to_tensor(mode), boxes.to_tensor(mode)[key].unsqueeze(0), atol=0, rtol=0)++ def test_scalar_selection_keeps_a_view_6478(+ self,+ container: type[Boxes] | type[Boxes3D],+ vertices: int,+ coordinates: int,+ mode: str,+ device: torch.device,+ dtype: torch.dtype,+ ) -> None:+ # The selection shares storage with the container, like the raw tensor indexing it wraps.+ data = torch.arange(3 * vertices * coordinates, device=device, dtype=dtype).reshape(3, vertices, coordinates)+ boxes = container(data, mode=mode)++ selected = boxes[1]+ selected.data.add_(1.0)+ self.assert_close(boxes.data[1], selected.data[0], atol=0, rtol=0)++ boxes[2] = container(torch.full((1, vertices, coordinates), 7.0, device=device, dtype=dtype), mode=mode)+ self.assert_close(+ boxes.data[2], torch.full((vertices, coordinates), 7.0, device=device, dtype=dtype), atol=0, rtol=0+ )++ @pytest.mark.parametrize("batched", [False, True])+ def test_existing_selection_6478(+ self,+ container: type[Boxes] | type[Boxes3D],+ vertices: int,+ coordinates: int,+ mode: str,+ batched: bool,+ device: torch.device,+ dtype: torch.dtype,+ ) -> None:+ # Slices, index tensors, masks and (batched) scalars keep their tensor-selection shape.+ shape = (2, 3, vertices, coordinates) if batched else (3, vertices, coordinates)+ count = (6 if batched else 3) * vertices * coordinates+ data = torch.arange(count, device=device, dtype=dtype).reshape(shape)+ boxes = container(data, mode=mode)+ keys = [+ slice(None, 1),+ slice(0, 0),+ slice(None, None, 2),+ torch.tensor([1, 0], device=device),+ torch.arange(data.shape[0], device=device) % 2 == 0,+ ]+ if batched:+ keys.extend([0, -1, torch.tensor(-1, device=device)])++ for key in keys:+ selected = boxes[key]+ assert selected.shape == data[key].shape+ assert selected._is_batched == (data[key].ndim == 4)+ assert selected.mode == boxes.mode+ self.assert_close(selected.data, data[key], atol=0, rtol=0)+ if container is Boxes:+ assert selected._N is None+ assert selected._valid.shape == selected.data.shape[:-2]+ self.assert_close(selected._valid, boxes._valid[key])++ empty = container(data[:0], mode=mode)+ assert empty[:].shape == data[:0].shape+ for key in [0, -1, torch.tensor(0, device=device)]:+ with pytest.raises(IndexError):+ empty[key]++ @pytest.mark.parametrize(+ "batched,key",+ [+ (False, (slice(None), 0)),+ (False, (slice(None), -1)),+ (False, (Ellipsis, 0, slice(None))),+ (True, (0, 1)),+ (True, (-1, -1)),+ ],+ )+ def test_tuple_key_selection_raises_6478(+ self,+ container: type[Boxes] | type[Boxes3D],+ vertices: int,+ coordinates: int,+ mode: str,+ batched: bool,+ key: tuple,+ device: torch.device,+ dtype: torch.dtype,+ ) -> None:+ # A tuple key that leaves a (vertices, coordinates) tensor, as ``[:, 0]`` does with as many boxes as vertices,+ # is not the selection of one box by an integer: it raises, as it did before #6478.+ shape = (2, vertices, vertices, coordinates) if batched else (vertices, vertices, coordinates)+ boxes = container(torch.rand(shape, device=device, dtype=dtype), mode=mode)+ with pytest.raises(ValueError, match="shape must be"):+ boxes[key]++ def test_gradcheck_scalar_6478(+ self,+ container: type[Boxes] | type[Boxes3D],+ vertices: int,+ coordinates: int,+ mode: str,+ device: torch.device,+ ) -> None:+ data = torch.arange(3 * vertices * coordinates, device=device, dtype=torch.float64).reshape(+ 3, vertices, coordinates+ )+ self.gradcheck(lambda x: container(x, mode=mode)[-1].data, (data,))++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_dynamo_scalar_6478(+ self,+ container: type[Boxes] | type[Boxes3D],+ vertices: int,+ coordinates: int,+ mode: str,+ device: torch.device,+ dtype: torch.dtype,+ torch_optimizer: object,+ ) -> None:+ # The getter is pure tensor indexing plus an unsqueeze, so a scalar selection stays fullgraph.+ data = torch.arange(3 * vertices * coordinates, device=device, dtype=dtype).reshape(3, vertices, coordinates)++ def select_last(x: torch.Tensor) -> torch.Tensor:+ return container(x, mode=mode)[-1].data++ self.assert_close(torch_optimizer(select_last, fullgraph=True)(data), data[-1:].clone(), atol=0, rtol=0)++class TestBoxes2D(BaseTester):def test_convention_from_tensor_xyxy_stores_inclusive_vertices_in_tl_tr_br_bl_order(self, device, dtype):# Convention pin: Boxes stores four inclusive (x, y) vertices in clockwise@@ -386,6 +560,27 @@ class TestBoxes2D(BaseTester):assert scalar._N is Noneassert isinstance(scalar.to_tensor("xyxy"), torch.Tensor)+ @pytest.mark.parametrize("key_kind", ["first", "last", "scalar_tensor"])+ def test_scalar_selection_keeps_validity_in_step_6478(+ self,+ key_kind: str,+ device: torch.device,+ dtype: torch.dtype,+ ) -> None:+ # #6478: a scalar selection carries the per-box validity of the row it selected.+ xyxy = torch.tensor([[0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 4.0, 4.0]], device=device, dtype=dtype)+ key = TestBoxesIndexing._key(key_kind, device)+ target = Boxes.from_tensor(xyxy)+ filtered = target.filter_boxes_by_area(min_area=2.0)++ selected = filtered[key]++ assert selected.shape == (1, 4, 2)+ assert selected._N is None+ assert selected._valid.shape == (1,)+ self.assert_close(selected._valid, filtered._valid[key].reshape(1), atol=0, rtol=0)+ self.assert_close(selected.to_tensor("xyxy"), filtered.to_tensor("xyxy")[key].unsqueeze(0), atol=0, rtol=0)+def test_smoke(self, device, dtype):def _create_tensor_box():# Sample two points of the rectangle