Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add Motion Blur #302 (#328)

mronta0fc33c98ce88
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 1f6ddf0e6..a355b8025 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -48,12 +48,14 @@ from kornia.filters import (
get_gaussian_kernel2d,
get_laplacian_kernel1d,
get_laplacian_kernel2d,
+ get_motion_kernel2d,
gaussian_blur2d,
laplacian,
sobel,
spatial_gradient,
box_blur,
median_blur,
+ motion_blur,
filter2D,
)
from kornia.losses import (
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.py
index c067b02ca..e56e5a812 100644
--- a/kornia/filters/__init__.py
+++ b/kornia/filters/__init__.py
@@ -4,6 +4,7 @@ from .sobel import SpatialGradient, spatial_gradient
from .sobel import Sobel, sobel
from .blur import BoxBlur, box_blur
from .median import MedianBlur, median_blur
+from .motion import MotionBlur, motion_blur
from .filter import filter2D
from .kernels import (
gaussian,
@@ -17,6 +18,7 @@ from .kernels import (
get_gaussian_kernel2d,
get_laplacian_kernel1d,
get_laplacian_kernel2d,
+ get_motion_kernel2d
)
__all__ = [
@@ -28,11 +30,13 @@ __all__ = [
"get_sobel_kernel2d",
"get_diff_kernel2d",
"gaussian_blur2d",
+ "get_motion_kernel2d",
"laplacian",
"sobel",
"spatial_gradient",
"box_blur",
"median_blur",
+ "motion_blur",
"filter2D",
"GaussianBlur2d",
"Laplacian",
@@ -40,4 +44,5 @@ __all__ = [
"Sobel",
"BoxBlur",
"MedianBlur",
+ "MotionBlur"
]
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index f4e6dae94..d37d93cde 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -3,6 +3,8 @@ from typing import Tuple, List
import torch
import torch.nn as nn
+from kornia.geometry.transform.affwarp import rotate
+
def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:
r"""Normalizes both derivative and smoothing kernel.
@@ -300,3 +302,52 @@ def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:
kernel[mid, mid] = 1 - kernel_size ** 2
kernel_2d: torch.Tensor = kernel
return kernel_2d
+
+
+def get_motion_kernel2d(ksize: int, angle: float, direction: float = 0.) -> torch.Tensor:
+ r"""Function that returns motion blur filter.
+
+ Args:
+ ksize (int): motion kernel width and height. It should be odd and positive.
+ angle (float): angle of the motion blur in degrees (anti-clockwise rotation).
+ direction (float): 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
+ uniformly (but still angled) motion blur.
+
+ Returns:
+ torch.Tensor: the motion blur kernel.
+
+ Shape:
+ - Output: :math:`(ksize, ksize)`
+
+ Examples::
+ >>> kornia.filters.get_motion_kernel2d(5, 0., 0.)
+ tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.2000, 0.2000, 0.2000, 0.2000, 0.2000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]])
+ >>> kornia.filters.get_motion_kernel2d(3, 215., -0.5)
+ tensor([[0.0000, 0.0412, 0.0732],
+ [0.1920, 0.3194, 0.0804],
+ [0.2195, 0.0743, 0.0000]])
+ """
+ if not isinstance(ksize, int) or ksize % 2 == 0 or ksize < 3:
+ raise TypeError("ksize must be an odd integer >= than 3")
+ if not isinstance(angle, float):
+ raise TypeError("angle must be a float")
+ if not isinstance(direction, float):
+ raise TypeError("direction must be a float")
+
+ kernel_size = (ksize, ksize)
+ # direction from [-1, 1] to [0, 1] range
+ direction = (torch.clamp(torch.tensor(direction), -1., 1.).item() + 1.) / 2.
+ kernel = torch.zeros(kernel_size, dtype=torch.float)
+ kernel[kernel_size[0] // 2, :] = torch.linspace(direction, 1. - direction, steps=kernel_size[0])
+ kernel = kernel.unsqueeze(0).unsqueeze(0)
+ # rotate (counterclockwise) kernel by given angle
+ kernel = rotate(kernel, torch.tensor(angle))
+ kernel = kernel[0][0]
+ kernel /= kernel.sum()
+ return kernel
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
new file mode 100644
index 000000000..8fe70a572
--- /dev/null
+++ b/kornia/filters/motion.py
@@ -0,0 +1,75 @@
+from typing import Tuple
+
+import torch
+import torch.nn as nn
+
+from kornia.filters.kernels import get_motion_kernel2d
+from kornia.filters.filter import filter2D
+
+
+class MotionBlur(nn.Module):
+ r"""Blurs a tensor using the motion filter.
+
+ Args:
+ ksize (int): motion kernel width and height. It should be odd and positive.
+ angle (float): angle of the motion blur in degrees (anti-clockwise rotation).
+ direction (float): 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
+ uniformly (but still angled) motion blur.
+ border_type (str): the padding mode to be applied before convolving.
+ The expected modes are: ``'constant'``, ``'reflect'``,
+ ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
+
+ Returns:
+ torch.Tensor: the blurred input tensor.
+
+ Shape:
+ - Input: :math:`(B, C, H, W)`
+ - Output: :math:`(B, C, H, W)`
+
+ Examples::
+ >>> input = torch.rand(2, 4, 5, 7)
+ >>> motion_blur = kornia.filters.MotionBlur(3, 35., 0.5)
+ >>> output = motion_blur(input) # 2x4x5x7
+ """
+
+ def __init__(
+ self, ksize: int, angle: float, direction: float, border_type: str = 'constant'
+ ) -> None:
+ super(MotionBlur, self).__init__()
+ self.ksize = ksize
+ self.angle: float = angle
+ self.direction: float = direction
+ assert border_type in ["constant", "reflect", "replicate", "circular"]
+ self.border_type: str = border_type
+ self.kernel: torch.Tensor = torch.unsqueeze(
+ get_motion_kernel2d(self.ksize, self.angle, self.direction),
+ dim=0
+ )
+
+ def __repr__(self) -> str:
+ return f'{self.__class__.__name__} (ksize={self.ksize}, ' \
+ f'angle={self.angle}, direction={self.direction})'
+
+ def forward(self, x: torch.Tensor): # type: ignore
+ return filter2D(x, self.kernel, self.border_type)
+
+
+######################
+# functional interface
+######################
+
+def motion_blur(
+ input: torch.Tensor,
+ ksize: int,
+ angle: float,
+ direction: float,
+ border_type: str = 'constant'
+) -> torch.Tensor:
+ r"""
+ Function that blurs a tensor using the motion filter.
+
+ See :class:`~kornia.filters.MotionBlur` for details.
+ """
+ return MotionBlur(ksize, angle, direction, border_type)(input)
diff --git a/test/filters/test_motion.py b/test/filters/test_motion.py
new file mode 100644
index 000000000..d33bf1d22
--- /dev/null
+++ b/test/filters/test_motion.py
@@ -0,0 +1,65 @@
+from typing import Tuple
+import pytest
+
+import kornia
+import kornia.testing as utils # test utils
+from test.common import device_type
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
[email protected]("ksize", [3, 11])
[email protected]("angle", [0., 360.])
[email protected]("direction", [-1., 1.])
+def test_get_motion_kernel2d(ksize, angle, direction):
+ kernel = kornia.get_motion_kernel2d(ksize, angle, direction)
+ assert kernel.shape == (ksize, ksize)
+ assert_allclose(kernel.sum(), 1.)
+
+
+class TestMotionBlur:
+ @pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
+ def test_motion_blur(self, batch_shape, device_type):
+ ksize = 5
+ angle = 200.
+ direction = 0.3
+
+ input = torch.rand(batch_shape).to(torch.device(device_type))
+ motion = kornia.filters.MotionBlur(ksize, angle, direction)
+ assert motion(input).shape == batch_shape
+
+ def test_gradcheck(self):
+ batch_shape = (2, 3, 11, 7)
+ ksize = 9
+ angle = 34.
+ direction = -0.2
+
+ input = torch.rand(batch_shape)
+ input = utils.tensor_to_gradcheck_var(input)
+ assert gradcheck(
+ kornia.motion_blur,
+ (input, ksize, angle, direction, "replicate"),
+ raise_exception=True,
+ )
+
+ @pytest.mark.skip("")
+ @pytest.mark.skip(reason="turn off all jit for a while")
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(
+ input: torch.Tensor,
+ ksize: int,
+ angle: float,
+ direction: float
+ ) -> torch.Tensor:
+ return kornia.filters.motion_blur(input, ksize, angle, direction)
+
+ img = torch.rand(2, 3, 4, 5)
+ ksize = 5
+ angle = 65.
+ direction = .1
+ actual = op_script(img, ksize, angle, direction)
+ expected = kornia.filters.motion_blur(img, ksize, angle, direction)
+ assert_allclose(actual, expected)