π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] 3D motion blur with element-wise implementations. (#713)
shijianjian07f4726a2e17
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 21135cd5f..323c823b8 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -26,6 +26,7 @@ from .augmentation3d import (RandomDepthicalFlip3D,RandomRotation3D,RandomAffine3D,+ RandomMotionBlur3D,RandomCrop3D,CenterCrop3D,RandomEqualize3D@@ -66,6 +67,7 @@ __all__ = ["RandomVerticalFlip3D","RandomHorizontalFlip3D","RandomRotation3D",+ "RandomMotionBlur3D","RandomAffine3D","RandomCrop3D","CenterCrop3D",diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex 72745c8d1..f99477a82 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -742,15 +742,13 @@ class RandomResizedCrop(AugmentationBase2D):class RandomMotionBlur(AugmentationBase2D):- r"""Blurs a tensor image or batch of tensor images using a motion filter.-- The same transformation can be applied across different batches.+ r"""Perform motion blur on 2D images (4D tensor).Args:p (float): probability of applying the transformation. Default value is 0.5.- kernel_size (int or Tuple[int, int]): motion kernel width and height (odd and positive).+ kernel_size (int or Tuple[int, int]): motion kernel size (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.+ If Tuple[int, int], it will randomly generate the value from the range batch-wisely.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.@@ -783,9 +781,9 @@ class RandomMotionBlur(AugmentationBase2D):angle: Union[torch.Tensor, float, Tuple[float, float]],direction: Union[torch.Tensor, float, Tuple[float, float]],border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,- return_transform: bool = False, p: float = 0.5+ return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5) -> None:- super(RandomMotionBlur, self).__init__(p=p, return_transform=return_transform, same_on_batch=True)+ super(RandomMotionBlur, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)self.kernel_size: Union[int, Tuple[int, int]] = kernel_sizeangle = cast(torch.Tensor, angle) if isinstance(angle, torch.Tensor) else torch.tensor(angle)@@ -805,8 +803,8 @@ class RandomMotionBlur(AugmentationBase2D):return self.__class__.__name__ + f"({repr}, {super().__repr__()})"def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:- # TODO: Enable batch mode- return rg.random_motion_blur_generator(1, self.kernel_size, self.angle, self.direction)+ return rg.random_motion_blur_generator(+ batch_shape[0], self.kernel_size, self.angle, self.direction, self.same_on_batch)def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.compute_intensity_transformation(input)diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.pyindex 299cf9255..ff2d47903 100644--- a/kornia/augmentation/augmentation3d.py+++ b/kornia/augmentation/augmentation3d.py@@ -8,6 +8,7 @@ from .base import AugmentationBase3Dfrom . import functional as Ffrom . import random_generator as rgfrom .utils import (+ _range_bound,_tuple_range_reader,_singular_range_check)@@ -374,6 +375,96 @@ class RandomRotation3D(AugmentationBase3D):return F.apply_rotation3d(input, params, self.flags)+class RandomMotionBlur3D(AugmentationBase3D):+ r"""Perform motion blur on 3D volumes (5D tensor).++ Args:+ p (float): probability of applying the transformation. Default value is 0.5.+ kernel_size (int or Tuple[int, int]): motion kernel size (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 batch-wisely.+ angle (float or tuple or list): Range of degrees to select from.+ If angle is a number, then yaw, pitch, roll will be generated from the range of (-angle, +angle).+ If angle is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).+ If angle is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)+ and (-c, c).+ If angle is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from+ (a, b), (m, n) and (x, y).+ Set to 0 to deactivate rotations.+ 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, D, H, W)`+ - Output: :math:`(B, C, D, H, W)`++ Examples:+ >>> rng = torch.manual_seed(0)+ >>> input = torch.rand(1, 1, 3, 5, 5)+ >>> motion_blur = RandomMotionBlur3D(3, 35., 0.5, p=1.)+ >>> motion_blur(input)+ tensor([[[[[ 0.1654, 5.0626, 3.7446, 6.8393, 3.5563],+ [-5.0999, 2.1964, 2.4311, -1.8043, 1.4908],+ [-3.2720, -2.1332, 2.1459, 1.7491, 1.3186],+ [-2.6045, 5.2450, 6.0367, 1.0320, 6.7205],+ [-4.5962, -5.2259, -0.9809, -1.6601, 0.1398]],+ <BLANKLINE>+ [[ 0.1843, 2.6303, 7.0769, 1.3952, 2.1699],+ [-6.4852, 0.3011, 0.3557, 4.5564, 5.5316],+ [-6.4329, 2.8427, 0.2914, 3.6307, 0.4988],+ [-1.2635, -4.5109, 1.3771, 0.8912, 2.1555],+ [-1.6038, -3.7698, 0.0352, -0.8663, 0.1607]],+ <BLANKLINE>+ [[ 0.2733, 1.8909, 4.7292, 1.0408, 1.4417],+ [-6.8248, 0.8740, 1.4280, -4.1784, 5.0158],+ [-3.8589, 2.7687, 2.9419, 3.2143, 6.3996],+ [-4.7014, -0.3668, -1.8947, 0.1953, 7.2572],+ [-3.5506, -4.1522, -5.3692, -6.4713, 0.3117]]]]])+ """++ def __init__(+ self, kernel_size: Union[int, Tuple[int, int]],+ angle: Union[torch.Tensor, float, Tuple[float, float]],+ direction: Union[torch.Tensor, float, Tuple[float, float]],+ border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,+ return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5+ ) -> None:+ super(RandomMotionBlur3D, self).__init__(+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)+ self.kernel_size: Union[int, Tuple[int, int]] = kernel_size++ self.angle: torch.Tensor = _tuple_range_reader(angle, 3)++ direction = \+ cast(torch.Tensor, direction) if isinstance(direction, torch.Tensor) else torch.tensor(direction)+ self.direction = _range_bound(direction, 'direction', center=0., bounds=(-1, 1))+ self.border_type = BorderType.get(border_type)+ self.flags: Dict[str, torch.Tensor] = {+ "border_type": torch.tensor(self.border_type.value)+ }++ def __repr__(self) -> str:+ repr = f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}, " +\+ f"border_type='{self.border_type.name.lower()}'"+ return self.__class__.__name__ + f"({repr}, {super().__repr__()})"++ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:+ return rg.random_motion_blur_generator3d(+ batch_shape[0], self.kernel_size, self.angle, self.direction, self.same_on_batch)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_intensity_transformation3d(input)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.apply_motion_blur3d(input, params, self.flags)++class CenterCrop3D(AugmentationBase3D):r"""Crops a given image tensor at the center.diff --git a/kornia/augmentation/functional/functional.py b/kornia/augmentation/functional/functional.pyindex 62fe20aba..acc9e3b40 100644--- a/kornia/augmentation/functional/functional.py+++ b/kornia/augmentation/functional/functional.py@@ -829,7 +829,7 @@ def apply_motion_blur(input: torch.Tensor, params: Dict[str, torch.Tensor],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())+ kernel_size: int = cast(int, params['ksize_factor'].unique().item())angle = params['angle_factor']direction = params['direction_factor']border_type: str = cast(str, BorderType(flags['border_type'].item()).name.lower())diff --git a/kornia/augmentation/functional/functional3d.py b/kornia/augmentation/functional/functional3d.pyindex 61fdbae83..010e831e1 100644--- a/kornia/augmentation/functional/functional3d.py+++ b/kornia/augmentation/functional/functional3d.py@@ -25,6 +25,7 @@ from ..utils import (_transform_input3d,_validate_input_dtype)+from kornia.filters import motion_blur3dfrom .__temp__ import __deprecation_warning@@ -360,15 +361,45 @@ def compute_rotate_tranformation3d(input: torch.Tensor, params: Dict[str, torch.return trans_mat-def apply_crop3d(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]) -> torch.Tensor:- r"""Apply cropping by src bounding box and dst bounding box.+def apply_motion_blur3d(input: torch.Tensor, params: Dict[str, torch.Tensor],+ flags: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Perform motion blur on an image.- Order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,- back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in x, y, z order.+ The input image is expected to be in the range of [0, 1].Args:input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).params (Dict[str, torch.Tensor]):+ - params['ksize_factor']: motion kernel width and height (odd and positive).+ - params['angle_factor']: yaw, pitch and roll range of the motion blur in degrees :math:`(B, 3)`.+ - 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.+ flags (Dict[str, torch.Tensor]):+ - flags['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_input3d(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])++ kernel_size: int = cast(int, params['ksize_factor'].unique().item())+ angle = params['angle_factor']+ direction = params['direction_factor']+ border_type: str = cast(str, BorderType(flags['border_type'].item()).name.lower())++ return motion_blur3d(input, kernel_size, angle, direction, border_type)+++def apply_crop3d(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]) -> torch.Tensor:+ r"""Apply cropping by src bounding box and dst bounding box.++ Order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,+ back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in x, y, z order.- params['src']: The applied cropping src matrix :math: `(*, 8, 3)`.- params['dst']: The applied cropping dst matrix :math: `(*, 8, 3)`.flags (Dict[str, torch.Tensor]):diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.pyindex 3f9f9196e..8d184b350 100644--- a/kornia/augmentation/random_generator/random_generator.py+++ b/kornia/augmentation/random_generator/random_generator.py@@ -515,13 +515,13 @@ def random_motion_blur_generator(kernel_size: Union[int, Tuple[int, int]],angle: torch.Tensor,direction: torch.Tensor,- same_on_batch: bool = True+ same_on_batch: bool = False) -> Dict[str, torch.Tensor]:r"""Get parameters for motion blur.Args:batch_size (int): the tensor batch size.- kernel_size (int or (int, int)): motion kernel width and height (odd and positive).+ kernel_size (int or (int, int)): motion kernel size (odd and positive) or range.angle (torch.Tensor): angle of the motion blur in degrees (anti-clockwise rotation).direction (torch.Tensor): forward/backward direction of the motion blur.Lower values towards -1.0 will point the motion blur towards the back (with@@ -538,9 +538,9 @@ def random_motion_blur_generator(if isinstance(kernel_size, int):ksize_factor = torch.tensor([kernel_size] * batch_size)elif isinstance(kernel_size, tuple):- ksize_x, ksize_y = kernel_size+ # kernel_size is fixed across the batchksize_factor = _adapted_uniform(- (batch_size,), ksize_x // 2, ksize_y // 2, same_on_batch).int() * 2 + 1+ (batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1else:raise TypeError(f"Unsupported type: {type(kernel_size)}")diff --git a/kornia/augmentation/random_generator/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.pyindex 3fee737f5..61f8a9785 100644--- a/kornia/augmentation/random_generator/random_generator3d.py+++ b/kornia/augmentation/random_generator/random_generator3d.py@@ -131,6 +131,51 @@ def random_affine_generator3d(szy=szy)+def random_motion_blur_generator3d(+ batch_size: int,+ kernel_size: Union[int, Tuple[int, int]],+ angle: torch.Tensor,+ direction: torch.Tensor,+ same_on_batch: bool = False+) -> Dict[str, torch.Tensor]:+ r"""Get parameters for motion blur.++ Args:+ batch_size (int): the tensor batch size.+ kernel_size (int or (int, int)): motion kernel size (odd and positive) or range.+ angle (torch.Tensor): yaw, pitch and roll range of the motion blur in degrees :math:`(3, 2)`.+ direction (torch.Tensor): 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.+ same_on_batch (bool): apply the same transformation across the batch. Default: False.++ Returns:+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.+ """+ if isinstance(kernel_size, int):+ ksize_factor = torch.tensor([kernel_size] * batch_size)+ elif isinstance(kernel_size, tuple):+ # kernel_size is fixed across the batch+ ksize_factor = _adapted_uniform(+ (batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1+ else:+ raise TypeError(f"Unsupported type: {type(kernel_size)}")++ assert angle.shape == torch.Size([3, 2]), f"'angle' must be the shape of (3, 2). Got {angle.shape}."+ yaw = _adapted_uniform((batch_size,), angle[0][0], angle[0][1], same_on_batch)+ pitch = _adapted_uniform((batch_size,), angle[1][0], angle[1][1], same_on_batch)+ roll = _adapted_uniform((batch_size,), angle[2][0], angle[2][1], same_on_batch)+ angle_factor = torch.stack([yaw, pitch, roll], dim=1)++ direction_factor = _adapted_uniform(+ (batch_size,), direction[0], direction[1], same_on_batch)++ return dict(ksize_factor=ksize_factor,+ angle_factor=angle_factor,+ direction_factor=direction_factor)++def center_crop_generator3d(batch_size: int,depth: int,diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.pyindex 877e60959..ad1424331 100644--- a/kornia/augmentation/utils/param_validation.py+++ b/kornia/augmentation/utils/param_validation.py@@ -9,7 +9,7 @@ def _range_bound(factor: Union[torch.Tensor, float, Tuple[float, float], List[flr"""Check inputs and compute the corresponding factor bounds"""if not isinstance(factor, (torch.Tensor)):- factor = torch.tensor(factor)+ factor = torch.tensor(factor, dtype=torch.float32)factor_bound: torch.Tensorif factor.dim() == 0:@@ -20,7 +20,7 @@ def _range_bound(factor: Union[torch.Tensor, float, Tuple[float, float], List[fl# Note: I personally think throw an error will be better than a coarse clamp.factor_bound = torch.tensor([center - factor, center + factor], dtype=torch.float32).clamp(bounds[0], bounds[1])else:- factor_bound = factor+ factor_bound = factor.to(dtype=torch.float32)if check is not None:if check == 'joint':diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.pyindex 28d094aab..acbf935d1 100644--- a/kornia/filters/__init__.py+++ b/kornia/filters/__init__.py@@ -4,7 +4,7 @@ from .sobel import SpatialGradient, spatial_gradient, SpatialGradient3d, spatialfrom .sobel import Sobel, sobelfrom .blur import BoxBlur, box_blurfrom .median import MedianBlur, median_blur-from .motion import MotionBlur, motion_blur+from .motion import MotionBlur, MotionBlur3D, motion_blur, motion_blur3dfrom .filter import filter2D, filter3Dfrom .kernels import (gaussian,@@ -39,6 +39,7 @@ __all__ = ["box_blur","median_blur","motion_blur",+ "motion_blur3d","filter2D","filter3D","GaussianBlur2d",@@ -48,6 +49,7 @@ __all__ = ["BoxBlur","MedianBlur","MotionBlur",+ "MotionBlur3D","SpatialGradient3d","spatial_gradient3d",]diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex dc256fb49..1fd94731f 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -33,7 +33,7 @@ def compute_padding(kernel_size: List[int]) -> List[int]:def filter2D(input: torch.Tensor, kernel: torch.Tensor,border_type: str = 'reflect',normalized: bool = False) -> torch.Tensor:- r"""Function that convolves a tensor with a 2d kernel.+ r"""Convolve a tensor with a 2d kernel.The function applies a given kernel to a tensor. The kernel is appliedindependently at each depth channel of the tensor. Before applying the@@ -44,7 +44,7 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,input (torch.Tensor): the input tensor with shape of:math:`(B, C, H, W)`.kernel (torch.Tensor): the kernel to be convolved with the input- tensor. The kernel shape must be :math:`(1, kH, kW)`.+ tensor. The kernel shape must be :math:`(1, kH, kW)` or :math:`(B, kH, kW)`.border_type (str): the padding mode to be applied before convolving.The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``. Default: ``'reflect'``.@@ -86,23 +86,31 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,# prepare kernelb, c, h, w = input.shape- tmp_kernel: torch.Tensor = kernel[None].type_as(input)+ tmp_kernel: torch.Tensor = kernel.unsqueeze(1).to(input)if normalized:tmp_kernel = normalize_kernel2d(tmp_kernel)+ tmp_kernel = tmp_kernel.expand(-1, c, -1, -1)+# pad the input tensorheight, width = tmp_kernel.shape[-2:]padding_shape: List[int] = compute_padding([height, width])input_pad: torch.Tensor = F.pad(input, padding_shape, mode=border_type)- return F.conv2d(input_pad, tmp_kernel.expand(c, -1, -1, -1), groups=c, padding=0, stride=1)+ # kernel and input tensor reshape to align element-wise or batch-wise params+ tmp_kernel = tmp_kernel.reshape(-1, 1, height, width)+ input_pad = input_pad.view(-1, tmp_kernel.size(0), input_pad.size(-2), input_pad.size(-1))++ # convolve the tensor with the kernel.+ output = F.conv2d(input_pad, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)+ return output.view(b, c, h, w)def filter3D(input: torch.Tensor, kernel: torch.Tensor,border_type: str = 'replicate',normalized: bool = False) -> torch.Tensor:- r"""Function that convolves a tensor with a 3d kernel.+ r"""Convolve a tensor with a 3d kernel.The function applies a given kernel to a tensor. The kernel is appliedindependently at each depth channel of the tensor. Before applying the@@ -113,7 +121,7 @@ def filter3D(input: torch.Tensor, kernel: torch.Tensor,input (torch.Tensor): the input tensor with shape of:math:`(B, C, D, H, W)`.kernel (torch.Tensor): the kernel to be convolved with the input- tensor. The kernel shape must be :math:`(1, kD, kH, kW)`.+ tensor. The kernel shape must be :math:`(1, kD, kH, kW)` or :math:`(B, kD, kH, kW)`.border_type (str): the padding mode to be applied before convolving.The expected modes are: ``'constant'``,``'replicate'`` or ``'circular'``. Default: ``'replicate'``.@@ -177,17 +185,24 @@ def filter3D(input: torch.Tensor, kernel: torch.Tensor,# prepare kernelb, c, d, h, w = input.shape- tmp_kernel: torch.Tensor = kernel[None].type_as(input)+ tmp_kernel: torch.Tensor = kernel.unsqueeze(1).to(input)if normalized:bk, dk, hk, wk = kernel.shapetmp_kernel = normalize_kernel2d(tmp_kernel.view(- bk, dk, hk * wk)).view_as(kernel)+ bk, dk, hk * wk)).view_as(tmp_kernel)++ tmp_kernel = tmp_kernel.expand(-1, c, -1, -1, -1)# pad the input tensordepth, height, width = tmp_kernel.shape[-3:]padding_shape: List[int] = compute_padding([depth, height, width])input_pad: torch.Tensor = F.pad(input, padding_shape, mode=border_type)+ # kernel and input tensor reshape to align element-wise or batch-wise params+ tmp_kernel = tmp_kernel.reshape(-1, 1, depth, height, width)+ input_pad = input_pad.view(-1, tmp_kernel.size(0), input_pad.size(-3), input_pad.size(-2), input_pad.size(-1))+# convolve the tensor with the kernel.- return F.conv3d(input_pad, tmp_kernel.expand(c, -1, -1, -1, -1), groups=c, padding=0, stride=1)+ output = F.conv3d(input_pad, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)+ return output.view(b, c, d, h, w)diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 79c46678d..5fd71b33c 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -3,7 +3,7 @@ from typing import Tuple, List, Union, castimport torchimport torch.nn as nn-from kornia.geometry.transform.affwarp import rotate+from kornia.geometry.transform.affwarp import rotate, rotate3ddef normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:@@ -446,7 +446,7 @@ def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],direction: Union[torch.Tensor, float] = 0.) -> torch.Tensor:- r"""Function that returns motion blur filter.+ r"""Return 2D motion blur filter.Args:kernel_size (int): motion kernel width and height. It should be odd and positive.@@ -482,7 +482,7 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],angle = cast(torch.Tensor, angle)if angle.dim() == 0:- angle = angle.unsqueeze(dim=0)+ angle = angle.unsqueeze(0)assert angle.dim() == 1, f"angle must be a 1-dim tensor. Got {angle}."if not isinstance(direction, torch.Tensor):@@ -490,17 +490,94 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],direction = cast(torch.Tensor, direction)if direction.dim() == 0:- direction = direction.unsqueeze(dim=0)+ direction = direction.unsqueeze(0)assert direction.dim() == 1, f"direction must be a 1-dim tensor. Got {direction}."+ assert direction.size(0) == angle.size(0), \+ f"direction and angle must have the same length. Got {direction} and {angle}."+kernel_tuple: Tuple[int, int] = (kernel_size, kernel_size)# direction from [-1, 1] to [0, 1] range- direction = (torch.clamp(direction, -1., 1.).item() + 1.) / 2.- 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)+ direction = (torch.clamp(direction, -1., 1.) + 1.) / 2.+ kernel = torch.zeros((direction.size(0), *kernel_tuple), dtype=torch.float)++ # Element-wise linspace+ kernel[:, kernel_tuple[0] // 2, :] = torch.stack(+ [(direction - (1 / (kernel_tuple[0] - 1)) * i) for i in range(kernel_tuple[0])], dim=-1)+ kernel = kernel.unsqueeze(1)+ # rotate (counterclockwise) kernel by given angle+ kernel = rotate(kernel, angle, mode='nearest', align_corners=True)+ kernel = kernel[:, 0]+ kernel = kernel / kernel.sum(dim=(1, 2), keepdim=True)++ return kernel+++def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[float, float, float]],+ direction: Union[torch.Tensor, float] = 0.) -> torch.Tensor:+ r"""Return 3D motion blur filter.++ Args:+ kernel_size (int): motion kernel width, height and depth. It should be odd and positive.+ angle (tensor or float): Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.+ If tensor, it must be :math:`(B, 3)`.+ 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(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, torch.Tensor):+ angle = torch.tensor([angle])++ angle = cast(torch.Tensor, angle)+ if angle.dim() == 1:+ angle = angle.unsqueeze(0)+ assert len(angle.shape) == 2 and angle.size(1) == 3, f"angle must be (B, 3). Got {angle}."++ if not isinstance(direction, torch.Tensor):+ direction = torch.tensor([direction])++ direction = cast(torch.Tensor, direction)+ if direction.dim() == 0:+ direction = direction.unsqueeze(0)+ assert direction.dim() == 1, f"direction must be a 1-dim tensor. Got {direction}."++ assert direction.size(0) == angle.size(0), \+ f"direction and angle must have the same length. Got {direction} and {angle}."++ kernel_tuple: Tuple[int, int, int] = (kernel_size, kernel_size, kernel_size)+ # direction from [-1, 1] to [0, 1] range+ direction = (torch.clamp(direction, -1., 1.) + 1.) / 2.+ kernel = torch.zeros((direction.size(0), *kernel_tuple), dtype=torch.float)++ # Element-wise linspace+ kernel[:, kernel_tuple[0] // 2, kernel_tuple[0] // 2, :] = torch.stack(+ [(direction - (1 / (kernel_tuple[0] - 1)) * i) for i in range(kernel_tuple[0])], dim=-1)+ kernel = kernel.unsqueeze(1)# rotate (counterclockwise) kernel by given angle- kernel = rotate(kernel, angle)- kernel = kernel[0][0]- kernel = kernel / kernel.sum()+ kernel = rotate3d(kernel, angle[:, 0], angle[:, 1], angle[:, 2], mode='nearest', align_corners=True)+ kernel = kernel[:, 0]+ kernel = kernel / kernel.sum(dim=(1, 2, 3), keepdim=True)+return kerneldiff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex ca35b7720..628e7f97a 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -3,12 +3,12 @@ from typing import Tuple, Unionimport torchimport torch.nn as nn-from kornia.filters.kernels import get_motion_kernel2d-from kornia.filters.filter import filter2D+from kornia.filters.kernels import get_motion_kernel2d, get_motion_kernel3d+from kornia.filters.filter import filter2D, filter3Dclass MotionBlur(nn.Module):- r"""Blurs a tensor using the motion filter.+ r"""Blur 2D images (4D tensor) using the motion filter.Args:kernel_size (int): motion kernel width and height. It should be odd and positive.@@ -17,9 +17,8 @@ class MotionBlur(nn.Module):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 auniformly (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'``.+ border_type (str): the padding mode to be applied before convolving. The expected modes are:+ ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'constant'``.Returns:torch.Tensor: the blurred input tensor.@@ -28,9 +27,9 @@ class MotionBlur(nn.Module):- Input: :math:`(B, C, H, W)`- Output: :math:`(B, C, H, W)`- Examples::+ Examples:>>> input = torch.rand(2, 4, 5, 7)- >>> motion_blur = kornia.filters.MotionBlur(3, 35., 0.5)+ >>> motion_blur = MotionBlur(3, 35., 0.5)>>> output = motion_blur(input) # 2x4x5x7"""@@ -45,12 +44,62 @@ 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})'+ f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'def forward(self, x: torch.Tensor): # type: ignorereturn motion_blur(x, self.kernel_size, self.angle, self.direction, self.border_type)+class MotionBlur3D(nn.Module):+ r"""Blur 3D volumes (5D tensor) using the motion filter.++ Args:+ kernel_size (int): motion kernel width and height. It should be odd and positive.+ angle (float or tuple): Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.+ 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: ``'constant'``.++ Returns:+ torch.Tensor: the blurred input tensor.++ Shape:+ - Input: :math:`(B, C, D, H, W)`+ - Output: :math:`(B, C, D, H, W)`++ Examples:+ >>> input = torch.rand(2, 4, 5, 7, 9)+ >>> motion_blur = MotionBlur3D(3, 35., 0.5)+ >>> output = motion_blur(input) # 2x4x5x7x9+ """++ def __init__(+ self, kernel_size: int, angle: Union[float, Tuple[float, float, float]],+ direction: float, border_type: str = 'constant'+ ) -> None:+ super(MotionBlur3D, self).__init__()+ self.kernel_size = kernel_size+ self.angle: Tuple[float, float, float]+ if isinstance(angle, float):+ self.angle = (angle, angle, angle)+ elif isinstance(angle, (tuple, list)) and len(angle) == 3:+ self.angle = angle+ else:+ raise ValueError(f"Expect angle to be either a float or a tuple of floats. Got {angle}.")+ self.direction: float = direction+ self.border_type: str = border_type++ 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})'++ def forward(self, x: torch.Tensor): # type: ignore+ return motion_blur3d(x, self.kernel_size, self.angle, self.direction, self.border_type)++def motion_blur(input: torch.Tensor,kernel_size: int,@@ -58,12 +107,72 @@ def motion_blur(direction: Union[float, torch.Tensor],border_type: str = 'constant') -> torch.Tensor:- r"""- Function that blurs a tensor using the motion filter.+ r"""Perform motion blur on 2D images (4D tensor).++ Args:+ input (tensor): the input tensor with shape :math:`(B, C, H, W)`.+ kernel_size (int): motion kernel width and height. It should be odd and positive.+ angle (tensor, float): angle of the motion blur in degrees (anti-clockwise rotation).+ If tensor, it must be :math:`(B,)`.+ direction (tensor or 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 tensor, it must be :math:`(B,)`.+ border_type (str): the padding mode to be applied before convolving. The expected modes are:+ ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'constant'``.See :class:`~kornia.filters.MotionBlur` for details.++ Example:+ >>> input = torch.randn(1, 3, 80, 90).repeat(2, 1, 1, 1)+ >>> # perform exact motion blur accross the batch+ >>> out_1 = motion_blur(input, 5, 90., 1)+ >>> torch.allclose(out_1[0], out_1[1])+ True+ >>> # perform element-wise motion blur accross the batch+ >>> out_1 = motion_blur(input, 5, torch.tensor([90., 180,]), torch.tensor([1, -1]))+ >>> torch.allclose(out_1[0], out_1[1])+ False"""assert border_type in ["constant", "reflect", "replicate", "circular"]- kernel: torch.Tensor = torch.unsqueeze(- get_motion_kernel2d(kernel_size, angle, direction), dim=0)+ kernel: torch.Tensor = get_motion_kernel2d(kernel_size, angle, direction)return filter2D(input, kernel, border_type)+++def motion_blur3d(+ input: torch.Tensor,+ kernel_size: int,+ angle: Union[Tuple[float, float, float], torch.Tensor],+ direction: Union[float, torch.Tensor],+ border_type: str = 'constant'+) -> torch.Tensor:+ r"""Perform motion blur on 3D volumes (5D tensor).++ Args:+ input (tensor): the input tensor with shape :math:`(B, C, D, H, W)`.+ kernel_size (int): motion kernel width, height and depth. It should be odd and positive.+ angle (tensor or tuple): Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.+ If tensor, it must be :math:`(B, 3)`.+ direction (tensor or 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 tensor, it must be :math:`(B,)`.+ border_type (str): the padding mode to be applied before convolving. The expected modes are:+ ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'constant'``.++ Example:+ >>> input = torch.randn(1, 3, 120, 80, 90).repeat(2, 1, 1, 1, 1)+ >>> # perform exact motion blur accross the batch+ >>> out_1 = motion_blur3d(input, 5, (0., 90., 90.), 1)+ >>> torch.allclose(out_1[0], out_1[1])+ True+ >>> # perform element-wise motion blur accross the batch+ >>> out_1 = motion_blur3d(input, 5, torch.tensor([[0., 90., 90.], [90., 180., 0.]]), torch.tensor([1, -1]))+ >>> torch.allclose(out_1[0], out_1[1])+ False+ """+ assert border_type in ["constant", "reflect", "replicate", "circular"]+ kernel: torch.Tensor = get_motion_kernel3d(kernel_size, angle, direction)+ return filter3D(input, kernel, border_type)diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex 57907863b..7458daa16 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -243,8 +243,11 @@ def rotate3d(tensor: torch.Tensor, yaw: torch.Tensor, pitch: torch.Tensor, roll:raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))if not torch.is_tensor(yaw):- raise TypeError("Input angle type is not a torch.Tensor. Got {}"- .format(type(yaw)))+ raise TypeError("yaw is not a torch.Tensor. Got {}".format(type(yaw)))+ if not torch.is_tensor(pitch):+ raise TypeError("pitch is not a torch.Tensor. Got {}".format(type(pitch)))+ if not torch.is_tensor(roll):+ raise TypeError("roll is not a torch.Tensor. Got {}".format(type(roll)))if center is not None and not torch.is_tensor(center):raise TypeError("Input center type is not a torch.Tensor. Got {}".format(type(center)))diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex 91b30adf2..b86ee50aa 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -20,8 +20,7 @@ from kornia.augmentation import (RandomGrayscale,RandomRotation,RandomCrop,- RandomResizedCrop,- RandomMotionBlur+ RandomResizedCrop)@@ -1570,29 +1569,6 @@ class TestRandomResizedCrop:size=(3, 3), scale=(1., 1.), ratio=(1., 1.)), (inp, ), raise_exception=True)-class TestRandomMotionBlur:- def test_smoke(self):- f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5)- repr = "RandomMotionBlur(kernel_size=(3, 5), angle=tensor([10, 30]), direction=tensor([-0.5000, 0.5000]), "\- "border_type='constant', p=0.5, p_batch=1.0, same_on_batch=True, return_transform=False)"- assert str(f) == repr-- def test_gradcheck(self, device, dtype):- torch.manual_seed(0) # for random reproductibility- inp = torch.rand((1, 3, 11, 7), device=device, dtype=dtype)- inp = utils.tensor_to_gradcheck_var(inp) # to var- # TODO: Gradcheck for param random gen failed. Suspect get_motion_kernel2d issue.- params = {- 'batch_prob': torch.tensor([True]),- '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), p=1.0), (inp, params), raise_exception=True)--class TestRandomEqualize:def test_smoke(self, device, dtype):f = RandomEqualize(p=0.5)diff --git a/test/augmentation/test_motionblur.py b/test/augmentation/test_motionblur.pynew file mode 100644index 000000000..77b57e3ed--- /dev/null+++ b/test/augmentation/test_motionblur.py@@ -0,0 +1,107 @@+from typing import Union, Tuple++import pytest+import torch+import torch.nn as nn++from torch.testing import assert_allclose+from torch.autograd import gradcheck++import kornia+import kornia.testing as utils # test utils+from kornia.augmentation import (+ RandomMotionBlur,+ RandomMotionBlur3D,+)+++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=tensor([10., 30.]), direction=tensor([-0.5000, 0.5000]), "\+ "border_type='constant', p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)"+ assert str(f) == repr++ @pytest.mark.parametrize("same_on_batch", [True, False])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("p", [0., 1.])+ def test_random_motion_blur(self, same_on_batch, return_transform, p, device, dtype):+ f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5,+ same_on_batch=same_on_batch, return_transform=return_transform, p=p)+ input = torch.randn(1, 3, 5, 6).repeat(2, 1, 1, 1)++ output = f(input)++ if return_transform:+ assert len(output) == 2, f"must return a length 2 tuple if return_transform is True. Got {len(output)}."+ identity = kornia.eye_like(3, input)+ output, mat = output+ assert_allclose(mat, identity, rtol=1e-4, atol=1e-4)++ if same_on_batch:+ assert_allclose(output[0], output[1], rtol=1e-4, atol=1e-4)+ elif p == 0:+ assert_allclose(output, input, rtol=1e-4, atol=1e-4)+ else:+ assert not torch.allclose(output[0], output[1], rtol=1e-4, atol=1e-4)++ 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 = {+ 'batch_prob': torch.tensor([True]),+ '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), p=1.0), (inp, params), raise_exception=True)+++class TestRandomMotionBlur3D:+ def test_smoke(self, device, dtype):+ f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5)+ repr = "RandomMotionBlur3D(kernel_size=(3, 5), angle=tensor([[10., 30.],"\+ "\n [10., 30.],\n [10., 30.]]), direction=tensor([-0.5000, 0.5000]), " \+ "border_type='constant', p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)"+ assert str(f) == repr++ @pytest.mark.parametrize("same_on_batch", [True, False])+ @pytest.mark.parametrize("return_transform", [True, False])+ @pytest.mark.parametrize("p", [0., 1.])+ def test_random_motion_blur(self, same_on_batch, return_transform, p, device, dtype):+ f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5,+ same_on_batch=same_on_batch, return_transform=return_transform, p=p)+ input = torch.randn(1, 3, 5, 6, 7).repeat(2, 1, 1, 1, 1)++ output = f(input)++ if return_transform:+ assert len(output) == 2, f"must return a length 2 tuple if return_transform is True. Got {len(output)}."+ identity = kornia.eye_like(4, input)+ output, mat = output+ assert_allclose(mat, identity, rtol=1e-4, atol=1e-4)++ if same_on_batch:+ assert_allclose(output[0], output[1], rtol=1e-4, atol=1e-4)+ elif p == 0:+ assert_allclose(output, input, rtol=1e-4, atol=1e-4)+ else:+ assert not torch.allclose(output[0], output[1], rtol=1e-4, atol=1e-4)++ def test_gradcheck(self, device, dtype):+ 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+ params = {+ 'batch_prob': torch.tensor([True]),+ 'ksize_factor': torch.tensor([31]),+ 'angle_factor': torch.tensor([[30., 30., 30.]]),+ 'direction_factor': torch.tensor([-0.5]),+ 'border_type': torch.tensor([0]),+ }+ assert gradcheck(RandomMotionBlur3D(+ kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0), (inp, params), raise_exception=True)diff --git a/test/filters/test_motion.py b/test/filters/test_motion.pyindex 5d5068d43..45c6e34a5 100644--- a/test/filters/test_motion.py+++ b/test/filters/test_motion.py@@ -9,13 +9,19 @@ from torch.autograd import gradcheckfrom torch.testing import assert_allclose[email protected]("batch_size", [0, 1, 5])@pytest.mark.parametrize("ksize", [3, 11])@pytest.mark.parametrize("angle", [0., 360.])@pytest.mark.parametrize("direction", [-1., 1.])-def test_get_motion_kernel2d(ksize, angle, direction):+def test_get_motion_kernel2d(batch_size, ksize, angle, direction):+ if batch_size != 0:+ angle = torch.tensor([angle] * batch_size)+ direction = torch.tensor([direction] * batch_size)+ else:+ batch_size = 1kernel = kornia.get_motion_kernel2d(ksize, angle, direction)- assert kernel.shape == (ksize, ksize)- assert_allclose(kernel.sum(), 1.)+ assert kernel.shape == (batch_size, ksize, ksize)+ assert_allclose(kernel.sum(), batch_size)class TestMotionBlur: