π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): floor the mosaic crop start so slice boxes follow the image (#5467)
niukanen1a1e814027bf3
diff --git a/changelog.d/5467.fixed.md b/changelog.d/5467.fixed.mdnew file mode 100644index 000000000..693495b25--- /dev/null+++ b/changelog.d/5467.fixed.md@@ -0,0 +1,4 @@+`RandomMosaic` with `cropping_mode="slice"` no longer offsets bounding boxes from the image content by the+fractional part of the crop start (up to 1 px up and left): the sampled start corner is now floored to a whole+pixel, which the image crop and the boxes share. `cropping_mode="resample"` crops from the same integer corner,+so it no longer interpolates a sub-pixel shift into the image.diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.pyindex 2d1c306c5..e831be5ed 100644--- a/kornia/augmentation/_2d/mix/mosaic.py+++ b/kornia/augmentation/_2d/mix/mosaic.py@@ -82,8 +82,8 @@ class RandomMosaic(MixAugmentationBaseV2):- ``output_size`` and the default output shape are ordered ``(height, width)``. With ``output_size=None``the output preserves the input's ``(H, W)`` even when they differ, in both ``cropping_mode="slice"`` and``cropping_mode="resample"``. ``start_ratio_range`` draws a pair used as ``(x / W, y / H)`` for the crop's- top-left corner. These are the repaired axis conventions from- `#4438 <https://github.com/kornia/kornia/issues/4438>`_.+ top-left corner, which is floored to a whole pixel that both cropping modes and the boxes share. These are+ the repaired axis conventions from `#4438 <https://github.com/kornia/kornia/issues/4438>`_.- ``p`` is per sample and this class fixes ``same_on_batch=False``. It composes ``mosaic_grid[0]`` tilesalong width and ``mosaic_grid[1]`` tiles along height, then crops each result. It supports``"bbox"``, ``"bbox_xyxy"``, and ``"bbox_xywh"`` in addition to image inputs; it does not supportdiff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.pyindex 2d28ce333..544864778 100644--- a/kornia/augmentation/random_generator/_2d/mosaic.py+++ b/kornia/augmentation/random_generator/_2d/mosaic.py@@ -100,8 +100,11 @@ class MosaicGenerator(RandomGeneratorBase):start_corner_factor = _adapted_rsampling((batch_size, 2), self.start_ratio_range_sampler, same_on_batch=False).to(device=_device, dtype=_dtype)- start_corner_x = start_corner_factor[:, 0] * batch_shape[-1]- start_corner_y = start_corner_factor[:, 1] * batch_shape[-2]+ # Slice-mode crops cast the start to long (``crop_by_indices``), so a fractional start would+ # translate boxes by a sub-pixel amount the image crop never applies. Floor the start here so+ # the image and the boxes share the same integer coordinates.+ start_corner_x = torch.floor(start_corner_factor[:, 0] * batch_shape[-1])+ start_corner_y = torch.floor(start_corner_factor[:, 1] * batch_shape[-2])crop_src = bbox_generator(start_corner_x,start_corner_y,diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.pyindex 72c6912f5..c25262fdb 100644--- a/tests/augmentation/test_augmentation_mix.py+++ b/tests/augmentation/test_augmentation_mix.py@@ -831,27 +831,29 @@ class TestRandomMosaic(BaseTester):dtype=dtype,)+ # The start corner is floored to the integer the slice crop uses (issue #5464), so boxes are+ # translated by whole pixels and land on integer coordinates.expected_box = torch.tensor([[- [0.7074, 0.7099, 2.7074, 2.7099],+ [1.0000, 1.0000, 3.0000, 3.0000],[0.0000, 0.0000, 1.0000, 1.0000],- [0.0000, 5.7099, 2.7074, 8.0000],- [0.0000, 2.7099, 1.0000, 4.7099],- [7.0000, 0.7099, 8.0000, 2.7099],- [5.7074, 0.0000, 7.7074, 1.0000],+ [0.0000, 6.0000, 3.0000, 8.0000],+ [0.0000, 3.0000, 1.0000, 5.0000],+ [7.0000, 1.0000, 8.0000, 3.0000],+ [6.0000, 0.0000, 8.0000, 1.0000],[7.0000, 7.0000, 8.0000, 8.0000],- [5.7074, 5.7099, 7.7074, 7.7099],+ [6.0000, 6.0000, 8.0000, 8.0000],],[- [0.0000, 0.0000, 1.0000, 2.8313],+ [0.0000, 0.0000, 1.0000, 3.0000],[0.0000, 0.0000, 1.0000, 1.0000],[0.0000, 7.0000, 1.0000, 8.0000],- [0.0000, 6.8313, 1.0000, 8.0000],- [4.5036, 0.0000, 8.0000, 2.8313],- [1.5036, 0.0000, 3.5036, 1.0000],- [4.5036, 6.8313, 8.0000, 8.0000],- [1.5036, 3.8313, 3.5036, 5.8313],+ [0.0000, 7.0000, 1.0000, 8.0000],+ [5.0000, 0.0000, 8.0000, 3.0000],+ [2.0000, 0.0000, 4.0000, 1.0000],+ [5.0000, 7.0000, 8.0000, 8.0000],+ [2.0000, 4.0000, 4.0000, 6.0000],],],device=device,diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.pyindex 666f75679..1bb655d7b 100644--- a/tests/augmentation/test_conventions_mix.py+++ b/tests/augmentation/test_conventions_mix.py@@ -247,6 +247,37 @@ class TestMixConventions(BaseTester):top_left = aug._params["src"][0, 0]self.assert_close(top_left, torch.tensor([4.0, 3.0], device=top_left.device, dtype=top_left.dtype))+ def test_convention_mosaic_slice_box_follows_image_crop_5464(self, device, dtype):+ # The image crop is sliced at the integer start while boxes were translated by the float+ # start, so a fractional ``start_ratio_range`` offset boxes from the image content.+ torch.manual_seed(0)+ ys, xs = torch.meshgrid(+ torch.arange(64, device=device, dtype=dtype),+ torch.arange(64, device=device, dtype=dtype),+ indexing="ij",+ )+ # Each pixel stores its source (x, y), which shows where the crop actually landed.+ image = torch.stack([xs, ys]).unsqueeze(0)+ boxes = torch.tensor([[[30.0, 30.0, 40.0, 40.0]]], device=device, dtype=dtype)++ aug = K.RandomMosaic(p=1.0, output_size=(20, 20), data_keys=["input", "bbox_xyxy"])+ output, output_boxes = aug(image, boxes)++ crop_start_x = output[0, 0, 0, 0]+ crop_start_y = output[0, 1, 0, 0]+ # The reported params and the image crop agree on the start corner. The generator samples in+ # float32 regardless of the input dtype, so only the value is compared.+ assert aug._params["src"][0, 0, 0].item() == crop_start_x.item()+ assert aug._params["src"][0, 0, 1].item() == crop_start_y.item()+ # The tile-0 box is translated by the same start the image crop used.+ expected = torch.stack(+ [+ torch.stack([30.0 - crop_start_x, 30.0 - crop_start_y]),+ torch.stack([40.0 - crop_start_x, 40.0 - crop_start_y]),+ ]+ ).reshape(4)+ self.assert_close(output_boxes[0, 0], expected.to(device=device, dtype=dtype))+def test_convention_mosaic_grid_first_axis_is_width(self, device, dtype):image = torch.arange(6, device=device, dtype=dtype).view(6, 1, 1, 1).expand(6, 1, 6, 4)aug = K.RandomMosaic(mosaic_grid=(2, 3), start_ratio_range=(0.5, 0.5), p=1.0)@@ -842,13 +873,15 @@ class TestMixConventions(BaseTester):aug = K.RandomMosaic(start_ratio_range=(0.3, 0.7), p=1.0)aug(image)top_left = aug._params["src"][:, 0]- ratios = torch.stack([top_left[:, 0] / 10, top_left[:, 1] / 6], dim=-1)- assert bool(((ratios >= 0.3 - 1e-5) & (ratios <= 0.7 + 1e-5)).all())+ # The start corner is the floored integer position of the ratio draw, so the bound is the+ # integer envelope of the ratio range: floor(low * size) .. floor(high * size).+ assert bool(((top_left[:, 0] >= (0.3 * 10) - 1) & (top_left[:, 0] <= 0.7 * 10)).all())+ assert bool(((top_left[:, 1] >= (0.3 * 6) - 1) & (top_left[:, 1] <= 0.7 * 6)).all())# Both entries are bounds on one draw, so both axes vary across the batch.- assert ratios[:, 0].unique().numel() > 1- assert ratios[:, 1].unique().numel() > 1+ assert top_left[:, 0].unique().numel() > 1+ assert top_left[:, 1].unique().numel() > 1# "Draws a pair": the two ratios are separate draws, not one value used twice.- assert not torch.allclose(ratios[:, 0], ratios[:, 1])+ assert not torch.allclose(top_left[:, 0] / 10, top_left[:, 1] / 6)@pytest.mark.device_agnosticdef test_convention_patchmix_patch_stays_inside_the_image(self):