π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): preserve filtered box validity (#5649)
Puttala Jeevan Kumar5e2aae144316
diff --git a/changelog.d/5649.breaking.md b/changelog.d/5649.breaking.mdnew file mode 100644index 000000000..4c0eb2136--- /dev/null+++ b/changelog.d/5649.breaking.md@@ -0,0 +1 @@+`Boxes.filter_boxes_by_area` now marks the boxes it removes as invalid instead of only zeroing their stored inclusive vertices. Previously a removed box exported as `[0, 0, 1, 1]` in the exclusive `'xyxy'`, `'xywh'` and `'vertices'` modes, `to_mask` filled pixel `(0, 0)` for it, and a later `transform_boxes`, `translate` or `pad` moved it like a real box. Now it exports as exact zeros in every mode, also after later transforms, and `to_mask` draws nothing for it. `RandomMosaic` boxes below `min_bbox_size` change in the same way: in direct calls for every box key, and inside `AugmentationSequential` for `"bbox_xywh"`, and for every key when a geometric augmentation follows the mosaic (it used to move them into real-looking boxes; without one, `"bbox_xyxy"` and `"bbox"` already came out as zeros). Because zero-width rows are rejected on import, passing such an `'xyxy'` or `'xywh'` export back to `Boxes.from_tensor` with the default `validate_boxes=True`, or a `"bbox_xywh"` output to another `AugmentationSequential`, now raises `ValueError` where it used to import a 1x1 box at the origin. A `Boxes` object pickled by an earlier version loads with every box valid.diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.pyindex e831be5ed..177e71180 100644--- a/kornia/augmentation/_2d/mix/mosaic.py+++ b/kornia/augmentation/_2d/mix/mosaic.py@@ -103,11 +103,8 @@ class RandomMosaic(MixAugmentationBaseV2):unselected sample's tensor is its own boxes unchanged, with no padding rows. A selected sample's tensorholds the boxes of each tile's source image, with no padding rows.- In either form, a selected sample's box that falls below ``min_bbox_size`` is zeroed by- :meth:`~kornia.geometry.boxes.Boxes.filter_boxes_by_area`. A direct call exports it as ``[0, 0, 1, 1]``- in ``"bbox_xyxy"`` and ``"bbox_xywh"``, not as zero-area padding- (`#4714 <https://github.com/kornia/kornia/issues/4714>`_); inside- :class:`~kornia.augmentation.container.AugmentationSequential` it is ``[0, 0, 1, 1]`` in ``"bbox_xywh"``- and ``[0, 0, 0, 0]`` in ``"bbox_xyxy"``.+ :meth:`~kornia.geometry.boxes.Boxes.filter_boxes_by_area`. It exports as exact zeros in every box+ format, from a direct call and from :class:`~kornia.augmentation.container.AugmentationSequential`."""@@ -171,7 +168,7 @@ class RandomMosaic(MixAugmentationBaseV2):_offset[idx, 1] = batch_shapes_idx[:, -2] * j - src_box_idx[:, 0, 1]_box = input.clone()_idx = i * flags["mosaic_grid"][1] + j- _box._data[params["permutation"][:, 0]] = _box._data[params["permutation"][:, _idx]]+ _box[params["permutation"][:, 0]] = input[params["permutation"][:, _idx]]if input._N is not None:# A list input pads each sample to the longest one; the tile keeps its source's padding count._box._N = list(input._N)@@ -190,6 +187,7 @@ class RandomMosaic(MixAugmentationBaseV2):# An unselected sample keeps its own boxes unchanged, followed by padding up to the mosaic box count.# The padding is recorded in ``_N`` and exported as all-zero (zero-area) rows.out_boxes._data[~to_apply, :num_boxes] = input._data[~to_apply]+ out_boxes._valid[~to_apply, :num_boxes] = input._valid[~to_apply]out_boxes._data[~to_apply, num_boxes:] = 0.0padding = out_boxes._data.shape[1] - num_boxesmerged_padding = out_boxes._N if out_boxes._N is not None else [0] * len(to_apply)diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex ed56c1d59..7fc21aeef 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -523,6 +523,7 @@ class _AugmentationBase(_BasicAugmentationBase):# and swap in the blended data, same effect as the index_put on .data.output = output_not_transformed.clone()output._data = blended_data+ output._valid = self._blend_by_prob(output_transformed._valid, output_not_transformed._valid, to_apply)return outputdef transform_keypoints(diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex 2100cab89..bdf616aae 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -17,7 +17,7 @@from __future__ import annotations-from typing import Optional, Tuple, cast+from typing import Any, Optional, Tuple, castimport torchfrom torch import Size@@ -292,10 +292,18 @@ class Boxes:self._data = boxesself._mode = mode+ # Filtering can leave holes; _N only describes trailing list padding.+ self._valid = torch.ones(boxes.shape[:-2], device=boxes.device, dtype=torch.bool)++ def __setstate__(self, state: dict[str, Any]) -> None:+ self.__dict__.update(state)+ if "_valid" not in state: # pickled before filtering kept validity: every box is valid+ 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)new_box._mode = self._mode+ new_box._valid = self._valid[key]# 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]@@ -304,6 +312,7 @@ class Boxes:def __setitem__(self, key: slice | int | torch.Tensor, value: Boxes) -> Boxes:self._data[key] = value._data+ self._valid[key] = value._validreturn self@property@@ -384,18 +393,34 @@ class Boxes:for i, (self_pad, boxes_pad) in enumerate(zip(self_padding, boxes_padding))])+ valid = torch.stack(+ [+ torch.cat(+ [+ self._valid[i, : self._valid.shape[-1] - self_pad],+ boxes._valid[i, : boxes._valid.shape[-1] - boxes_pad],+ self._valid[i, self._valid.shape[-1] - self_pad :],+ boxes._valid[i, boxes._valid.shape[-1] - boxes_pad :],+ ]+ )+ for i, (self_pad, boxes_pad) in enumerate(zip(self_padding, boxes_padding))+ ]+ )padding = [self_pad + boxes_pad for self_pad, boxes_pad in zip(self_padding, boxes_padding)]else:data = torch.cat([self._data, boxes.data], dim=-3)+ valid = torch.cat([self._valid, boxes._valid], dim=-1)if inplace:self._data = dataself._N = padding+ self._valid = validreturn selfobj = self.clone()obj._data = dataobj._N = padding+ obj._valid = validreturn objdef index_put(@@ -417,7 +442,8 @@ class Boxes:The indices address entries in the stored tensor, commonlyshaped :math:`(B, N, 4, 2)` or :math:`(N, 4, 2)`.values: Replacement coordinates. If a :class:`Boxes` object is- passed, its :attr:`data` tensor is used.+ passed, its coordinates and filtering validity are copied. Raw tensor writes+ change only coordinates and preserve the existing filtering validity.inplace: If ``True``, update this object and return ``self``. If``False``, clone the current data first and return a new:class:`Boxes` instance.@@ -425,18 +451,12 @@ class Boxes:Returns::class:`Boxes` containing the updated coordinates."""- _data = self._data if inplace else self._data.clone()-+ obj = self if inplace else self.clone()if isinstance(values, Boxes):- _data.index_put_(indices, values.data)+ obj._data.index_put_(indices, values.data)+ obj._valid.index_put_(indices, values._valid)else:- _data.index_put_(indices, values)-- if inplace:- return self-- obj = self.clone()- obj._data = _data+ obj._data.index_put_(indices, values)return objdef _broadcast_over_vertices(self, values: torch.Tensor) -> torch.Tensor:@@ -590,7 +610,8 @@ class Boxes:``min_area`` or larger than ``max_area`` are not dropped from thetensor; their coordinates are replaced with zeros so the original batchand box dimensions stay unchanged. See :meth:`compute_area` for the- area convention used by the thresholds.+ area convention used by the thresholds. Filtered boxes export as exact zeros in every+ mode and draw no mask pixels, including after subsequent coordinate transforms.Args:min_area: Optional lower inclusive area threshold. Boxes with area@@ -605,16 +626,15 @@ class Boxes:out-of-range boxes replaced by zero coordinates."""area = self.compute_area()- _data = self._data if inplace else self._data.clone()+ keep = torch.ones_like(area, dtype=torch.bool)if min_area is not None:- _data[area < min_area] = 0.0+ keep &= ~(area < min_area)if max_area is not None:- _data[area > max_area] = 0.0- if inplace:- return self-- obj = self.clone()- obj._data = _data+ keep &= ~(area > max_area)+ obj = self if inplace else self.clone()+ obj._valid &= keep+ if min_area is not None or max_area is not None:+ obj._data.masked_fill_(~keep[..., None, None], 0.0)return objdef compute_area(self) -> torch.Tensor:@@ -782,6 +802,10 @@ class Boxes:if mode.startswith("vertices"):boxes = _boxes_to_polygons(boxes[..., 0], boxes[..., 1], boxes[..., 2], boxes[..., 3])+ valid = self._valid if self._is_batched else self._valid.unsqueeze(0)+ valid = valid.reshape(valid.shape + (1,) * (boxes.ndim - valid.ndim))+ boxes = boxes.masked_fill(~valid, 0.0)+if self._N is not None and not as_padded_sequence:boxes = [torch.nn.functional.pad(o, (len(o.shape) - 1) * [0, 0] + [0, -n]) for o, n in zip(boxes, self._N)]else:@@ -1004,6 +1028,7 @@ class Boxes:if dtype is not None and not _is_floating_point_dtype(dtype):raise ValueError("Boxes must be in floating point")self._data = self._data.to(device=device, dtype=dtype)+ self._valid = self._valid.to(device=self._data.device)return selfdef clone(self) -> Boxes:@@ -1017,6 +1042,7 @@ class Boxes:obj = type(self)(self._data.clone(), False)obj._mode = self._modeobj._N = self._N+ obj._valid = self._valid.clone()obj._is_batched = self._is_batchedreturn obj@@ -1030,6 +1056,7 @@ class Boxes:``self`` after converting :attr:`data` in place."""self._data = self._data.type(dtype)+ self._valid = self._valid.to(device=self._data.device)return self@@ -1120,6 +1147,8 @@ class VideoBoxes(Boxes):out = type(self)(selected.flatten(0, 1), False)out._mode = self._mode+ selected_valid = self._valid.view(batch_size, self.temporal_channel_size, self._valid.shape[-1])[key]+ out._valid = selected_valid.reshape(out._data.shape[:-2])out.temporal_channel_size = self.temporal_channel_sizereturn out@@ -1127,6 +1156,7 @@ class VideoBoxes(Boxes):r"""Write whole videos, selected by ``key`` on the video-batch axis as in :meth:`__getitem__`."""size = self.temporal_channel_sizeself._data.view(-1, size, *self._data.shape[1:])[key] = value.data.view(-1, size, *value.data.shape[1:])+ self._valid.view(-1, size, self._valid.shape[-1])[key] = value._valid.view(-1, size, value._valid.shape[-1])return selfdef to_tensor(@@ -1164,6 +1194,7 @@ class VideoBoxes(Boxes):obj = type(self)(self._data.clone(), False)obj._mode = self._modeobj._N = self._N+ obj._valid = self._valid.clone()obj._is_batched = self._is_batchedobj.temporal_channel_size = self.temporal_channel_sizereturn objdiff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.pyindex 11fb22f84..3595f5ad1 100644--- a/tests/augmentation/test_augmentation_mix.py+++ b/tests/augmentation/test_augmentation_mix.py@@ -24,6 +24,7 @@ from kornia.augmentation import (AugmentationSequential,PatchMix,RandomCutMixV2,+ RandomHorizontalFlip,RandomJigsaw,RandomMixUpV2,RandomMosaic,@@ -663,6 +664,61 @@ class TestRandomMosaic(BaseTester):torch.testing.assert_close(output[0], boxes[0])torch.testing.assert_close(output[2], boxes[2])+ @pytest.mark.parametrize("sequential", [False, True])+ @pytest.mark.parametrize("data_key", ["bbox_xyxy", "bbox_xywh", "bbox"])+ def test_mosaic_filtered_exports_4714(self, sequential, data_key, device, dtype):+ image = torch.zeros(2, 1, 6, 8, device=device, dtype=dtype)+ xyxy = image.new_tensor([[[1.0, 1.0, 2.0, 2.0]], [[1.0, 1.0, 4.0, 4.0]]])+ mode = {"bbox_xyxy": "xyxy", "bbox_xywh": "xywh", "bbox": "vertices_plus"}[data_key]+ if data_key == "bbox" and not sequential:+ mode = "vertices"+ boxes = Boxes.from_tensor(xyxy).to_tensor(mode)+ mosaic = RandomMosaic(p=1.0, min_bbox_size=99.0)+ aug = AugmentationSequential(mosaic, data_keys=["input", data_key]) if sequential else mosaic+ if sequential:+ aug(image, boxes)+ params = aug._params+ params[0].data["batch_prob"] = image.new_tensor([0.0, 1.0])+ _, output = aug(image, boxes, params=params)+ else:+ params = mosaic.forward_parameters(image.shape)+ params["batch_prob"] = image.new_tensor([0.0, 1.0])+ _, output = aug(image, boxes, params=params, data_keys=["input", data_key])+ self.assert_close(output[0, :1], boxes[0], atol=0.0, rtol=0.0)+ assert output[0, 1:].count_nonzero() == 0+ assert output[1].count_nonzero() == 0++ def test_annotation_filter_validity_follows_gate_4714(self, device, dtype):+ class FilterBoxes(RandomHorizontalFlip):+ def apply_transform_box(self, input, params, flags, transform=None):+ return input.filter_boxes_by_area(2.0)++ image = torch.zeros(2, 1, 6, 8, device=device, dtype=dtype)+ xyxy = image.new_tensor([[[1.0, 1.0, 2.0, 2.0]], [[1.0, 1.0, 2.0, 2.0]]])+ boxes = Boxes.from_tensor(xyxy)+ aug = FilterBoxes(p=1.0)+ params = aug.forward_parameters(image.shape)+ params["batch_prob"] = image.new_tensor([0.0, 1.0])+ output = aug.transform_boxes(boxes, params, aug.flags)+ self.assert_close(output.to_tensor("xyxy")[0], xyxy[0])+ assert output.to_tensor("xyxy")[1].count_nonzero() == 0+ self.assert_close(boxes.to_tensor("xyxy"), xyxy)++ def test_mosaic_permutates_filtered_validity_4714(self, device, dtype):+ image = torch.zeros(2, 1, 6, 8, device=device, dtype=dtype)+ boxes = Boxes.from_tensor(+ image.new_tensor([[[1.0, 1.0, 2.0, 2.0]], [[1.0, 1.0, 4.0, 4.0]]])+ ).filter_boxes_by_area(2.0)+ aug = RandomMosaic(p=1.0, output_size=(12, 16), start_ratio_range=(0.0, 0.0))+ params = aug.forward_parameters(image.shape)+ params["permutation"] = torch.tensor([[0, 1, 0, 1], [1, 0, 1, 0]], device=device)+ output = aug.apply_transform_boxes(boxes, params, aug.flags).to_tensor("xyxy")+ invalid = params["permutation"] == 0+ assert output[invalid].count_nonzero() == 0+ # Select whole boxes before slicing coordinates; mixed mask/slice indexing differs across torch versions.+ valid_boxes = output[~invalid]+ assert (valid_boxes[:, 2:] > valid_boxes[:, :2]).all()+def test_partial_batch_preserves_unselected_filtered_boxes_4679(self, device, dtype):input = torch.rand(4, 1, 6, 8, device=device, dtype=dtype)boxes = torch.tensor(diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.pyindex d3cb8c365..0e8b6772c 100644--- a/tests/geometry/test_boxes.py+++ b/tests/geometry/test_boxes.py@@ -15,6 +15,7 @@# limitations under the License.#+import picklefrom functools import partialimport pytest@@ -947,6 +948,133 @@ class TestBoxes2D(BaseTester):assert filtered.data.shape == boxes.data.shapeassert not torch.equal(boxes.data, torch.zeros_like(boxes.data))+ @pytest.mark.parametrize("inplace", [False, True])+ @pytest.mark.parametrize("batched", [False, True])+ def test_filter_exports_and_masks_4714(self, inplace, batched, device, dtype, monkeypatch):+ xyxy = torch.tensor(+ [[1.0, 1.0, 4.0, 4.0], [1.0, 1.0, 2.0, 2.0], [2.0, 2.0, 5.0, 5.0]], device=device, dtype=dtype+ )+ if batched:+ xyxy = torch.stack([xyxy, xyxy.flip(0).roll(1, 0)])+ boxes = Boxes.from_tensor(xyxy)+ before = boxes.clone()+ filtered = boxes.filter_boxes_by_area(min_area=2.0, inplace=inplace)+ invalid = (xyxy[..., 2] - xyxy[..., 0]) == 1+ assert (filtered is boxes) == inplace+ for mode in ("xyxy", "xywh", "vertices", "xyxy_plus", "vertices_plus"):+ expected = before.to_tensor(mode)+ expected[invalid] = 0+ self.assert_close(filtered.to_tensor(mode), expected, atol=0.0, rtol=0.0)+ expected_mask = before.to_mask(6, 6)+ expected_mask[invalid] = 0+ self.assert_close(filtered.to_mask(6, 6), expected_mask, atol=0.0, rtol=0.0)+ monkeypatch.setattr(boxes_module, "is_exporting", lambda: True)+ self.assert_close(filtered.to_mask(6, 6), expected_mask, atol=0.0, rtol=0.0)+ if not inplace:+ self.assert_close(boxes.to_tensor("xyxy"), xyxy, atol=0.0, rtol=0.0)++ def test_filter_origin_all_none_and_repeat_4714(self, device, dtype):+ # The valid origin pixel and a filtered box have identical raw inclusive coordinates.+ xyxy = torch.tensor([[0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 4.0, 4.0]], device=device, dtype=dtype)+ boxes = Boxes.from_tensor(xyxy)+ filtered = boxes.filter_boxes_by_area(max_area=0.0)+ self.assert_close(filtered.to_tensor("xyxy"), xyxy.new_tensor([[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]))+ assert filtered.to_mask(5, 5)[0, 0, 0] == 1+ assert filtered.to_mask(5, 5)[1].count_nonzero() == 0+ for mode in ("xyxy", "xywh", "vertices", "xyxy_plus", "vertices_plus"):+ self.assert_close(+ boxes.filter_boxes_by_area(min_area=0.0).to_tensor(mode), boxes.to_tensor(mode), atol=0.0, rtol=0.0+ )+ assert boxes.filter_boxes_by_area(min_area=99.0).to_tensor(mode).count_nonzero() == 0+ self.assert_close(+ filtered.filter_boxes_by_area().to_tensor(mode), filtered.to_tensor(mode), atol=0.0, rtol=0.0+ )+ assert boxes.filter_boxes_by_area(min_area=99.0).to_mask(5, 5).count_nonzero() == 0+ empty = Boxes.from_tensor(xyxy[:0]).filter_boxes_by_area(2.0)+ assert empty.to_tensor("xyxy").shape == (0, 4)++ def test_filter_copy_index_and_transforms_4714(self, device, dtype):+ xyxy = torch.tensor([[[1.0, 1.0, 4.0, 4.0], [1.0, 1.0, 2.0, 2.0]]], device=device, dtype=dtype)+ boxes = Boxes.from_tensor(xyxy.repeat(2, 1, 1)).filter_boxes_by_area(2.0)+ expected = boxes.to_tensor("xyxy")+ for key in (slice(None), 0, torch.tensor([1, 0], device=device), torch.tensor([True, False], device=device)):+ self.assert_close(boxes[key].to_tensor("xyxy"), expected[key], atol=0.0, rtol=0.0)+ cloned = boxes.clone()+ cloned.filter_boxes_by_area(99.0, inplace=True)+ self.assert_close(boxes.to_tensor("xyxy"), expected, atol=0.0, rtol=0.0)+ assert cloned.to_tensor("xyxy").count_nonzero() == 0+ offset = xyxy.new_tensor([[2.0, 3.0]])+ moved = boxes.translate(offset.expand(2, -1))+ for mode in ("xyxy", "xywh", "vertices", "xyxy_plus", "vertices_plus"):+ assert moved.to_tensor(mode)[:, 1].count_nonzero() == 0+ padding = xyxy.new_tensor([[2.0, 0.0, 3.0, 0.0]])+ for result in (boxes.clone().pad(padding), moved.clamp(xyxy.new_zeros(1, 2), xyxy.new_full((1, 2), 9.0))):+ assert result.to_mask(10, 10)[:, 1].count_nonzero() == 0+ self.assert_close(boxes.clone().pad(padding).unpad(padding).to_tensor("xyxy"), expected)+ converted = boxes.clone().to(device=torch.device("cpu"), dtype=torch.float32).type(dtype).to(device=device)+ self.assert_close(converted.to_tensor("xyxy"), expected)+ assert converted._valid.dtype == torch.bool+ assert converted._valid.device == converted.device+ # Basic slices share both coordinates and filtering state.+ original = Boxes.from_tensor(xyxy)+ original[:].filter_boxes_by_area(2.0, inplace=True)+ assert original.to_tensor("xyxy")[:, 1].count_nonzero() == 0++ @pytest.mark.parametrize("inplace", [False, True])+ def test_filter_assignment_4714(self, inplace, device, dtype):+ xyxy = torch.tensor([[[1.0, 1.0, 4.0, 4.0], [1.0, 1.0, 2.0, 2.0]]], device=device, dtype=dtype)+ boxes = Boxes.from_tensor(xyxy.repeat(2, 1, 1))+ filtered = boxes[:1].filter_boxes_by_area(2.0)+ index = torch.tensor([1], device=device)+ updated = boxes.index_put((index,), filtered, inplace=inplace)+ assert updated.to_tensor("xyxy")[1, 1].count_nonzero() == 0+ self.assert_close(updated.to_tensor("xyxy")[0], xyxy[0])+ updated[index] = Boxes.from_tensor(xyxy)+ self.assert_close(updated.to_tensor("xyxy")[1], xyxy[0])+ updated[index] = filtered+ assert updated.to_mask(5, 5)[1, 1].count_nonzero() == 0+ if not inplace:+ self.assert_close(boxes.to_tensor("xyxy"), xyxy.repeat(2, 1, 1))++ @pytest.mark.parametrize("inplace", [False, True])+ @pytest.mark.parametrize("reverse", [False, True])+ def test_filter_merge_and_padding_4714(self, inplace, reverse, device, dtype):+ xyxy = torch.tensor(+ [[1.0, 1.0, 4.0, 4.0], [1.0, 1.0, 2.0, 2.0], [2.0, 2.0, 5.0, 5.0]], device=device, dtype=dtype+ )+ first = Boxes.from_tensor([xyxy, xyxy[:1]]).filter_boxes_by_area(2.0)+ second = Boxes.from_tensor(xyxy[:1].expand(2, 1, 4))+ if reverse:+ first, second = second, first+ first_out = first.to_tensor("xyxy")+ second_out = second.to_tensor("xyxy")+ expected = [torch.cat([a, b]) for a, b in zip(first_out, second_out)]+ merged = first.merge(second, inplace=inplace)+ assert merged._N == [0, 2]+ assert merged.to_tensor("xyxy")[0][2 if reverse else 1].count_nonzero() == 0+ for actual, wanted in zip(merged.to_tensor("xyxy"), expected):+ self.assert_close(actual, wanted, atol=0.0, rtol=0.0)+ assert merged.to_mask(6, 6)[1, 2:].count_nonzero() == 0+ dense = Boxes.from_tensor(xyxy).filter_boxes_by_area(2.0)+ dense_merged = dense.merge(Boxes.from_tensor(xyxy[:1]))+ self.assert_close(dense_merged.to_tensor("xyxy"), torch.cat([dense.to_tensor("xyxy"), xyxy[:1]]))++ def test_unpickle_without_filter_validity_4714(self, device, dtype):+ # A Boxes pickled by an earlier kornia has no ``_valid``: it loads with every box valid and can be filtered.+ xyxy = torch.tensor([[[1.0, 1.0, 4.0, 4.0], [0.0, 0.0, 1.0, 1.0]]], device=device, dtype=dtype)+ boxes = Boxes.from_tensor(xyxy)+ del boxes._valid+ restored = pickle.loads(pickle.dumps(boxes)) # noqa: S301+ self.assert_close(restored.to_tensor("xyxy"), xyxy, atol=0.0, rtol=0.0)+ filtered = restored.filter_boxes_by_area(min_area=2.0).to_tensor("xyxy")+ self.assert_close(filtered, torch.cat([xyxy[:, :1], torch.zeros_like(xyxy[:, 1:])], 1), atol=0.0, rtol=0.0)++ def test_filter_gradcheck_4714(self, device):+ xyxy = torch.tensor(+ [[1.0, 1.0, 4.0, 4.0], [1.0, 1.0, 2.0, 2.0]], device=device, dtype=torch.float64, requires_grad=True+ )+ self.gradcheck(lambda x: Boxes.from_tensor(x).filter_boxes_by_area(2.0).to_tensor("xyxy"), (xyxy,))+def test_convention_filter_boxes_by_area_maximum_zeroes_in_place(self, device, dtype):# The shoelace areas are 2 and 8. Equal lower/upper bounds retain the# first box, pinning both inclusive endpoints; the larger box is zeroed.@@ -2005,6 +2133,20 @@ class TestTransformBoxes3D(BaseTester):class TestVideoBoxes(BaseTester):+ def test_filter_video_copy_index_assignment_4714(self, device, dtype):+ data = torch.tensor([[[1.0, 1.0, 4.0, 4.0], [1.0, 1.0, 2.0, 2.0]]], device=device, dtype=dtype)+ vertices = Boxes.from_tensor(data).data.repeat(4, 1, 1, 1).reshape(2, 2, 2, 4, 2)+ video = VideoBoxes.from_tensor(vertices)+ filtered = video.filter_boxes_by_area(2.0)+ expected = filtered.to_tensor("xyxy")+ assert expected[:, :, 1].count_nonzero() == 0+ for selected in (filtered.clone(), filtered[:], filtered[0]):+ assert selected.to_tensor("xyxy")[..., 1, :].count_nonzero() == 0+ video[0] = filtered[1]+ self.assert_close(video.to_tensor("xyxy")[:1], expected[:1])+ assert video.to_tensor("xyxy")[1, :, 1].count_nonzero() > 0+ assert filtered.to_mask(5, 5)[:, 1].count_nonzero() == 0+"""Public API and round-trip coverage for :class:`VideoBoxes` (#4016)."""@staticmethod