🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): accept a size-1 axis in CenterCrop3D and RandomCrop3D (#4732)
Rızgar Ozan38d2562fedbc
diff --git a/changelog.d/4732.fixed.md b/changelog.d/4732.fixed.mdnew file mode 100644index 000000000..583b46fd4--- /dev/null+++ b/changelog.d/4732.fixed.md@@ -0,0 +1 @@+`CenterCrop3D` and `RandomCrop3D` now accept a crop with a size-1 axis. The crop matrix is built as the translation it is, instead of being solved from the box vertices, which raised `_LinAlgError` because those vertices are coplanar.diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.pyindex 3e0213977..62f6c720b 100644--- a/kornia/augmentation/_3d/geometric/center_crop.py+++ b/kornia/augmentation/_3d/geometric/center_crop.py@@ -21,8 +21,9 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D+from kornia.augmentation._3d.geometric.crop import _crop_translation3dfrom kornia.constants import Resample-from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d+from kornia.geometry import crop_by_transform_mat3dclass CenterCrop3D(GeometricAugmentationBase3D):@@ -110,7 +111,7 @@ class CenterCrop3D(GeometricAugmentationBase3D):def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:- transform: torch.Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))+ transform = _crop_translation3d(params["src"].to(input), params["dst"].to(input))return transform.expand(input.shape[0], -1, -1)def apply_transform(diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.pyindex b8f83eb40..84f8dd9d3 100644--- a/kornia/augmentation/_3d/geometric/crop.py+++ b/kornia/augmentation/_3d/geometric/crop.py@@ -25,7 +25,18 @@ from kornia.augmentation import random_generator as rgfrom kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3Dfrom kornia.augmentation.utils.helpers import _pad_with_fillfrom kornia.constants import Resample-from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d+from kornia.geometry import crop_by_transform_mat3d+++def _crop_translation3d(src: torch.Tensor, dst: torch.Tensor) -> torch.Tensor:+ """Return the matrix of a crop, which only moves the first ``src`` vertex onto the first ``dst`` vertex.++ Solving the perspective system from the eight vertices instead fails for a crop with a size-1 axis, whose+ vertices are coplanar (#4705).+ """+ transform = torch.eye(4, device=src.device, dtype=src.dtype).repeat(src.shape[0], 1, 1)+ transform[:, :3, 3] = dst[:, 0] - src[:, 0]+ return transformclass RandomCrop3D(GeometricAugmentationBase3D):@@ -168,7 +179,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]) -> torch.Tensor:- transform: torch.Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))+ transform = _crop_translation3d(params["src"].to(input), params["dst"].to(input))return transform.expand(input.shape[0], -1, -1)def apply_transform(diff --git a/testing/base.py b/testing/base.pyindex f1f802b68..cb915aa7c 100644--- a/testing/base.py+++ b/testing/base.py@@ -253,6 +253,20 @@ def supports_nearest_3d_grid_sample(device: torch.device, dtype: torch.dtype) ->return _supports_kernel_probe(_nearest_3d_grid_sample_op, device.type, dtype)+def _unit_size_3d_affine_grid_op(device_type: str, dtype: torch.dtype) -> None:+ theta = _probe_zeros(device_type, dtype, 1, 3, 4)+ F.affine_grid(theta, [1, 1, 1, 2, 2], align_corners=True)+++def supports_unit_size_3d_affine_grid(device: torch.device, dtype: torch.dtype) -> bool:+ """Whether 3D ``affine_grid`` with ``align_corners=True`` can build a grid with a size-1 axis for ``dtype``.++ PyTorch builds a size-1 axis through ``torch.tensor``, which has no CPU kernel for half precision.+ Probed at runtime and cached per (device type, dtype).+ """+ return _supports_kernel_probe(_unit_size_3d_affine_grid_op, device.type, dtype)++def _reflect_padding_op(device_type: str, dtype: torch.dtype) -> None:F.pad(_probe_zeros(device_type, dtype, 1, 1, 2, 2), (1, 1, 1, 1), mode="reflect")diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.pyindex 51a524313..0766b7516 100644--- a/tests/augmentation/test_conventions_3d.py+++ b/tests/augmentation/test_conventions_3d.py@@ -23,7 +23,12 @@ import torchimport korniaimport kornia.augmentation as K-from testing.base import BaseTester, supports_bilinear_3d_grid_sample, supports_nearest_3d_grid_sample+from testing.base import (+ BaseTester,+ supports_bilinear_3d_grid_sample,+ supports_nearest_3d_grid_sample,+ supports_unit_size_3d_affine_grid,+)class Test3DAugmentationConventions(BaseTester):@@ -123,6 +128,20 @@ class Test3DAugmentationConventions(BaseTester):)self.assert_close(augmentation(volume, params=params), volume[..., 1:3, 1:4, 1:5])+ @pytest.mark.parametrize("size", [(1, 3, 4), (2, 1, 4), (2, 3, 1), (1, 1, 1)])+ def test_convention_crop3d_accepts_a_size_one_axis_4705(self, size, device, dtype):+ # A crop is a translation. Solving the perspective system from the box vertices instead raised+ # _LinAlgError here, because a size-1 axis makes the vertices coplanar.+ if not supports_bilinear_3d_grid_sample(device, dtype):+ pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")+ if not supports_unit_size_3d_affine_grid(device, dtype):+ pytest.skip("3D affine_grid cannot build a size-1 axis for this device and dtype")+ volume = torch.arange(120, device=device, dtype=dtype).reshape(1, 1, 4, 5, 6)+ for augmentation in (K.CenterCrop3D(size, p=1.0), K.RandomCrop3D(size, p=1.0)):+ output = augmentation(volume)+ x, y, z = augmentation._params["src"][0, 0].long().tolist()+ self.assert_close(output, volume[..., z : z + size[0], y : y + size[1], x : x + size[2]])+def test_convention_geometric_defaults_and_identity(self, device, dtype):if not supports_bilinear_3d_grid_sample(device, dtype):pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")