π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): insert the 3D channel axis at dim 1 in _transform_input3d_by_shape (#6358)
Parman Mohammadalizadeha0017820a82e
diff --git a/changelog.d/6358.fixed.md b/changelog.d/6358.fixed.mdnew file mode 100644index 000000000..1eae0a9d6--- /dev/null+++ b/changelog.d/6358.fixed.md@@ -0,0 +1 @@+`transform_tensor(input, shape=..., match_channel=False)` on 3D augmentations now inserts the missing channel axis at dim 1, so a `(B, D, H, W)` mask becomes `(B, 1, D, H, W)` instead of `(B, D, 1, H, W)`, and a `(D, H, W)` or `(C, D, H, W)` input now reaches 5 dimensions.diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex e47606851..06d04326f 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -209,12 +209,11 @@ def _transform_input_by_shape(def _transform_input3d_by_shape(input: torch.Tensor, reference_shape: torch.Tensor, match_channel: bool = True) -> torch.Tensor:- """Unsqueeze a 3-dim tensor at dim 0, then a 4-dim one at dim 2 if its first size equals the reference batch size.+ """Add the missing batch or channel dimension of a volume tensor, e.g. a mask, to match a (B, C, D, H, W) reference.- A 3-dim ``(D, H, W)`` input first becomes ``(1, D, H, W)``. When the reference batch size is 1, the next branch- also inserts dimension 2, giving ``(1, D, 1, H, W)``; otherwise it stays 4-dim. A 4-dim ``(B, D, H, W)`` input- becomes ``(B, D, 1, H, W)``: the new axis lands after ``D`` rather than at ``C``. Tracked in- `#6354 <https://github.com/kornia/kornia/issues/6354>`_.+ A ``(D, H, W)`` input becomes ``(1, 1, D, H, W)``. A 4-dim input whose first size equals the reference batch size+ is read as ``(B, D, H, W)`` and becomes ``(B, 1, D, H, W)``; any other 4-dim input is read as ``(C, D, H, W)`` and+ becomes ``(1, C, D, H, W)``.Arguments:input: torch.Tensor to be transformed@@ -228,10 +227,10 @@ def _transform_input3d_by_shape(if len(input.shape) == 3:input = input.unsqueeze(0)- if len(input.shape) == 4 and B == input.shape[-4]:+ if len(input.shape) == 4:# If the first dim matches within the batch_size, add a `C` dim# Useful to handler Masks without `C` dimensions- input = input.unsqueeze(2)+ input = input.unsqueeze(1) if B == input.shape[-4] else input.unsqueeze(0)if match_channel and C:if not input.shape[-4] == C:diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.pyindex d82b856c9..626748554 100644--- a/tests/augmentation/test_base.py+++ b/tests/augmentation/test_base.py@@ -31,6 +31,7 @@ from kornia.augmentation._2d.intensity.gaussian_blur import RandomGaussianBlurfrom kornia.augmentation._2d.intensity.invert import RandomInvertfrom kornia.augmentation._2d.mix.mixup import RandomMixUpV2from kornia.augmentation._3d.geometric.affine import RandomAffine3D+from kornia.augmentation._3d.geometric.depthical_flip import RandomDepthicalFlip3Dfrom kornia.augmentation._3d.geometric.horizontal_flip import RandomHorizontalFlip3Dfrom kornia.augmentation._3d.intensity.motion_blur import RandomMotionBlur3Dfrom kornia.augmentation.base import _BasicAugmentationBase@@ -348,6 +349,55 @@ class TestGeometricAugmentationBase3D:assert res.dtype == dtype, "The output dtype should match the input dtype"+class _RandomDepthicalFlip3DWithMask(RandomDepthicalFlip3D):+ def apply_transform_mask(self, input, params, flags, transform=None):+ return self.apply_transform(input, params, flags, transform)++ def apply_non_transform_mask(self, input, params, flags, transform=None):+ return input+++class TestTransformTensorByShape(BaseTester):+ # Each case gives the output shape for match_channel=False and for True; None means the channel check raises.+ @pytest.mark.parametrize("match_channel", [False, True])+ @pytest.mark.parametrize(+ "reference, input_shape, expected",+ [+ ((2, 3, 5, 6), (5, 6), ((1, 1, 5, 6), None)),+ ((1, 3, 5, 6), (5, 6), ((1, 1, 5, 6), None)),+ ((2, 3, 5, 6), (2, 5, 6), ((2, 1, 5, 6), None)),+ ((2, 3, 5, 6), (3, 5, 6), ((1, 3, 5, 6), (1, 3, 5, 6))),+ ((2, 3, 5, 6), (2, 3, 5, 6), ((2, 3, 5, 6), (2, 3, 5, 6))),+ ((2, 3, 4, 5, 6), (4, 5, 6), ((1, 1, 4, 5, 6), None)),+ ((1, 3, 4, 5, 6), (4, 5, 6), ((1, 1, 4, 5, 6), None)),+ ((2, 3, 4, 5, 6), (2, 4, 5, 6), ((2, 1, 4, 5, 6), None)),+ ((2, 3, 4, 5, 6), (3, 4, 5, 6), ((1, 3, 4, 5, 6), (1, 3, 4, 5, 6))),+ ((2, 3, 4, 5, 6), (2, 3, 4, 5, 6), ((2, 3, 4, 5, 6), (2, 3, 4, 5, 6))),+ ],+ )+ def test_shape_6354(self, device, dtype, reference, input_shape, expected, match_channel):+ augmentation = RandomHorizontalFlip(p=1.0) if len(reference) == 4 else RandomHorizontalFlip3D(p=1.0)+ input = torch.rand(input_shape, device=device, dtype=dtype)+ shape = torch.tensor(reference, device=device)+ expected = expected[match_channel]+ if expected is None:+ with pytest.raises(ValueError, match="C dimension"):+ augmentation.transform_tensor(input, shape=shape, match_channel=match_channel)+ else:+ assert augmentation.transform_tensor(input, shape=shape, match_channel=match_channel).shape == expected++ @pytest.mark.parametrize("keepdim", [False, True])+ def test_3d_bdhw_mask_follows_the_volume_6354(self, device, dtype, keepdim):+ volume = torch.arange(2 * 4 * 5 * 6, device=device).to(dtype).reshape(2, 1, 4, 5, 6)+ augmentation = _RandomDepthicalFlip3DWithMask(p=1.0, keepdim=keepdim)+ output_volume = augmentation(volume)+ output_mask = augmentation.transform_masks(+ volume[:, 0], augmentation._params, augmentation.flags, transform=augmentation.transform_matrix+ )+ expected = output_volume[:, 0] if keepdim else output_volume+ self.assert_close(output_mask, expected, rtol=0, atol=0)++class TestDeviceAgnosticAugmentationParameters(BaseTester):"""Augmentations keep RNG/params on CPU while accepting accelerator inputs.