π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): improve error handling for small volumes in RandomMotionBlur3D (#5455)
Prateekshit Jaiswal96fabb5c9059
diff --git a/changelog.d/5455.fixed.md b/changelog.d/5455.fixed.mdnew file mode 100644index 000000000..ec4a626a9--- /dev/null+++ b/changelog.d/5455.fixed.md@@ -0,0 +1 @@+`RandomMotionBlur3D` now raises a `ValueError` naming the class, the drawn kernel, the border type, the axis and the input shape when a volume is too small for `border_type="reflect"` or `"circular"` along depth, height or width, as `RandomMotionBlur` does for an image, instead of letting a raw torch padding error out. The sizes it accepts are unchanged.diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.pyindex c1e3d3131..57ab846ef 100644--- a/kornia/augmentation/_3d/intensity/motion_blur.py+++ b/kornia/augmentation/_3d/intensity/motion_blur.py@@ -21,6 +21,7 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._3d.intensity.base import IntensityAugmentationBase3D+from kornia.augmentation.utils import _check_filter_min_sizefrom kornia.constants import BorderType, Resamplefrom kornia.filters import motion_blur3d@@ -75,6 +76,11 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):likely, bounds included, so ``(3, 5)`` draws ``3`` and ``5`` and ``(3, 20)`` draws ``3, 5, ..., 19``.A range holding no odd size is rounded **up** out of the requested range instead, so ``(4, 4)`` draws``5``; a reversed pair such as ``(20, 3)`` raises a ``ValueError`` at construction.+ - a volume smaller than the kernel is accepted, down to ``1 x 1 x 1``, at the default+ ``border_type="constant"`` and at ``"replicate"``. ``"reflect"`` needs each of depth, height and width+ longer than the kernel radius, and ``"circular"`` at least that long; below that both raise a+ ``ValueError`` naming the class, the drawn kernel, the axis and the input shape, as+ :class:`~kornia.augmentation.RandomMotionBlur` does for an image.- this class fixes ``p_batch=1``; its ``p`` remains the per-sample gate.Examples:@@ -150,11 +156,13 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):kernel_size = int(params["ksize_factor"].unique().item())angle = params["angle_factor"]direction = params["direction_factor"]+ border_type = self.flags["border_type"].name.lower()+ _check_filter_min_size("RandomMotionBlur3D", input, kernel_size, border_type=border_type, spatial_dims=3)return motion_blur3d(input,kernel_size,angle,direction,- self.flags["border_type"].name.lower(),+ border_type,self.flags["resample"].name.lower(),)diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex aebf9c373..eadac2525 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -575,10 +575,10 @@ class MultiprocessWrapper:#: How small an image each padding mode can filter, given the kernel extent ``k`` along that axis.-#: ``filter2d`` pads an even kernel asymmetrically -- ``(k - 1) // 2`` in front and ``k // 2``-#: behind -- so the constraint is against the wider of the two, ``k // 2``, not against the radius.-#: ``reflect`` cannot mirror a pad as wide as the axis and ``circular`` cannot wrap one wider than-#: it; ``"valid"`` is the no-padding case, where the kernel itself must fit. ``constant`` and+#: ``filter2d`` and ``filter3d`` pad an even kernel asymmetrically -- ``(k - 1) // 2`` in front and+#: ``k // 2`` behind -- so the constraint is against the wider of the two, ``k // 2``, not against the+#: radius. ``reflect`` cannot mirror a pad as wide as the axis and ``circular`` cannot wrap one wider+#: than it; ``"valid"`` is the no-padding case, where the kernel itself must fit. ``constant`` and#: ``replicate`` invent their padding and run on a 1-pixel axis._MIN_FILTERED_SIZE: Dict[str, Callable[[int], int]] = {"reflect": lambda extent: extent // 2 + 1,@@ -586,28 +586,35 @@ _MIN_FILTERED_SIZE: Dict[str, Callable[[int], int]] = {"valid": lambda extent: extent,}+#: Names of the trailing spatial axes, read from the right: a 2D filter uses the last two.+_SPATIAL_AXIS_NAMES = ("depth", "height", "width")+def _check_filter_min_size(name: str,input: torch.Tensor,- kernel_size: Union[int, Tuple[int, int], List[int]],+ kernel_size: Union[int, Tuple[int, ...], List[int]],border_type: str = "reflect",+ spatial_dims: int = 2,) -> None:"""Refuse an image the filter's padding cannot handle, naming the class and the shape.torch raises about "padding size" or "calculated padded input size" from two layers below,- which names neither the augmentation nor the image the caller passed.+ which names neither the augmentation nor the image the caller passed. ``spatial_dims`` is the+ number of trailing axes the kernel spans: 2 for an image, 3 for a volume."""- size = (kernel_size, kernel_size) if isinstance(kernel_size, int) else tuple(kernel_size)+ size = (kernel_size,) * spatial_dims if isinstance(kernel_size, int) else tuple(kernel_size)smallest = _MIN_FILTERED_SIZE.get(str(border_type).lower())if smallest is None:return- for axis, (extent, side) in enumerate(zip(size, input.shape[-2:])):+ subject, unit = ("an image", "pixel") if spatial_dims == 2 else ("a volume", "voxel")+ axes = _SPATIAL_AXIS_NAMES[-spatial_dims:]+ for axis, extent, side in zip(axes, size, input.shape[-spatial_dims:]):minimum = smallest(int(extent))if side < minimum:raise ValueError(- f"{name} cannot filter an image this small: kernel_size="+ f"{name} cannot filter {subject} this small: kernel_size="f"{tuple(int(s) for s in size)} with border_type={border_type!r} needs at least "- f"{minimum} pixel(s) along {'height' if axis == 0 else 'width'}, but the input is "+ f"{minimum} {unit}(s) along {axis}, but the input is "f"{tuple(int(s) for s in input.shape)}.")diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.pyindex 3457aeb27..ca1f6efbc 100644--- a/tests/augmentation/test_conventions_3d.py+++ b/tests/augmentation/test_conventions_3d.py@@ -30,6 +30,7 @@ from testing.base import (BaseTester,supports_bilinear_3d_grid_sample,supports_nearest_3d_grid_sample,+ supports_replicate_padding_3d,supports_unit_size_3d_affine_grid,)@@ -535,6 +536,50 @@ class Test3DAugmentationConventions(BaseTester):with pytest.raises(ValueError, match="smaller than or equal to"):K.RandomMotionBlur3D((7, 3), 35.0, 0.5)+ # The three rows of #4999: "reflect" and "circular" refuse a volume they cannot pad with a ValueError naming the+ # class and the axis, as RandomMotionBlur does for an image (#4784), and "constant" runs on it.+ @pytest.mark.parametrize(+ ("shape", "border", "kernel_size", "too_short"),+ [+ ((1, 1, 1, 8, 8), "reflect", 3, "depth"),+ ((1, 1, 1, 1, 1), "circular", 5, "depth"),+ ((1, 1, 1, 8, 8), "constant", 3, None),+ ],+ )+ def test_convention_motion_blur3d_names_the_size_it_needs_4999(+ self, device, dtype, shape, border, kernel_size, too_short+ ):+ volume = torch.rand(*shape, device=device, dtype=dtype)+ message = f"RandomMotionBlur3D cannot filter a volume this small.*along {too_short}"+ # A ranged kernel_size is checked against the size drawn for the call.+ for size in (kernel_size, (kernel_size, kernel_size)):+ augmentation = K.RandomMotionBlur3D(size, 35.0, 0.5, border_type=border, p=1.0)+ if too_short is None:+ assert augmentation(volume).shape == volume.shape+ else:+ with pytest.raises(ValueError, match=message):+ augmentation(volume)+ # "replicate" invents its padding as "constant" does, so it runs on every row too.+ if supports_replicate_padding_3d(device, dtype):+ replicate = K.RandomMotionBlur3D(kernel_size, 35.0, 0.5, border_type="replicate", p=1.0)+ assert replicate(volume).shape == volume.shape++ # Each spatial axis needs ``k // 2 + 1`` voxels under "reflect" and ``k // 2`` under "circular": a volume at+ # exactly that size runs, and one voxel fewer along depth, height or width raises, naming that axis.+ @pytest.mark.parametrize("axis", ["depth", "height", "width"])+ @pytest.mark.parametrize(("border", "bound"), [("reflect", 3), ("circular", 2)])+ def test_convention_motion_blur3d_runs_at_the_size_bound_4999(self, device, dtype, border, bound, axis):+ def volume(side: int) -> torch.Tensor:+ shape = [1, 1, 6, 6, 6]+ shape[2 + ("depth", "height", "width").index(axis)] = side+ return torch.rand(*shape, device=device, dtype=dtype)++ augmentation = K.RandomMotionBlur3D(5, 35.0, 0.5, border_type=border, p=1.0)+ at_bound = volume(bound)+ assert augmentation(at_bound).shape == at_bound.shape+ with pytest.raises(ValueError, match=rf"needs at least {bound} voxel\(s\) along {axis}"):+ augmentation(volume(bound - 1))+@pytest.mark.device_agnosticdef test_convention_only_transplantation3d_exposes_p_batch(self):import inspect