π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): honor motion blur module parameters (#5364)
A Aswanth Raj8b8f71ac2ae2
diff --git a/changelog.d/5364.fixed.md b/changelog.d/5364.fixed.mdnew file mode 100644index 000000000..2fd792849--- /dev/null+++ b/changelog.d/5364.fixed.md@@ -0,0 +1 @@+`MotionBlur` and `MotionBlur3D` now honor `mode="bilinear"` instead of silently using nearest interpolation, and show the selected mode in their representation. `MotionBlur3D` accepts tensor and integer angles and rejects sequences whose length is not three at construction. Nearest-mode outputs and border defaults stay unchanged.diff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex 1564f0a72..eb60fa693 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -90,7 +90,7 @@ class MotionBlur(nn.Module):def __repr__(self) -> str:return (f"{self.__class__.__name__} (kernel_size={self.kernel_size}, "- f"angle={self.angle}, direction={self.direction}, border_type={self.border_type})"+ f"angle={self.angle}, direction={self.direction}, border_type={self.border_type}, mode={self.mode})")def forward(self, x: torch.Tensor) -> torch.Tensor:@@ -111,7 +111,7 @@ class MotionBlur(nn.Module):blur response. The output uses the same batch, channel, and spatiallayout as ``x``."""- return motion_blur(x, self.kernel_size, self.angle, self.direction, self.border_type)+ return motion_blur(x, self.kernel_size, self.angle, self.direction, self.border_type, mode=self.mode)class MotionBlur3D(nn.Module):@@ -119,7 +119,8 @@ class MotionBlur3D(nn.Module):Args:kernel_size: motion kernel width and height. It should be odd and positive.- angle: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.+ angle: Rotation components in degrees. A scalar sets all three components to the same value;+ a three-element sequence sets each component, and a tensor must have shape :math:`(B, 3)`.direction: forward/backward direction of the motion blur.Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a@@ -153,7 +154,7 @@ class MotionBlur3D(nn.Module):def __init__(self,kernel_size: int,- angle: float | tuple[float, float, float] | torch.Tensor,+ angle: float | tuple[float, float, float] | list[float] | torch.Tensor,direction: float | torch.Tensor,border_type: str = "replicate",mode: str = "nearest",@@ -161,12 +162,16 @@ class MotionBlur3D(nn.Module):super().__init__()self.kernel_size = kernel_sizeKORNIA_CHECK(- isinstance(angle, (torch.Tensor, float, list, tuple)),- f"Angle should be a torch.Tensor, float or a sequence of floats. Got {angle}",+ isinstance(angle, (torch.Tensor, int, float, list, tuple)),+ f"Angle should be a torch.Tensor, int, float or a sequence of floats. Got {angle}",)- if isinstance(angle, float):+ self.angle: tuple[float, float, float] | torch.Tensor+ if isinstance(angle, torch.Tensor):+ self.angle = angle+ elif isinstance(angle, (int, float)):self.angle = (angle, angle, angle)- elif isinstance(angle, (tuple, list)) and len(angle) == 3:+ else:+ KORNIA_CHECK(len(angle) == 3, f"Angle sequence must have length 3. Got {len(angle)}")self.angle = (angle[0], angle[1], angle[2])self.direction = direction@@ -176,7 +181,7 @@ class MotionBlur3D(nn.Module):def __repr__(self) -> str:return (f"{self.__class__.__name__} (kernel_size={self.kernel_size}, "- f"angle={self.angle}, direction={self.direction}, border_type={self.border_type})"+ f"angle={self.angle}, direction={self.direction}, border_type={self.border_type}, mode={self.mode})")def forward(self, x: torch.Tensor) -> torch.Tensor:@@ -196,7 +201,7 @@ class MotionBlur3D(nn.Module):Tensor with shape :math:`(B, C, D, H, W)` containing the blurredvolume. The output keeps the same dimensional order as ``x``."""- return motion_blur3d(x, self.kernel_size, self.angle, self.direction, self.border_type)+ return motion_blur3d(x, self.kernel_size, self.angle, self.direction, self.border_type, mode=self.mode)def motion_blur(diff --git a/tests/filters/test_motion.py b/tests/filters/test_motion.pyindex a7bf47b07..5b742a824 100644--- a/tests/filters/test_motion.py+++ b/tests/filters/test_motion.py@@ -20,6 +20,7 @@ import inspectimport pytestimport torch+from kornia.core.exceptions import BaseErrorfrom kornia.filters import (MotionBlur,MotionBlur3D,@@ -167,6 +168,22 @@ class TestMotionBlur(BaseTester):self.assert_close(op(img, *params), op_module(img))+ @pytest.mark.parametrize("mode", ["nearest", "bilinear"])+ @pytest.mark.parametrize("params_as_tensor", [False, True])+ def test_module_forwards_mode(self, mode, params_as_tensor, device, dtype):+ image = torch.rand(2, 2, 7, 9, device=device, dtype=dtype)+ angle, direction = 30.0, 0.3+ if params_as_tensor:+ angle = torch.tensor([30.0, 60.0], device=device, dtype=dtype)+ direction = torch.tensor([0.3, -0.5], device=device, dtype=dtype)+ actual = MotionBlur(5, angle, direction, "constant", mode)(image)+ expected = motion_blur(image, 5, angle, direction, "constant", mode)+ self.assert_close(actual, expected, rtol=0, atol=0)++ @pytest.mark.device_agnostic+ def test_repr_includes_mode(self):+ assert "mode=bilinear" in repr(MotionBlur(3, 30.0, 0.3, mode="bilinear"))+def test_python_float_parameters_preserve_float64_precision(self):image = torch.ones(1, 1, 9, 9, dtype=torch.float64)results = [@@ -350,6 +367,58 @@ class TestMotionBlur3D(BaseTester):self.assert_close(op(img, *params), op_module(img))+ @pytest.mark.parametrize("mode", ["nearest", "bilinear"])+ @pytest.mark.parametrize("angle_form", ["float", "int", "tuple", "list", "tensor"])+ def test_module_forwards_mode_and_angle(self, mode, angle_form, device, dtype):+ volume = torch.rand(2, 2, 5, 6, 7, device=device, dtype=dtype)+ direction = 0.3+ expected_angle = (10.0, 20.0, 30.0)+ if angle_form in ("float", "int"):+ angle = 35.0 if angle_form == "float" else 35+ expected_angle = (35.0, 35.0, 35.0)+ elif angle_form == "tensor":+ supports_mode = (+ supports_nearest_3d_grid_sample(device, dtype)+ if mode == "nearest"+ else supports_bilinear_3d_grid_sample(device, dtype)+ )+ if not supports_mode:+ pytest.skip(f"This device does not support {mode} interpolation for 3D grid_sample")+ angle = torch.tensor([[10.0, 20.0, 30.0], [40.0, 50.0, 60.0]], device=device, dtype=dtype)+ expected_angle = angle+ direction = torch.tensor([0.3, -0.5], device=device, dtype=dtype)+ else:+ angle = list(expected_angle) if angle_form == "list" else expected_angle+ actual = MotionBlur3D(3, angle, direction, "constant", mode)(volume)+ expected = motion_blur3d(volume, 3, expected_angle, direction, "constant", mode)+ self.assert_close(actual, expected, rtol=0, atol=0)++ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("angle", [[], [10.0, 20.0], (10.0, 20.0, 30.0, 40.0)])+ def test_module_rejects_wrong_angle_length(self, angle):+ with pytest.raises(BaseError, match="Angle sequence must have length 3"):+ MotionBlur3D(3, angle, 0.3)++ @pytest.mark.device_agnostic+ def test_repr_includes_mode(self):+ assert "mode=bilinear" in repr(MotionBlur3D(3, (10.0, 20.0, 30.0), 0.3, mode="bilinear"))++ def test_module_tensor_parameter_gradients(self, device):+ dtype = torch.float32 if device.type == "mps" else torch.float64+ if not supports_bilinear_3d_grid_sample(device, dtype):+ pytest.skip("This device does not support bilinear interpolation for 3D grid_sample")+ volume = torch.rand(2, 1, 5, 6, 7, device=device, dtype=dtype, requires_grad=True)+ angle = torch.tensor([[10.0, 20.0, 30.0], [40.0, 50.0, 60.0]], device=device, dtype=dtype)+ angle.requires_grad_()+ direction = torch.tensor([0.3, -0.5], device=device, dtype=dtype, requires_grad=True)+ actual = MotionBlur3D(3, angle, direction, "constant", "bilinear")(volume)+ expected = motion_blur3d(volume, 3, angle, direction, "constant", "bilinear")+ actual_grads = torch.autograd.grad(actual.square().sum(), (volume, angle, direction))+ expected_grads = torch.autograd.grad(expected.square().sum(), (volume, angle, direction))+ for actual_grad, expected_grad in zip(actual_grads, expected_grads):+ assert torch.isfinite(actual_grad).all()+ self.assert_close(actual_grad, expected_grad)+def test_python_float_parameters_preserve_float64_precision(self):volume = torch.ones(1, 1, 5, 6, 7, dtype=torch.float64)results = [