Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Fix] random motion blur improvments (#562)

Edgar Ribacddb41d71d90
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rst
index 1a9055f5c..51a8d0a0e 100644
--- a/docs/source/augmentation.rst
+++ b/docs/source/augmentation.rst
@@ -121,19 +121,20 @@ Example for semantic segmentation using low-level randomness control:
mask = self.jit(mask, jit_params)
return input, mask
-.. autoclass:: RandomHorizontalFlip
-.. autoclass:: RandomVerticalFlip
+.. autoclass:: CenterCrop
+.. autoclass:: ColorJitter
+.. autoclass:: Denormalize
+.. autoclass:: Normalize
+.. autoclass:: RandomAffine
+.. autoclass:: RandomCrop
.. autoclass:: RandomErasing
.. autoclass:: RandomGrayscale
-.. autoclass:: RandomAffine
+.. autoclass:: RandomHorizontalFlip
+.. autoclass:: RandomMotionBlur
.. autoclass:: RandomPerspective
-.. autoclass:: RandomRotation
-.. autoclass:: ColorJitter
-.. autoclass:: CenterCrop
-.. autoclass:: RandomCrop
.. autoclass:: RandomResizedCrop
-.. autoclass:: Normalize
-.. autoclass:: Denormalize
+.. autoclass:: RandomRotation
+.. autoclass:: RandomVerticalFlip
Functional
----------
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 3e6107353..59a5e7e0d 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
from torch.nn.functional import pad
-from kornia.constants import Resample
+from kornia.constants import Resample, BorderType
from . import functional as F
from . import random_generator as rg
from .utils import (
@@ -697,3 +697,66 @@ class RandomResizedCrop(AugmentationBase):
def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.apply_crop(input, params)
+
+
+class RandomMotionBlur(AugmentationBase):
+ r"""Blurs a tensor using the motion filter. Same transformation happens across batches.
+
+ Args:
+ kernel_size (int or Tuple[int, int]): motion kernel width and height (odd and positive).
+ If int, the kernel will have a fixed size.
+ If Tuple[int, int], it will randomly generate the value from the range.
+ angle (float or Tuple[float, float]): angle of the motion blur in degrees (anti-clockwise rotation).
+ If float, it will generate the value from (-angle, angle).
+ direction (float or Tuple[float, 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.
+ If float, it will generate the value from (-direction, direction).
+ If Tuple[int, int], it will randomly generate the value from the range.
+ border_type (int, str or kornia.BorderType): the padding mode to be applied before convolving.
+ CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT.
+
+ Shape:
+ - Input: :math:`(B, C, H, W)`
+ - Output: :math:`(B, C, H, W)`
+
+ Examples::
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 5, 5)
+ >>> motion_blur = RandomMotionBlur(3, 35., 0.5)
+ >>> motion_blur(input)
+ tensor([[[[0.2724, 0.5235, 0.3796, 0.2433, 0.2210],
+ [0.3233, 0.5494, 0.5746, 0.5407, 0.3910],
+ [0.2101, 0.3865, 0.3072, 0.2510, 0.1902],
+ [0.2973, 0.6174, 0.6530, 0.4360, 0.2797],
+ [0.3804, 0.6217, 0.5535, 0.4855, 0.4249]]]])
+ """
+
+ def __init__(
+ self, kernel_size: Union[int, Tuple[int, int]],
+ angle: Union[float, Tuple[float, float]],
+ direction: Union[float, Tuple[float, float]],
+ border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
+ return_transform: bool = False
+ ) -> None:
+ super(RandomMotionBlur, self).__init__(return_transform)
+ self.kernel_size: Union[int, Tuple[int, int]] = kernel_size
+ self.angle: Union[float, Tuple[float, float]] = angle
+ self.direction: Union[float, Tuple[float, float]] = direction
+ self.border_type: BorderType = BorderType.get(border_type)
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(kernel_size={self.kernel_size}, angle={self.angle}, " \
+ f"direction={self.direction}, border_type='{self.border_type.name.lower()}', " \
+ f"return_transform={self.return_transform})"
+
+ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ # TODO: Enable batch mode
+ return rg.motion_blur_param_generator(1, self.kernel_size, self.angle, self.direction, self.border_type)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.compute_intensity_transformation(input, params)
+
+ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.apply_motion_blur(input, params)
diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.py
index fe7a2d19c..1ca7c335e 100644
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@ -3,7 +3,7 @@ from typing import Tuple, List, Union, Dict, cast, Optional
import torch
import torch.nn as nn
-from kornia.constants import Resample, pi
+from kornia.constants import Resample, BorderType, pi
from kornia.geometry import (
get_perspective_transform,
get_rotation_matrix2d,
@@ -24,6 +24,7 @@ from kornia.color import (
adjust_gamma,
rgb_to_grayscale
)
+from kornia.filters import motion_blur
from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
from . import random_generator as rg
@@ -759,3 +760,36 @@ def apply_adjust_gamma(input: torch.Tensor, params: Dict[str, torch.Tensor]) ->
transformed = adjust_gamma(input, params['gamma_factor'].to(input.dtype))
return transformed
+
+
+def apply_motion_blur(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Perform motion blur on an image
+
+ The input image is expected to be in the range of [0, 1].
+
+ Args:
+ input (torch.Tensor): Image/Tensor to be adjusted in the shape of (\*, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['ksize_factor']: motion kernel width and height (odd and positive).
+ - params['angle_factor']: angle of the motion blur in degrees (anti-clockwise rotation).
+ - params['direction_factor']: 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.
+ - params['border_type']: the padding mode to be applied before convolving.
+ CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT.
+
+ Returns:
+ torch.Tensor: Adjusted image with the shape as the inpute (\*, C, H, W).
+
+ """
+ input = _transform_input(input)
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+
+ kernel_size: int = cast(int, params['ksize_factor'].item())
+ # TODO: this params should be at some point, learnable tensors
+ angle: float = cast(float, params['angle_factor'].item())
+ direction: float = cast(float, params['direction_factor'].item())
+ border_type: str = cast(str, BorderType(params['border_type'].item()).name.lower())
+
+ return motion_blur(input, kernel_size, angle, direction, border_type)
diff --git a/kornia/augmentation/random_generator.py b/kornia/augmentation/random_generator.py
index 009843809..3e9a520d3 100644
--- a/kornia/augmentation/random_generator.py
+++ b/kornia/augmentation/random_generator.py
@@ -4,7 +4,7 @@ import math
import torch
-from kornia.constants import Resample
+from kornia.constants import Resample, BorderType
from kornia.augmentation.utils import (
_adapted_uniform,
_check_and_bound
@@ -587,3 +587,36 @@ def center_crop_params_generator(
dst=points_dst,
interpolation=torch.tensor(Resample.BILINEAR.value),
align_corners=torch.tensor(align_corners))
+
+
+def motion_blur_param_generator(
+ batch_size: int,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: UnionFloat,
+ direction: UnionFloat,
+ border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
+ same_on_batch: bool = True
+) -> Dict[str, torch.Tensor]:
+
+ angle_bound: torch.Tensor = _check_and_bound(angle, 'angle', center=0.)
+ direction_bound: torch.Tensor = _check_and_bound(direction, 'direction', center=0., bounds=(-1, 1))
+
+ if isinstance(kernel_size, int):
+ ksize_factor = torch.tensor([kernel_size] * batch_size)
+ elif isinstance(kernel_size, tuple):
+ ksize_x, ksize_y = kernel_size
+ ksize_factor = _adapted_uniform(
+ (batch_size,), ksize_x // 2, ksize_y // 2, same_on_batch).int() * 2 + 1
+ else:
+ raise TypeError(f"Unsupported type: {type(kernel_size)}")
+
+ angle_factor = _adapted_uniform(
+ (batch_size,), angle_bound[0], angle_bound[1], same_on_batch)
+
+ direction_factor = _adapted_uniform(
+ (batch_size,), direction_bound[0], direction_bound[1], same_on_batch)
+
+ return dict(ksize_factor=ksize_factor,
+ angle_factor=angle_factor,
+ direction_factor=direction_factor,
+ border_type=torch.tensor(BorderType.get(border_type).value))
diff --git a/kornia/constants.py b/kornia/constants.py
index 7d612014b..827b053de 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -5,6 +5,7 @@ import torch
pi = torch.tensor(3.14159265358979323846)
T = TypeVar('T', bound='Resample')
+U = TypeVar('U', bound='BorderType')
class Resample(Enum):
@@ -21,3 +22,20 @@ class Resample(Enum):
if type(value) == cls:
return value # type: ignore
raise TypeError()
+
+
+class BorderType(Enum):
+ CONSTANT = 0
+ REFLECT = 1
+ REPLICATE = 2
+ CIRCULAR = 3
+
+ @classmethod
+ def get(cls, value: Union[str, int, U]) -> U: # type: ignore
+ if type(value) == str:
+ return cls[value.upper()] # type: ignore
+ if type(value) == int:
+ return cls(value) # type: ignore
+ if type(value) == cls:
+ return value # type: ignore
+ raise TypeError()
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.py
index fef0c2081..b28090fa4 100644
--- a/kornia/filters/blur.py
+++ b/kornia/filters/blur.py
@@ -64,7 +64,8 @@ class BoxBlur(nn.Module):
# functiona api
-
+# TODO: In terms of functional API, there should not be any initialization of an nn.Module.
+# This logic is reversed.
def box_blur(input: torch.Tensor,
kernel_size: Tuple[int, int],
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index d3fc43ef3..fafffa588 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -59,7 +59,8 @@ class GaussianBlur2d(nn.Module):
######################
# functional interface
######################
-
+# TODO: In terms of functional API, there should not be any initialization of an nn.Module.
+# This logic is reversed.
def gaussian_blur2d(
input: torch.Tensor,
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 56dd828d8..f9661a934 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -444,11 +444,11 @@ def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:
return kernel_2d
-def get_motion_kernel2d(ksize: int, angle: float, direction: float = 0.) -> torch.Tensor:
+def get_motion_kernel2d(kernel_size: 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.
+ kernel_size (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),
@@ -473,18 +473,20 @@ def get_motion_kernel2d(ksize: int, angle: float, direction: float = 0.) -> torc
[0.1920, 0.3194, 0.0804],
[0.2195, 0.0743, 0.0000]])
"""
- if not isinstance(ksize, int) or ksize % 2 == 0 or ksize < 3:
+ if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size < 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)
+ kernel_tuple: Tuple[int, int] = (kernel_size, kernel_size)
# 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 = torch.zeros(kernel_tuple, dtype=torch.float)
+ kernel[kernel_tuple[0] // 2, :] = torch.linspace(direction, 1. - direction, steps=kernel_tuple[0])
kernel = kernel.unsqueeze(0).unsqueeze(0)
# rotate (counterclockwise) kernel by given angle
kernel = rotate(kernel, torch.tensor(angle))
diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.py
index d24489d74..b0c2de6d4 100644
--- a/kornia/filters/laplacian.py
+++ b/kornia/filters/laplacian.py
@@ -60,7 +60,8 @@ class Laplacian(nn.Module):
######################
# functional interface
######################
-
+# TODO: In terms of functional API, there should not be any initialization of an nn.Module.
+# This logic is reversed.
def laplacian(
input: torch.Tensor,
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index 8fe70a572..cba987cc7 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -11,7 +11,7 @@ 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.
+ kernel_size (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),
@@ -35,34 +35,25 @@ class MotionBlur(nn.Module):
"""
def __init__(
- self, ksize: int, angle: float, direction: float, border_type: str = 'constant'
+ self, kernel_size: int, angle: float, direction: float, border_type: str = 'constant'
) -> None:
super(MotionBlur, self).__init__()
- self.ksize = ksize
+ self.kernel_size = kernel_size
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}, ' \
+ return f'{self.__class__.__name__} (kernel_size={self.kernel_size}, ' \
f'angle={self.angle}, direction={self.direction})'
def forward(self, x: torch.Tensor): # type: ignore
- return filter2D(x, self.kernel, self.border_type)
+ return motion_blur(x, self.kernel_size, self.angle, self.direction, self.border_type)
-######################
-# functional interface
-######################
-
def motion_blur(
input: torch.Tensor,
- ksize: int,
+ kernel_size: int,
angle: float,
direction: float,
border_type: str = 'constant'
@@ -72,4 +63,7 @@ def motion_blur(
See :class:`~kornia.filters.MotionBlur` for details.
"""
- return MotionBlur(ksize, angle, direction, border_type)(input)
+ assert border_type in ["constant", "reflect", "replicate", "circular"]
+ kernel: torch.Tensor = torch.unsqueeze(
+ get_motion_kernel2d(kernel_size, angle, direction), dim=0)
+ return filter2D(input, kernel, border_type)
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 1d36568a6..eca461b87 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -170,7 +170,8 @@ class Sobel(nn.Module):
# functiona api
-
+# TODO: In terms of functional API, there should not be any initialization of an nn.Module.
+# This logic is reversed.
def spatial_gradient(input: torch.Tensor,
mode: str = 'sobel',
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 60f6e2dcb..0c90e4668 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -11,7 +11,7 @@ import kornia
import kornia.testing as utils # test utils
from kornia.constants import pi
from kornia.augmentation import RandomHorizontalFlip, RandomVerticalFlip, ColorJitter, \
- RandomErasing, RandomGrayscale, RandomRotation, RandomCrop, RandomResizedCrop
+ RandomErasing, RandomGrayscale, RandomRotation, RandomCrop, RandomResizedCrop, RandomMotionBlur
from test.common import device
@@ -1455,3 +1455,25 @@ class TestRandomResizedCrop:
inp = torch.rand((1, 3, 3)).to(device) # 3 x 3
inp = utils.tensor_to_gradcheck_var(inp) # to var
assert gradcheck(RandomResizedCrop(size=(3, 3), scale=(1., 1.), ratio=(1., 1.)), (inp, ), raise_exception=True)
+
+
+class TestRandomMotionBlur:
+ def test_smoke(self, device):
+ f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5)
+ repr = "RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5, "\
+ "border_type='constant', return_transform=False)"
+ assert str(f) == repr
+
+ def test_gradcheck(self, device):
+ torch.manual_seed(0) # for random reproductibility
+ inp = torch.rand((1, 3, 11, 7)).to(device)
+ inp = utils.tensor_to_gradcheck_var(inp) # to var
+ # TODO: Gradcheck for param random gen failed. Suspect get_motion_kernel2d issue.
+ params = {
+ 'ksize_factor': torch.tensor(31),
+ 'angle_factor': torch.tensor(30.),
+ 'direction_factor': torch.tensor(-0.5),
+ 'border_type': torch.tensor([0]),
+ }
+ assert gradcheck(RandomMotionBlur(
+ kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5)), (inp, params), raise_exception=True)