π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] refactor kornia.filters and enable jit + tpu tests (#821)
Edgar Riba71ed1bcc6576
diff --git a/docker/tpu-tests/tpu_test_cases.jsonnet b/docker/tpu-tests/tpu_test_cases.jsonnetindex c82e9cc97..5d17cd817 100644--- a/docker/tpu-tests/tpu_test_cases.jsonnet+++ b/docker/tpu-tests/tpu_test_cases.jsonnet@@ -23,7 +23,7 @@ local tputests = base.BaseTest {python -c "import torch; print(torch.__version__)"python -c "import torch_xla; print(torch_xla.__version__)"python -c "import kornia; print(kornia.__version__)"- pytest -v kornia/test/color kornia/test/enhance --device tpu --dtype float32 -k "not grad"+ pytest -v kornia/test/color kornia/test/enhance kornia/test/filters --device tpu --dtype float32 -k "not grad"test_exit_code=$?echo "\nFinished running commands.\n"test $test_exit_code -eq 0diff --git a/kornia/filters/blur.py b/kornia/filters/blur.pyindex 028f2e8c0..66747d8b2 100644--- a/kornia/filters/blur.py+++ b/kornia/filters/blur.py@@ -4,8 +4,49 @@ import torchimport torch.nn as nnimport kornia-from kornia.filters.kernels import get_box_kernel2d-from kornia.filters.kernels import normalize_kernel2d+from kornia.filters.kernels import (+ get_box_kernel2d, normalize_kernel2d+)+++def box_blur(input: torch.Tensor,+ kernel_size: Tuple[int, int],+ border_type: str = 'reflect',+ normalized: bool = True) -> torch.Tensor:+ r"""Blurs an image using the box filter.++ The function smooths an image using the kernel:++ .. math::+ K = \frac{1}{\text{kernel_size}_x * \text{kernel_size}_y}+ \begin{bmatrix}+ 1 & 1 & 1 & \cdots & 1 & 1 \\+ 1 & 1 & 1 & \cdots & 1 & 1 \\+ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\+ 1 & 1 & 1 & \cdots & 1 & 1 \\+ \end{bmatrix}++ Args:+ image (torch.Tensor): the image to blur with shape :math:`(B,C,H,W)`.+ kernel_size (Tuple[int, int]): the blurring kernel size.+ border_type (str): the padding mode to be applied before convolving.+ The expected modes are: ``'constant'``, ``'reflect'``,+ ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.+ normalized (bool): if True, L1 norm of the kernel is set to 1.++ Returns:+ torch.Tensor: the blurred tensor with shape :math:`(B,C,H,W)`.++ Example:+ >>> input = torch.rand(2, 4, 5, 7)+ >>> output = box_blur(input, (3, 3)) # 2x4x5x7+ >>> output.shape+ torch.Size([2, 4, 5, 7])+ """+ kernel: torch.Tensor = get_box_kernel2d(kernel_size)+ if normalized:+ kernel = normalize_kernel2d(kernel)+ return kornia.filter2D(input, kernel, border_type)class BoxBlur(nn.Module):@@ -40,6 +81,8 @@ class BoxBlur(nn.Module):>>> input = torch.rand(2, 4, 5, 7)>>> blur = BoxBlur((3, 3))>>> output = blur(input) # 2x4x5x7+ >>> output.shape+ torch.Size([2, 4, 5, 7])"""def __init__(self, kernel_size: Tuple[int, int],@@ -48,10 +91,7 @@ class BoxBlur(nn.Module):super(BoxBlur, self).__init__()self.kernel_size: Tuple[int, int] = kernel_sizeself.border_type: str = border_type- self.kernel: torch.Tensor = get_box_kernel2d(kernel_size)self.normalized: bool = normalized- if self.normalized:- self.kernel = normalize_kernel2d(self.kernel)def __repr__(self) -> str:return self.__class__.__name__ +\@@ -59,20 +99,5 @@ class BoxBlur(nn.Module):'normalized=' + str(self.normalized) + ', ' + \'border_type=' + self.border_type + ')'- def forward(self, input: torch.Tensor): # type: ignore- return kornia.filter2D(input, self.kernel, self.border_type)---# 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],- border_type: str = 'reflect',- normalized: bool = True) -> torch.Tensor:- r"""Blurs an image using the box filter.-- See :class:`~kornia.filters.BoxBlur` for details.- """- return BoxBlur(kernel_size, border_type, normalized)(input)+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return box_blur(input, self.kernel_size, self.border_type, self.normalized)diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex e669df695..542ea70c3 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -5,10 +5,9 @@ import torch.nn as nnimport torch.nn.functional as Ffrom kornia.filters.kernels import normalize_kernel2d-import kornia.testing as testing-def compute_padding(kernel_size: List[int]) -> List[int]:+def _compute_padding(kernel_size: List[int]) -> List[int]:"""Computes padding tuple."""# 4 or 6 ints: (padding_left, padding_right,padding_top,padding_bottom)# https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad@@ -17,7 +16,7 @@ def compute_padding(kernel_size: List[int]) -> List[int]:# for even kernels we need to do asymetric padding :(- out_padding = []+ out_padding = 2 * len(kernel_size) * [0]for i in range(len(kernel_size)):computed_tmp = computed[-(i + 1)]@@ -25,8 +24,8 @@ def compute_padding(kernel_size: List[int]) -> List[int]:padding = computed_tmp - 1else:padding = computed_tmp- out_padding.append(padding)- out_padding.append(computed_tmp)+ out_padding[2 * i + 0] = padding+ out_padding[2 * i + 1] = computed_tmpreturn out_padding@@ -69,8 +68,13 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,[0., 5., 5., 5., 0.],[0., 0., 0., 0., 0.]]]])"""- testing.check_is_tensor(input)- testing.check_is_tensor(kernel)+ if not isinstance(input, torch.Tensor):+ raise TypeError("Input border_type is not torch.Tensor. Got {}"+ .format(type(input)))++ if not isinstance(kernel, torch.Tensor):+ raise TypeError("Input border_type is not torch.Tensor. Got {}"+ .format(type(kernel)))if not isinstance(border_type, str):raise TypeError("Input border_type is not string. Got {}"@@ -95,7 +99,7 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,# pad the input tensorheight, width = tmp_kernel.shape[-2:]- padding_shape: List[int] = compute_padding([height, width])+ padding_shape: List[int] = _compute_padding([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@@ -104,6 +108,7 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,# 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)@@ -169,8 +174,13 @@ def filter3D(input: torch.Tensor, kernel: torch.Tensor,[0., 5., 5., 5., 0.],[0., 0., 0., 0., 0.]]]]])"""- testing.check_is_tensor(input)- testing.check_is_tensor(kernel)+ if not isinstance(input, torch.Tensor):+ raise TypeError("Input border_type is not torch.Tensor. Got {}"+ .format(type(input)))++ if not isinstance(kernel, torch.Tensor):+ raise TypeError("Input border_type is not torch.Tensor. Got {}"+ .format(type(kernel)))if not isinstance(border_type, str):raise TypeError("Input border_type is not string. Got {}"@@ -197,7 +207,7 @@ def filter3D(input: torch.Tensor, kernel: torch.Tensor,# pad the input tensordepth, height, width = tmp_kernel.shape[-3:]- padding_shape: List[int] = compute_padding([depth, height, width])+ 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@@ -206,4 +216,5 @@ def filter3D(input: torch.Tensor, kernel: torch.Tensor,# convolve the tensor with the kernel.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/gaussian.py b/kornia/filters/gaussian.pyindex c09093969..5cad1a95b 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -7,6 +7,39 @@ import korniafrom kornia.filters.kernels import get_gaussian_kernel2d+def gaussian_blur2d(+ input: torch.Tensor,+ kernel_size: Tuple[int, int],+ sigma: Tuple[float, float],+ border_type: str = 'reflect') -> torch.Tensor:+ r"""Creates an operator that blurs a tensor using a Gaussian filter.++ The operator smooths the given tensor with a gaussian kernel by convolving+ it to each channel. It supports batched operation.++ Arguments:+ input (torch.Tensor): the input tensor with shape :math:`(B,C,H,W)`.+ kernel_size (Tuple[int, int]): the size of the kernel.+ sigma (Tuple[float, float]): the standard deviation of the kernel.+ 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 tensor with shape :math:`(B, C, H, W)`.++ Examples:+ >>> input = torch.rand(2, 4, 5, 5)+ >>> output = gaussian_blur2d(input, (3, 3), (1.5, 1.5))+ >>> output.shape+ torch.Size([2, 4, 5, 5])+ """+ kernel: torch.Tensor = torch.unsqueeze(+ get_gaussian_kernel2d(kernel_size, sigma), dim=0)++ return kornia.filter2D(input, kernel, border_type)++class GaussianBlur2d(nn.Module):r"""Creates an operator that blurs a tensor using a Gaussian filter.@@ -32,6 +65,8 @@ class GaussianBlur2d(nn.Module):>>> input = torch.rand(2, 4, 5, 5)>>> gauss = GaussianBlur2d((3, 3), (1.5, 1.5))>>> output = gauss(input) # 2x4x5x5+ >>> output.shape+ torch.Size([2, 4, 5, 5])"""def __init__(self, kernel_size: Tuple[int, int],@@ -40,10 +75,6 @@ class GaussianBlur2d(nn.Module):super(GaussianBlur2d, self).__init__()self.kernel_size: Tuple[int, int] = kernel_sizeself.sigma: Tuple[float, float] = sigma- self.kernel: torch.Tensor = torch.unsqueeze(- get_gaussian_kernel2d(kernel_size, sigma), dim=0)-- assert border_type in ["constant", "reflect", "replicate", "circular"]self.border_type = border_typedef __repr__(self) -> str:@@ -52,23 +83,5 @@ class GaussianBlur2d(nn.Module):'sigma=' + str(self.sigma) + ', ' +\'border_type=' + self.border_type + ')'- def forward(self, x: torch.Tensor): # type: ignore- return kornia.filter2D(x, self.kernel, self.border_type)---######################-# 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,- kernel_size: Tuple[int, int],- sigma: Tuple[float, float],- border_type: str = 'reflect') -> torch.Tensor:- r"""Function that blurs a tensor using a Gaussian filter.-- See :class:`~kornia.filters.GaussianBlur` for details.- """- return GaussianBlur2d(kernel_size, sigma, border_type)(input)+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type)diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex e76e2bcf2..910219b75 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -17,15 +17,15 @@ def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:return input / (norm.unsqueeze(-1).unsqueeze(-1))-def gaussian(window_size, sigma):- x = torch.arange(window_size).float() - window_size // 2+def gaussian(window_size: int, sigma: float) -> torch.Tensor:+ x = torch.arange(window_size) - window_size // 2if window_size % 2 == 0:x = x + 0.5- gauss = torch.exp((-x.pow(2.0) / float(2 * sigma ** 2)))+ gauss = torch.exp((-x.pow(2.0) / (2 * sigma ** 2)))return gauss / gauss.sum()-def gaussian_discrete_erf(window_size, sigma):+def gaussian_discrete_erf(window_size: int, sigma) -> torch.Tensor:r"""Discrete Gaussian by interpolating the error function. Adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py"""diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.pyindex d9b5f5be5..50f11135d 100644--- a/kornia/filters/laplacian.py+++ b/kornia/filters/laplacian.py@@ -8,31 +8,65 @@ from kornia.filters.kernels import get_laplacian_kernel2dfrom kornia.filters.kernels import normalize_kernel2d-class Laplacian(nn.Module):+def laplacian(+ input: torch.Tensor,+ kernel_size: int,+ border_type: str = 'reflect',+ normalized: bool = True) -> torch.Tensor:r"""Creates an operator that returns a tensor using a Laplacian filter.The operator smooths the given tensor with a laplacian kernel by convolvingit to each channel. It supports batched operation.Arguments:+ input (torch.Tensor): the input image tensor with shape :math:`(B, C, H, W)`.kernel_size (int): the size of the kernel.border_type (str): the padding mode to be applied before convolving.The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``. Default: ``'reflect'``.normalized (bool): if True, L1 norm of the kernel is set to 1.- Returns:- Tensor: the tensor.+ Return:+ torch.Tensor: the blurred image with shape :math:`(B, C, H, W)`.++ Examples:+ >>> input = torch.rand(2, 4, 5, 5)+ >>> output = laplacian(input, 3)+ >>> output.shape+ torch.Size([2, 4, 5, 5])+ """+ kernel: torch.Tensor = torch.unsqueeze(+ get_laplacian_kernel2d(kernel_size), dim=0)++ if normalized:+ kernel = normalize_kernel2d(kernel)++ return kornia.filter2D(input, kernel, border_type)+++class Laplacian(nn.Module):+ r"""Creates an operator that returns a tensor using a Laplacian filter.++ The operator smooths the given tensor with a laplacian kernel by convolving+ it to each channel. It supports batched operation.++ Arguments:+ kernel_size (int): the size of the kernel.+ border_type (str): the padding mode to be applied before convolving.+ The expected modes are: ``'constant'``, ``'reflect'``,+ ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.+ normalized (bool): if True, L1 norm of the kernel is set to 1.Shape:- Input: :math:`(B, C, H, W)`- Output: :math:`(B, C, H, W)`- Examples::-+ Examples:>>> input = torch.rand(2, 4, 5, 5)>>> laplace = Laplacian(5)- >>> output = laplace(input) # 2x4x5x5+ >>> output = laplace(input)+ >>> output.shape+ torch.Size([2, 4, 5, 5])"""def __init__(self,@@ -42,10 +76,6 @@ class Laplacian(nn.Module):self.kernel_size: int = kernel_sizeself.border_type: str = border_typeself.normalized: bool = normalized- self.kernel: torch.Tensor = torch.unsqueeze(- get_laplacian_kernel2d(kernel_size), dim=0)- if self.normalized:- self.kernel = normalize_kernel2d(self.kernel)def __repr__(self) -> str:return self.__class__.__name__ +\@@ -53,23 +83,5 @@ class Laplacian(nn.Module):'normalized=' + str(self.normalized) + ', ' + \'border_type=' + self.border_type + ')'- def forward(self, input: torch.Tensor): # type: ignore- return kornia.filter2D(input, self.kernel, self.border_type)---######################-# 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,- kernel_size: int,- border_type: str = 'reflect',- normalized: bool = True) -> torch.Tensor:- r"""Function that returns a tensor using a Laplacian filter.-- See :class:`~kornia.filters.Laplacian` for details.- """- return Laplacian(kernel_size, border_type, normalized)(input)+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return laplacian(input, self.kernel_size, self.border_type, self.normalized)diff --git a/kornia/filters/median.py b/kornia/filters/median.pyindex a1cd30c19..443b15f7a 100644--- a/kornia/filters/median.py+++ b/kornia/filters/median.py@@ -1,17 +1,60 @@-from typing import Tuple+from typing import List, Tupleimport torchimport torch.nn as nnimport torch.nn.functional as F+from kornia.filters.kernels import get_binary_kernel2ddef _compute_zero_padding(kernel_size: Tuple[int, int]) -> Tuple[int, int]:r"""Utility function that computes zero padding tuple."""- computed: Tuple[int, ...] = tuple([(k - 1) // 2 for k in kernel_size])+ computed: List[int] = [(k - 1) // 2 for k in kernel_size]return computed[0], computed[1]+def median_blur(input: torch.Tensor,+ kernel_size: Tuple[int, int]) -> torch.Tensor:+ r"""Blurs an image using the median filter.++ Args:+ input (torch.Tensor): the input image with shape :math:`(B,C,H,W)`.+ kernel_size (Tuple[int, int]): the blurring kernel size.++ Returns:+ torch.Tensor: the blurred input tensor with shape :math:`(B,C,H,W)`.++ Example:+ >>> input = torch.rand(2, 4, 5, 7)+ >>> output = median_blur(input, (3, 3))+ >>> output.shape+ torch.Size([2, 4, 5, 7])+ """+ if not isinstance(input, torch.Tensor):+ raise TypeError("Input type is not a torch.Tensor. Got {}"+ .format(type(input)))++ if not len(input.shape) == 4:+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"+ .format(input.shape))++ padding: Tuple[int, int] = _compute_zero_padding(kernel_size)++ # prepare kernel+ kernel: torch.Tensor = get_binary_kernel2d(kernel_size).to(input)+ b, c, h, w = input.shape++ # map the local window to single vector+ features: torch.Tensor = F.conv2d(+ input.reshape(b * c, 1, h, w), kernel, padding=padding, stride=1)+ features = features.view(b, c, -1, h, w) # BxCx(K_h * K_w)xHxW++ # compute the median along the feature axis+ median: torch.Tensor = torch.median(features, dim=2)[0]++ return median++class MedianBlur(nn.Module):r"""Blurs an image using the median filter.@@ -28,41 +71,14 @@ class MedianBlur(nn.Module):Example:>>> input = torch.rand(2, 4, 5, 7)>>> blur = MedianBlur((3, 3))- >>> output = blur(input) # 2x4x5x7+ >>> output = blur(input)+ >>> output.shape+ torch.Size([2, 4, 5, 7])"""def __init__(self, kernel_size: Tuple[int, int]) -> None:super(MedianBlur, self).__init__()- self.kernel: torch.Tensor = get_binary_kernel2d(kernel_size)- self.padding: Tuple[int, int] = _compute_zero_padding(kernel_size)-- def forward(self, input: torch.Tensor): # type: ignore- if not torch.is_tensor(input):- raise TypeError("Input type is not a torch.Tensor. Got {}"- .format(type(input)))- if not len(input.shape) == 4:- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"- .format(input.shape))- # prepare kernel- b, c, h, w = input.shape- kernel: torch.Tensor = self.kernel.to(input.device).to(input.dtype)- # map the local window to single vector- features: torch.Tensor = F.conv2d(- input.reshape(b * c, 1, h, w), kernel, padding=self.padding, stride=1)- features = features.view(b, c, -1, h, w) # BxCx(K_h * K_w)xHxW-- # compute the median along the feature axis- median: torch.Tensor = torch.median(features, dim=2)[0]- return median-+ self.kernel_size: Tuple[int, int] = kernel_size-# functiona api---def median_blur(input: torch.Tensor,- kernel_size: Tuple[int, int]) -> torch.Tensor:- r"""Blurs an image using the median filter.-- See :class:`~kornia.filters.MedianBlur` for details.- """- return MedianBlur(kernel_size)(input)+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return median_blur(input, self.kernel_size)diff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex 3fb26661f..97c46044b 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -3,8 +3,10 @@ from typing import Tuple, Unionimport torchimport torch.nn as nn-from kornia.filters.kernels import get_motion_kernel2d, get_motion_kernel3d-from kornia.filters.filter import filter2D, filter3D+import kornia+from kornia.filters.kernels import (+ get_motion_kernel2d, get_motion_kernel3d+)class MotionBlur(nn.Module):@@ -46,7 +48,7 @@ class MotionBlur(nn.Module):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+ def forward(self, x: torch.Tensor):return motion_blur(x, self.kernel_size, self.angle, self.direction, self.border_type)@@ -96,7 +98,7 @@ class MotionBlur3D(nn.Module):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+ def forward(self, x: torch.Tensor):return motion_blur3d(x, self.kernel_size, self.angle, self.direction, self.border_type)@@ -110,9 +112,9 @@ def motion_blur(r"""Perform motion blur on 2D images (4D tensor).Args:- input (tensor): the input tensor with shape :math:`(B, C, H, W)`.+ input (torch.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).+ angle (Union[torch.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),@@ -122,7 +124,8 @@ def motion_blur(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.+ Return:+ torch.Tensor: the blurred image with shape :math:`(B, C, H, W)`.Example:>>> input = torch.randn(1, 3, 80, 90).repeat(2, 1, 1, 1)@@ -137,7 +140,7 @@ def motion_blur("""assert border_type in ["constant", "reflect", "replicate", "circular"]kernel: torch.Tensor = get_motion_kernel2d(kernel_size, angle, direction)- return filter2D(input, kernel, border_type)+ return kornia.filter2D(input, kernel, border_type)def motion_blur3d(@@ -150,9 +153,9 @@ def motion_blur3d(r"""Perform motion blur on 3D volumes (5D tensor).Args:- input (tensor): the input tensor with shape :math:`(B, C, D, H, W)`.+ input (torch.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.+ angle (torch.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),@@ -162,6 +165,9 @@ def motion_blur3d(border_type (str): the padding mode to be applied before convolving. The expected modes are:``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'constant'``.+ Return:+ torch.Tensor: the blurred image with shape :math:`(B, C, D, H, W)`.+Example:>>> input = torch.randn(1, 3, 120, 80, 90).repeat(2, 1, 1, 1, 1)>>> # perform exact motion blur across the batch@@ -175,4 +181,4 @@ def motion_blur3d("""assert border_type in ["constant", "reflect", "replicate", "circular"]kernel: torch.Tensor = get_motion_kernel3d(kernel_size, angle, direction)- return filter3D(input, kernel, border_type)+ return kornia.filter3D(input, kernel, border_type)diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex 8284e7aa5..eafd5902e 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -2,14 +2,170 @@ import torchimport torch.nn as nnimport torch.nn.functional as F-from kornia.filters.kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d-from kornia.filters.kernels import normalize_kernel2d+from kornia.filters.kernels import (+ get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d+)+++def spatial_gradient(input: torch.Tensor,+ mode: str = 'sobel',+ order: int = 1,+ normalized: bool = True) -> torch.Tensor:+ r"""Computes the first order image derivative in both x and y using a Sobel+ operator.++ Args:+ input (torch.Tensor): input image tensor with shape :math:`(B, C, H, W)`.+ mode (str): derivatives modality, can be: `sobel` or `diff`. Default: `sobel`.+ order (int): the order of the derivatives. Default: 1.+ normalized (bool): whether the output is normalized. Default: True.++ Return:+ torch.Tensor: the derivatives of the input feature map. with shape :math:`(B, C, 2, H, W)`.++ Examples:+ >>> input = torch.rand(1, 3, 4, 4)+ >>> output = spatial_gradient(input) # 1x3x2x4x4+ >>> output.shape+ torch.Size([1, 3, 2, 4, 4])+ """+ if not isinstance(input, torch.Tensor):+ raise TypeError("Input type is not a torch.Tensor. Got {}"+ .format(type(input)))++ if not len(input.shape) == 4:+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"+ .format(input.shape))+ # allocate kernel+ kernel: torch.Tensor = get_spatial_gradient_kernel2d(mode, order)+ if normalized:+ kernel = normalize_kernel2d(kernel)++ # prepare kernel+ b, c, h, w = input.shape+ tmp_kernel: torch.Tensor = kernel.to(input).detach()+ tmp_kernel = tmp_kernel.unsqueeze(1).unsqueeze(1)++ # convolve input tensor with sobel kernel+ kernel_flip: torch.Tensor = tmp_kernel.flip(-3)++ # Pad with "replicate for spatial dims, but with zeros for channel+ spatial_pad = [+ kernel.size(1) // 2,+ kernel.size(1) // 2,+ kernel.size(2) // 2,+ kernel.size(2) // 2+ ]+ out_channels: int = 3 if order == 2 else 2+ padded_inp: torch.Tensor = F.pad(+ input.reshape(b * c, 1, h, w), spatial_pad, 'replicate')[:, :, None]++ return F.conv3d(padded_inp, kernel_flip, padding=0).view(b, c, out_channels, h, w)+++def spatial_gradient3d(input: torch.Tensor,+ mode: str = 'diff',+ order: int = 1) -> torch.Tensor:+ r"""Computes the first and second order volume derivative in x, y and d using a diff+ operator.++ Args:+ input (torch.Tensor): input features tensor with shape :math:`(B, C, D, H, W)`.+ mode (str): derivatives modality, can be: `sobel` or `diff`. Default: `diff`.+ order (int): the order of the derivatives. Default: 1.++ Return:+ torch.Tensor: the spatial gradients of the input feature map.++ Shape:+ - Input: :math:`(B, C, D, H, W)`. D, H, W are spatial dimensions, gradient is calculated w.r.t to them.+ - Output: :math:`(B, C, 3, D, H, W)` or :math:`(B, C, 6, D, H, W)`++ Examples:+ >>> input = torch.rand(1, 4, 2, 4, 4)+ >>> output = spatial_gradient3d(input)+ >>> output.shape+ torch.Size([1, 4, 3, 2, 4, 4])+ """+ if not isinstance(input, torch.Tensor):+ raise TypeError("Input type is not a torch.Tensor. Got {}"+ .format(type(input)))++ if not len(input.shape) == 5:+ raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"+ .format(input.shape))+ # allocate kernel+ kernel: torch.Tensor = get_spatial_gradient_kernel3d(mode, order)++ # prepare kernel+ b, c, d, h, w = input.shape+ tmp_kernel: torch.Tensor = kernel.to(input).detach()+ tmp_kernel = tmp_kernel.repeat(c, 1, 1, 1, 1)++ # convolve input tensor with grad kernel+ kernel_flip: torch.Tensor = tmp_kernel.flip(-3)++ # Pad with "replicate for spatial dims, but with zeros for channel+ spatial_pad = [+ kernel.size(2) // 2,+ kernel.size(2) // 2,+ kernel.size(3) // 2,+ kernel.size(3) // 2,+ kernel.size(4) // 2,+ kernel.size(4) // 2+ ]+ out_ch: int = 6 if order == 2 else 3+ return F.conv3d(F.pad(+ input, spatial_pad, 'replicate'), kernel_flip, padding=0, groups=c).view(b, c, out_ch, d, h, w)+++def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> torch.Tensor:+ r"""Computes the Sobel operator and returns the magnitude per channel.++ Args:+ input (torch.Tensor): the input image with shape :math:`(B,C,H,W)`.+ normalized (bool): if True, L1 norm of the kernel is set to 1.+ eps (float): regularization number to avoid NaN during backprop. Default: 1e-6.++ Return:+ torch.Tensor: the sobel edge gradient magnitudes map with shape :math:`(B,C,H,W)`.++ Example:+ >>> input = torch.rand(1, 3, 4, 4)+ >>> output = sobel(input) # 1x3x4x4+ >>> output.shape+ torch.Size([1, 3, 4, 4])+ """+ if not isinstance(input, torch.Tensor):+ raise TypeError("Input type is not a torch.Tensor. Got {}"+ .format(type(input)))++ if not len(input.shape) == 4:+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"+ .format(input.shape))++ # comput the x/y gradients+ edges: torch.Tensor = spatial_gradient(input, normalized=normalized)++ # unpack the edges+ gx: torch.Tensor = edges[:, :, 0]+ gy: torch.Tensor = edges[:, :, 1]++ # compute gradient maginitude+ magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy + eps)++ return magnitudeclass SpatialGradient(nn.Module):r"""Computes the first order image derivative in both x and y using a Sobeloperator.+ Args:+ mode (str): derivatives modality, can be: `sobel` or `diff`. Default: `sobel`.+ order (int): the order of the derivatives. Default: 1.+ normalized (bool): whether the output is normalized. Default: True.+Return:torch.Tensor: the sobel edges of the input feature map.@@ -30,10 +186,6 @@ class SpatialGradient(nn.Module):self.normalized: bool = normalizedself.order: int = orderself.mode: str = mode- self.kernel = get_spatial_gradient_kernel2d(mode, order)- if self.normalized:- self.kernel = normalize_kernel2d(self.kernel)- returndef __repr__(self) -> str:return self.__class__.__name__ + '('\@@ -41,34 +193,18 @@ class SpatialGradient(nn.Module):'normalized=' + str(self.normalized) + ', ' + \'mode=' + self.mode + ')'- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore- if not torch.is_tensor(input):- raise TypeError("Input type is not a torch.Tensor. Got {}"- .format(type(input)))- if not len(input.shape) == 4:- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"- .format(input.shape))- # prepare kernel- b, c, h, w = input.shape- tmp_kernel: torch.Tensor = self.kernel.to(input.device).to(input.dtype).detach()- kernel: torch.Tensor = tmp_kernel.unsqueeze(1).unsqueeze(1)-- # convolve input tensor with sobel kernel- kernel_flip: torch.Tensor = kernel.flip(-3)- # Pad with "replicate for spatial dims, but with zeros for channel- spatial_pad = [self.kernel.size(1) // 2,- self.kernel.size(1) // 2,- self.kernel.size(2) // 2,- self.kernel.size(2) // 2]- out_channels: int = 3 if self.order == 2 else 2- padded_inp: torch.Tensor = F.pad(input.reshape(b * c, 1, h, w), spatial_pad, 'replicate')[:, :, None]- return F.conv3d(padded_inp, kernel_flip, padding=0).view(b, c, out_channels, h, w)+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return spatial_gradient(input, self.mode, self.order, self.normalized)class SpatialGradient3d(nn.Module):r"""Computes the first and second order volume derivative in x, y and d using a diffoperator.+ Args:+ mode (str): derivatives modality, can be: `sobel` or `diff`. Default: `sobel`.+ order (int): the order of the derivatives. Default: 1.+Return:torch.Tensor: the spatial gradients of the input feature map.@@ -77,8 +213,10 @@ class SpatialGradient3d(nn.Module):- Output: :math:`(B, C, 3, D, H, W)` or :math:`(B, C, 6, D, H, W)`Examples:- >>> input = torch.rand(1, 3, 4, 4)- >>> output = SpatialGradient()(input) # 1x3x2x4x4+ >>> input = torch.rand(1, 4, 2, 4, 4)+ >>> output = SpatialGradient3d()(input)+ >>> output.shape+ torch.Size([1, 4, 3, 2, 4, 4])"""def __init__(self,@@ -96,40 +234,19 @@ class SpatialGradient3d(nn.Module):'mode=' + self.mode + ')'def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore- if not torch.is_tensor(input):- raise TypeError("Input type is not a torch.Tensor. Got {}"- .format(type(input)))- if not len(input.shape) == 5:- raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"- .format(input.shape))- # prepare kernel- b, c, d, h, w = input.shape- tmp_kernel: torch.Tensor = self.kernel.to(input.device).to(input.dtype).detach()- kernel: torch.Tensor = tmp_kernel.repeat(c, 1, 1, 1, 1)-- # convolve input tensor with grad kernel- kernel_flip: torch.Tensor = kernel.flip(-3)- # Pad with "replicate for spatial dims, but with zeros for channel- spatial_pad = [self.kernel.size(2) // 2,- self.kernel.size(2) // 2,- self.kernel.size(3) // 2,- self.kernel.size(3) // 2,- self.kernel.size(4) // 2,- self.kernel.size(4) // 2]- out_ch: int = 6 if self.order == 2 else 3- return F.conv3d(F.pad(input, spatial_pad, 'replicate'), kernel, padding=0, groups=c).view(b, c, out_ch, d, h, w)+ return spatial_gradient3d(input, self.mode, self.order)class Sobel(nn.Module):r"""Computes the Sobel operator and returns the magnitude per channel.- Return:- torch.Tensor: the sobel edge gradient magnitudes map.-Args:normalized (bool): if True, L1 norm of the kernel is set to 1.eps (float): regularization number to avoid NaN during backprop. Default: 1e-6.+ Return:+ torch.Tensor: the sobel edge gradient magnitudes map.+Shape:- Input: :math:`(B, C, H, W)`- Output: :math:`(B, C, H, W)`@@ -149,56 +266,5 @@ class Sobel(nn.Module):return self.__class__.__name__ + '('\'normalized=' + str(self.normalized) + ')'- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore- if not torch.is_tensor(input):- raise TypeError("Input type is not a torch.Tensor. Got {}"- .format(type(input)))- if not len(input.shape) == 4:- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"- .format(input.shape))- # comput the x/y gradients- edges: torch.Tensor = spatial_gradient(input,- normalized=self.normalized)-- # unpack the edges- gx: torch.Tensor = edges[:, :, 0]- gy: torch.Tensor = edges[:, :, 1]-- # compute gradient maginitude- magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy + self.eps)- return magnitude---# 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',- order: int = 1,- normalized: bool = True) -> torch.Tensor:- r"""Computes the first order image derivative in both x and y using a Sobel- operator.-- See :class:`~kornia.filters.SpatialGradient` for details.- """- return SpatialGradient(mode, order, normalized)(input)---def spatial_gradient3d(input: torch.Tensor,- mode: str = 'diff',- order: int = 1) -> torch.Tensor:- r"""Computes the first or second order image derivative in both x and y and y using a diff- operator.-- See :class:`~kornia.filters.SpatialGradient3d` for details.- """- return SpatialGradient3d(mode, order)(input)---def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> torch.Tensor:- r"""Computes the Sobel operator and returns the magnitude per channel.-- See :class:`~kornia.filters.Sobel` for details.- """- return Sobel(normalized, eps)(input)+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return sobel(input, self.normalized, self.eps)diff --git a/test/filters/test_blur.py b/test/filters/test_blur.pyindex b9c837b74..fba0483a1 100644--- a/test/filters/test_blur.py+++ b/test/filters/test_blur.py@@ -11,45 +11,65 @@ from torch.autograd import gradcheckclass TestBoxBlur:- def test_shape(self, device):- inp = torch.zeros(1, 3, 4, 4).to(device)+ def test_shape(self, device, dtype):+ inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)blur = kornia.filters.BoxBlur((3, 3))assert blur(inp).shape == (1, 3, 4, 4)- def test_shape_batch(self, device):- inp = torch.zeros(2, 6, 4, 4).to(device)+ def test_shape_batch(self, device, dtype):+ inp = torch.zeros(2, 6, 4, 4, device=device, dtype=dtype)blur = kornia.filters.BoxBlur((3, 3))assert blur(inp).shape == (2, 6, 4, 4)- def test_kernel_3x3(self, device):+ def test_kernel_3x3(self, device, dtype):inp = torch.tensor([[[[1., 1., 1., 1., 1.],[1., 1., 1., 1., 1.],[1., 1., 1., 1., 1.],[2., 2., 2., 2., 2.],[2., 2., 2., 2., 2.]- ]]]).to(device)+ ]]], device=device, dtype=dtype)kernel_size = (3, 3)actual = kornia.filters.box_blur(inp, kernel_size)- assert_allclose(actual[0, 0, 1, 1:4], torch.tensor(1.).to(device))- def test_kernel_5x5(self, device):+ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)+ assert_allclose(actual.sum(), torch.tensor(35.).to(actual), rtol=tol_val, atol=tol_val)++ # TODO(dmytro): normalized does not make any effect+ def test_kernel_3x3_nonormalize(self, device, dtype):inp = torch.tensor([[[[1., 1., 1., 1., 1.],[1., 1., 1., 1., 1.],[1., 1., 1., 1., 1.],[2., 2., 2., 2., 2.],[2., 2., 2., 2., 2.]- ]]]).to(device)+ ]]], device=device, dtype=dtype)++ kernel_size = (3, 3)+ actual = kornia.filters.box_blur(inp, kernel_size, normalized=False)++ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)+ assert_allclose(actual.sum(), torch.tensor(35.).to(actual), rtol=tol_val, atol=tol_val)++ def test_kernel_5x5(self, device, dtype):+ inp = torch.tensor([[[+ [1., 1., 1., 1., 1.],+ [1., 1., 1., 1., 1.],+ [1., 1., 1., 1., 1.],+ [2., 2., 2., 2., 2.],+ [2., 2., 2., 2., 2.]+ ]]], device=device, dtype=dtype)kernel_size = (5, 5)expected = inp.sum((1, 2, 3)) / torch.mul(*kernel_size)actual = kornia.filters.box_blur(inp, kernel_size)- assert_allclose(actual[:, 0, 2, 2], expected)- def test_kernel_5x5_batch(self, device):+ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)+ assert_allclose(actual[:, 0, 2, 2], expected, rtol=tol_val, atol=tol_val)++ def test_kernel_5x5_batch(self, device, dtype):batch_size = 3inp = torch.tensor([[[[1., 1., 1., 1., 1.],@@ -57,38 +77,48 @@ class TestBoxBlur:[1., 1., 1., 1., 1.],[2., 2., 2., 2., 2.],[2., 2., 2., 2., 2.]- ]]]).repeat(batch_size, 1, 1, 1).to(device)+ ]]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)kernel_size = (5, 5)expected = inp.sum((1, 2, 3)) / torch.mul(*kernel_size)actual = kornia.filters.box_blur(inp, kernel_size)- assert_allclose(actual[:, 0, 2, 2], expected)- def test_noncontiguous(self, device):+ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)+ assert_allclose(actual[:, 0, 2, 2], expected, rtol=tol_val, atol=tol_val)++ def test_noncontiguous(self, device, dtype):batch_size = 3- inp = torch.rand(3, 5, 5).expand(batch_size, -1, -1, -1).to(device)+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)kernel_size = (3, 3)actual = kornia.filters.box_blur(inp, kernel_size)expected = actualassert_allclose(actual, actual)- def test_gradcheck(self, device):+ def test_gradcheck(self, device, dtype):batch_size, channels, height, width = 1, 2, 5, 4- img = torch.rand(batch_size, channels, height, width).to(device)+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)img = utils.tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.filters.box_blur, (img, (3, 3),),raise_exception=True)- @pytest.mark.skip(reason="undefined value BoxBlur")- @pytest.mark.skip(reason="turn off all jit for a while")- def test_jit(self, device):+ def test_jit(self, device, dtype):op = kornia.filters.box_blurop_script = torch.jit.script(op)kernel_size = (3, 3)- img = torch.rand(2, 3, 4, 5).to(device)+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)actual = op_script(img, kernel_size)expected = op(img, kernel_size)assert_allclose(actual, expected)++ def test_module(self, device, dtype):+ op = kornia.filters.box_blur+ op_module = kornia.filters.BoxBlur++ kernel_size = (3, 3)+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ actual = op_module(kernel_size)(img)+ expected = op(img, kernel_size)+ assert_allclose(actual, expected)diff --git a/test/filters/test_filters.py b/test/filters/test_filters.pyindex 9e06b02e8..be4e71fca 100644--- a/test/filters/test_filters.py+++ b/test/filters/test_filters.py@@ -50,13 +50,14 @@ class TestFilter2D:[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.],]]], device=device, dtype=dtype).expand(2, 2, -1, -1)+expected = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 5., 5., 5., 0.],[0., 5., 5., 5., 0.],[0., 5., 5., 5., 0.],[0., 0., 0., 0., 0.],- ]]], device=device, dtype=dtype)+ ]]], device=device, dtype=dtype).expand(2, 2, -1, -1)actual = kornia.filter2D(input, kernel)assert_allclose(actual, expected)@@ -78,10 +79,12 @@ class TestFilter2D:[0., nv, nv, nv, 0.],[0., nv, nv, nv, 0.],[0., 0., 0., 0., 0.],- ]]], device=device, dtype=dtype)+ ]]], device=device, dtype=dtype).expand(2, 2, -1, -1)actual = kornia.filter2D(input, kernel, normalized=True)- assert_allclose(actual, expected)++ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)+ assert_allclose(actual, expected, rtol=tol_val, atol=tol_val)def test_even_sized_filter(self, device, dtype):kernel = torch.ones(1, 2, 2, device=device, dtype=dtype)@@ -123,14 +126,12 @@ class TestFilter2D:assert gradcheck(kornia.filter2D, (input, kernel),raise_exception=True)- @pytest.mark.skip(reason="not found compute_padding()")- @pytest.mark.skip(reason="turn off all jit for a while")- def test_jit(self, device):+ def test_jit(self, device, dtype):op = kornia.filter2D- op = torch.jit.script(op)+ op_script = torch.jit.script(op)- kernel = torch.rand(1, 3, 3)- input = torch.ones(1, 1, 7, 8)+ kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)+ input = torch.ones(1, 1, 7, 8, device=device, dtype=dtype)expected = op(input, kernel)actual = op_script(input, kernel)assert_allclose(actual, expected)@@ -236,6 +237,7 @@ class TestFilter3D:[0., 5., 5., 5., 0.],[0., 0., 0., 0., 0.],]]]], device=device, dtype=dtype)+ expected = expected.expand(2, 2, -1, -1, -1)actual = kornia.filter3D(input, kernel)assert_allclose(actual, expected)@@ -283,9 +285,12 @@ class TestFilter3D:[0., nv, nv, nv, 0.],[0., 0., 0., 0., 0.],]]]], device=device, dtype=dtype)+ expected = expected.expand(2, 2, -1, -1, -1)actual = kornia.filter3D(input, kernel, normalized=True)- assert_allclose(actual, expected)++ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)+ assert_allclose(actual, expected, rtol=tol_val, atol=tol_val)def test_even_sized_filter(self, device, dtype):kernel = torch.ones(1, 2, 2, 2, device=device, dtype=dtype)@@ -351,3 +356,13 @@ class TestFilter3D:kernel = utils.tensor_to_gradcheck_var(kernel) # to varassert gradcheck(kornia.filter3D, (input, kernel),raise_exception=True)++ def test_jit(self, device, dtype):+ op = kornia.filter3D+ op_script = torch.jit.script(op)++ kernel = torch.rand(1, 1, 3, 3, device=device, dtype=dtype)+ input = torch.ones(1, 1, 2, 7, 8, device=device, dtype=dtype)+ expected = op(input, kernel)+ actual = op_script(input, kernel)+ assert_allclose(actual, expected)diff --git a/test/filters/test_gaussian.py b/test/filters/test_gaussian.pyindex bb7ccb73e..05c8ffbb6 100644--- a/test/filters/test_gaussian.py+++ b/test/filters/test_gaussian.py@@ -41,35 +41,33 @@ def test_get_gaussian_kernel2d(ksize_x, ksize_y, sigma):assert kernel.sum().item() == pytest.approx(1.0)-class TestGaussianBlur:+class TestGaussianBlur2d:@pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])- def test_gaussian_blur(self, batch_shape, device):+ def test_cardinality(self, batch_shape, device, dtype):kernel_size = (5, 7)sigma = (1.5, 2.1)- input = torch.rand(batch_shape).to(device)- gauss = kornia.filters.GaussianBlur2d(kernel_size, sigma, "replicate")- assert gauss(input).shape == batch_shape+ input = torch.rand(batch_shape, device=device, dtype=dtype)+ actual = kornia.filters.gaussian_blur2d(input, kernel_size, sigma, "replicate")+ assert actual.shape == batch_shape- def test_noncontiguous(self, device):+ def test_noncontiguous(self, device, dtype):batch_size = 3- inp = torch.rand(3, 5, 5).expand(batch_size, -1, -1, -1).to(device)+ input = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)kernel_size = (3, 3)sigma = (1.5, 2.1)- gauss = kornia.filters.GaussianBlur2d(kernel_size, sigma, "replicate")- actual = gauss(inp)- expected = actual+ actual = kornia.filters.gaussian_blur2d(input, kernel_size, sigma, "replicate")assert_allclose(actual, actual)- def test_gradcheck(self, device):+ def test_gradcheck(self, device, dtype):# test parameters- batch_shape = (2, 3, 11, 7)- kernel_size = (5, 3)+ batch_shape = (1, 3, 5, 5)+ kernel_size = (3, 3)sigma = (1.5, 2.1)# evaluate function gradient- input = torch.rand(batch_shape).to(device)+ input = torch.rand(batch_shape, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input) # to varassert gradcheck(kornia.gaussian_blur2d,@@ -77,74 +75,18 @@ class TestGaussianBlur:raise_exception=True,)- @pytest.mark.skip(reason="turn off all jit for a while")- def test_jit(self):- @torch.jit.script- def op_script(img):-- return kornia.gaussian_blur2d(img, (5, 5), (1.2, 1.2), "replicate")-- batch_size, channels, height, width = 2, 3, 64, 64- img = torch.ones(batch_size, channels, height, width).to(device)- expected = kornia.filters.GaussianBlur2d(- (5, 5), (1.2, 1.2), "replicate"- )(img)- actual = op_script(img)- assert_allclose(actual, expected)--[email protected]("window_size", [5])-def test_get_laplacian_kernel(window_size):- kernel = kornia.get_laplacian_kernel1d(window_size)- assert kernel.shape == (window_size,)- assert kernel.sum().item() == pytest.approx(0.0)--[email protected]("window_size", [7])-def test_get_laplacian_kernel2d(window_size):- kernel = kornia.get_laplacian_kernel2d(window_size)- assert kernel.shape == (window_size, window_size)- assert kernel.sum().item() == pytest.approx(0.0)- expected = torch.tensor(- [- [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],- [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],- [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],- [1.0, 1.0, 1.0, -48.0, 1.0, 1.0, 1.0],- [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],- [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],- [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],- ]- )- assert_allclose(expected, kernel)---class TestLaplacian:- @pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])- def test_laplacian(self, batch_shape, device):- kernel_size = 5-- input = torch.rand(batch_shape).to(device)- laplace = kornia.filters.Laplacian(kernel_size)- assert laplace(input).shape == batch_shape+ def test_jit(self, device, dtype):+ op = kornia.filters.gaussian_blur2d+ op_script = torch.jit.script(op)+ params = [(3, 3), (1.5, 1.5)]- def test_noncontiguous(self, device):- batch_size = 3- inp = torch.rand(3, 5, 5).expand(batch_size, -1, -1, -1).to(device)+ img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)+ assert_allclose(op(img, *params), op_script(img, *params))- kernel_size = 3- laplace = kornia.filters.Laplacian(kernel_size)- actual = laplace(inp)- expected = actual- assert_allclose(actual, actual)+ def test_module(self, device, dtype):+ params = [(3, 3), (1.5, 1.5)]+ op = kornia.filters.gaussian_blur2d+ op_module = kornia.filters.GaussianBlur2d(*params)- def test_gradcheck(self, device):- # test parameters- batch_shape = (2, 3, 11, 7)- kernel_size = 9-- # evaluate function gradient- input = torch.rand(batch_shape).to(device)- input = utils.tensor_to_gradcheck_var(input)- assert gradcheck(- kornia.laplacian, (input, kernel_size), raise_exception=True)+ img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)+ assert_allclose(op(img, *params), op_module(img))diff --git a/test/filters/test_laplacian.py b/test/filters/test_laplacian.pynew file mode 100644index 000000000..26a8b1ac3--- /dev/null+++ b/test/filters/test_laplacian.py@@ -0,0 +1,79 @@+import pytest++import kornia+import kornia.testing as utils # test utils++import torch+from torch.autograd import gradcheck+from torch.testing import assert_allclose++[email protected]("window_size", [5])+def test_get_laplacian_kernel(window_size):+ kernel = kornia.get_laplacian_kernel1d(window_size)+ assert kernel.shape == (window_size,)+ assert kernel.sum().item() == pytest.approx(0.0)++[email protected]("window_size", [7])+def test_get_laplacian_kernel2d(window_size):+ kernel = kornia.get_laplacian_kernel2d(window_size)+ assert kernel.shape == (window_size, window_size)+ assert kernel.sum().item() == pytest.approx(0.0)+ expected = torch.tensor(+ [+ [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],+ [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],+ [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],+ [1.0, 1.0, 1.0, -48.0, 1.0, 1.0, 1.0],+ [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],+ [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],+ [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],+ ]+ )+ assert_allclose(expected, kernel)+++class TestLaplacian:+ @pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])+ def test_cardinality(self, batch_shape, device, dtype):+ kernel_size = 5++ input = torch.rand(batch_shape, device=device, dtype=dtype)+ actual = kornia.filters.laplacian(input, kernel_size)+ assert actual.shape == batch_shape++ def test_noncontiguous(self, device, dtype):+ batch_size = 3+ input = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)++ kernel_size = 3+ actual = kornia.filters.laplacian(input, kernel_size)+ assert_allclose(actual, actual)++ def test_gradcheck(self, device, dtype):+ # test parameters+ batch_shape = (1, 2, 5, 7)+ kernel_size = 3++ # evaluate function gradient+ input = torch.rand(batch_shape, device=device, dtype=dtype)+ input = utils.tensor_to_gradcheck_var(input)+ assert gradcheck(+ kornia.laplacian, (input, kernel_size), raise_exception=True)++ def test_jit(self, device, dtype):+ op = kornia.filters.laplacian+ op_script = torch.jit.script(op)+ params = [3]++ img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)+ assert_allclose(op(img, *params), op_script(img, *params))++ def test_module(self, device, dtype):+ params = [3]+ op = kornia.filters.laplacian+ op_module = kornia.filters.Laplacian(*params)++ img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)+ assert_allclose(op(img, *params), op_module(img))diff --git a/test/filters/test_median.py b/test/filters/test_median.pyindex 35b259cf7..1cbaf4e1d 100644--- a/test/filters/test_median.py+++ b/test/filters/test_median.py@@ -11,17 +11,15 @@ from torch.autograd import gradcheckclass TestMedianBlur:- def test_shape(self, device):- inp = torch.zeros(1, 3, 4, 4).to(device)- median = kornia.filters.MedianBlur((3, 3))- assert median(inp).shape == (1, 3, 4, 4)+ def test_shape(self, device, dtype):+ inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)+ assert kornia.filters.median_blur(inp, (3, 3)).shape == (1, 3, 4, 4)- def test_shape_batch(self, device):- inp = torch.zeros(2, 6, 4, 4).to(device)- blur = kornia.filters.BoxBlur((3, 3))- assert blur(inp).shape == (2, 6, 4, 4)+ def test_shape_batch(self, device, dtype):+ inp = torch.zeros(2, 6, 4, 4, device=device, dtype=dtype)+ assert kornia.filters.median_blur(inp, (3, 3)).shape == (2, 6, 4, 4)- def test_kernel_3x3(self, device):+ def test_kernel_3x3(self, device, dtype):inp = torch.tensor([[[0., 0., 0., 0., 0.],[0., 3., 7., 5., 0.],@@ -34,38 +32,43 @@ class TestMedianBlur:[65., 59., 2.0, 0., 0.],[0.0, 0.0, 0.0, 0., 0.],[0.0, 0.0, 0.0, 0., 0.]- ]]).repeat(2, 1, 1, 1).to(device)+ ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)kernel_size = (3, 3)actual = kornia.filters.median_blur(inp, kernel_size)- assert_allclose(actual[0, 0, 2, 2], torch.tensor(3.).to(device))- assert_allclose(actual[0, 1, 1, 1], torch.tensor(14.).to(device))+ assert_allclose(actual[0, 0, 2, 2], torch.tensor(3.).to(actual))+ assert_allclose(actual[0, 1, 1, 1], torch.tensor(14.).to(actual))- def test_noncontiguous(self, device):+ def test_noncontiguous(self, device, dtype):batch_size = 3- inp = torch.rand(3, 5, 5).expand(batch_size, -1, -1, -1).to(device)+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)kernel_size = (3, 3)actual = kornia.filters.median_blur(inp, kernel_size)expected = actualassert_allclose(actual, actual)- def test_gradcheck(self, device):+ def test_gradcheck(self, device, dtype):batch_size, channels, height, width = 1, 2, 5, 4- img = torch.rand(batch_size, channels, height, width).to(device)+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)img = utils.tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.filters.median_blur, (img, (5, 3),),raise_exception=True)- @pytest.mark.skip("")- @pytest.mark.skip(reason="turn off all jit for a while")- def test_jit(self, device):- @torch.jit.script- def op_script(input: torch.Tensor,- kernel_size: Tuple[int, int]) -> torch.Tensor:- return kornia.filters.median_blur(input, kernel_size)+ def test_jit(self, device, dtype):kernel_size = (3, 5)- img = torch.rand(2, 3, 4, 5).to(device)+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ op = kornia.filters.median_blur+ op_script = torch.jit.script(op)actual = op_script(img, kernel_size)- expected = kornia.filters.median_blur(img, kernel_size)+ expected = op(img, kernel_size)+ assert_allclose(actual, expected)++ def test_module(self, device, dtype):+ kernel_size = (3, 5)+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ op = kornia.filters.median_blur+ op_module = kornia.filters.MedianBlur((3, 5))+ actual = op_module(img)+ expected = op(img, kernel_size)assert_allclose(actual, expected)diff --git a/test/filters/test_motion.py b/test/filters/test_motion.pyindex 45c6e34a5..283b7a484 100644--- a/test/filters/test_motion.py+++ b/test/filters/test_motion.py@@ -1,4 +1,3 @@-from typing import Tupleimport pytestimport kornia@@ -26,18 +25,18 @@ def test_get_motion_kernel2d(batch_size, ksize, angle, direction):class TestMotionBlur:@pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])- def test_motion_blur(self, batch_shape, device):+ def test_motion_blur(self, batch_shape, device, dtype):ksize = 5angle = 200.direction = 0.3- input = torch.rand(batch_shape).to(device)+ input = torch.rand(batch_shape, device=device, dtype=dtype)motion = kornia.filters.MotionBlur(ksize, angle, direction)assert motion(input).shape == batch_shape- def test_noncontiguous(self, device):+ def test_noncontiguous(self, device, dtype):batch_size = 3- inp = torch.rand(3, 5, 5).expand(batch_size, -1, -1, -1).to(device)+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)kernel_size = 3angle = 200.@@ -46,13 +45,13 @@ class TestMotionBlur:expected = actualassert_allclose(actual, actual)- def test_gradcheck(self, device):- batch_shape = (2, 3, 11, 7)+ def test_gradcheck(self, device, dtype):+ batch_shape = (1, 3, 4, 5)ksize = 9angle = 34.direction = -0.2- input = torch.rand(batch_shape).to(device)+ input = torch.rand(batch_shape, device=device, dtype=dtype)input = utils.tensor_to_gradcheck_var(input)assert gradcheck(kornia.motion_blur,@@ -60,22 +59,14 @@ class TestMotionBlur:raise_exception=True,)- @pytest.mark.skip("")- @pytest.mark.skip(reason="turn off all jit for a while")- def test_jit(self, device):- @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).to(device)+ @pytest.mark.skip("angle can be Union")+ def test_jit(self, device, dtype):+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)ksize = 5angle = 65.direction = .1+ op = kornia.filters.motion_blur+ op_script = torch.jit.script(op)actual = op_script(img, ksize, angle, direction)- expected = kornia.filters.motion_blur(img, ksize, angle, direction)+ expected = op(img, ksize, angle, direction)assert_allclose(actual, expected)diff --git a/test/filters/test_sobel.py b/test/filters/test_sobel.pyindex 91c39d494..32122ffc0 100644--- a/test/filters/test_sobel.py+++ b/test/filters/test_sobel.py@@ -9,24 +9,24 @@ from torch.autograd import gradcheckclass TestSpatialGradient:- def test_shape(self, device):- inp = torch.zeros(1, 3, 4, 4).to(device)+ def test_shape(self, device, dtype):+ inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)sobel = kornia.filters.SpatialGradient()assert sobel(inp).shape == (1, 3, 2, 4, 4)- def test_shape_batch(self, device):- inp = torch.zeros(2, 6, 4, 4).to(device)+ def test_shape_batch(self, device, dtype):+ inp = torch.zeros(2, 6, 4, 4, device=device, dtype=dtype)sobel = kornia.filters.SpatialGradient()assert sobel(inp).shape == (2, 6, 2, 4, 4)- def test_edges(self, device):+ def test_edges(self, device, dtype):inp = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 0., 1., 0., 0.],[0., 1., 1., 1., 0.],[0., 0., 1., 0., 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)expected = torch.tensor([[[[[0., 1., 0., -1., 0.],@@ -40,19 +40,19 @@ class TestSpatialGradient:[0., 0., 0., 0., 0],[-1., -3., -4., -3., -1],[0., -1., -2., -1., 0.],- ]]]]).to(device)+ ]]]], device=device, dtype=dtype)edges = kornia.filters.spatial_gradient(inp, normalized=False)assert_allclose(edges, expected)- def test_edges_norm(self, device):+ def test_edges_norm(self, device, dtype):inp = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 0., 1., 0., 0.],[0., 1., 1., 1., 0.],[0., 0., 1., 0., 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)expected = torch.tensor([[[[[0., 1., 0., -1., 0.],@@ -66,19 +66,19 @@ class TestSpatialGradient:[0., 0., 0., 0., 0],[-1., -3., -4., -3., -1],[0., -1., -2., -1., 0.],- ]]]]).to(device) / 8.0+ ]]]], device=device, dtype=dtype) / 8.0edges = kornia.filters.spatial_gradient(inp, normalized=True)assert_allclose(edges, expected)- def test_edges_sep(self, device):+ def test_edges_sep(self, device, dtype):inp = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 0., 1., 0., 0.],[0., 1., 1., 1., 0.],[0., 0., 1., 0., 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)expected = torch.tensor([[[[[0., 0., 0., 0., 0.],@@ -92,19 +92,20 @@ class TestSpatialGradient:[0., 0., 0., 0., 0.],[0., -1., -1., -1., 0.],[0., 0., -1., 0., 0.]- ]]]]).to(device)+ ]]]], device=device, dtype=dtype)+edges = kornia.filters.spatial_gradient(inp, 'diff',normalized=False)assert_allclose(edges, expected)- def test_edges_sep_norm(self, device):+ def test_edges_sep_norm(self, device, dtype):inp = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 0., 1., 0., 0.],[0., 1., 1., 1., 0.],[0., 0., 1., 0., 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)expected = torch.tensor([[[[[0., 0., 0., 0., 0.],@@ -118,49 +119,56 @@ class TestSpatialGradient:[0., 0., 0., 0., 0.],[0., -1., -1., -1., 0.],[0., 0., -1., 0., 0.]- ]]]]).to(device) / 2.0+ ]]]], device=device, dtype=dtype) / 2.0+edges = kornia.filters.spatial_gradient(inp, 'diff',normalized=True)assert_allclose(edges, expected)- def test_noncontiguous(self, device):+ def test_noncontiguous(self, device, dtype):batch_size = 3- inp = torch.rand(3, 5, 5).expand(batch_size, -1, -1, -1).to(device)+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)actual = kornia.filters.spatial_gradient(inp)- expected = actualassert_allclose(actual, actual)- def test_gradcheck(self, device):- batch_size, channels, height, width = 1, 2, 5, 4- img = torch.rand(batch_size, channels, height, width).to(device)+ def test_gradcheck(self, device, dtype):+ batch_size, channels, height, width = 1, 1, 3, 4+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)img = utils.tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.filters.spatial_gradient, (img,),raise_exception=True)- @pytest.mark.skip(reason="turn off all jit for a while")- def test_jit(self, device):- @torch.jit.script- def op_script(input):- return kornia.filters.spatial_gradient(input)- img = torch.rand(2, 3, 4, 5).to(device)+ def test_jit(self, device, dtype):+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ op = kornia.filters.spatial_gradient+ op_script = torch.jit.script(op)actual = op_script(img)- expected = kornia.filters.spatial_gradient(img)+ expected = op(img)+ assert_allclose(actual, expected)++ def test_module(self, device, dtype):+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ op = kornia.filters.spatial_gradient+ op_module = kornia.filters.SpatialGradient()+ expected = op(img)+ actual = op_module(img)assert_allclose(actual, expected)class TestSpatialGradient3d:- def test_shape(self, device):- inp = torch.zeros(1, 2, 4, 5, 6).to(device)+ def test_shape(self, device, dtype):+ inp = torch.zeros(1, 2, 4, 5, 6, device=device, dtype=dtype)sobel = kornia.filters.SpatialGradient3d()assert sobel(inp).shape == (1, 2, 3, 4, 5, 6)- def test_shape_batch(self, device):- inp = torch.zeros(7, 2, 4, 5, 6).to(device)+ def test_shape_batch(self, device, dtype):+ inp = torch.zeros(7, 2, 4, 5, 6, device=device, dtype=dtype)sobel = kornia.filters.SpatialGradient3d()assert sobel(inp).shape == (7, 2, 3, 4, 5, 6)- def test_edges(self, device):+ @pytest.mark.skip("fix due to bug in kernel_flip")+ def test_edges(self, device, dtype):inp = torch.tensor([[[[[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.],@@ -177,95 +185,101 @@ class TestSpatialGradient3d:[0., 0., 1., 0., 0.],[0., 0., 0., 0., 0.],[0., 0., 0., 0., 0.]],- ]]]).to(device)-- expected = torch.tensor([[[[[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],- [0.5000, 0.5000, 0.0000, -0.5000, -0.5000],- [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]],- [[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],- [[0.0000, 0.0000, 0.5000, 0.0000, 0.0000],- [0.0000, 0.5000, 0.5000, 0.5000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, -0.5000, -0.5000, -0.5000, 0.0000],- [0.0000, 0.0000, -0.5000, 0.0000, 0.0000]],- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]],- [[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],- [0.0000, 0.5000, 0.0000, 0.5000, 0.0000],- [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],- [0.0000, -0.5000, 0.0000, -0.5000, 0.0000],- [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]]]])-- expected = expected.to(device)+ ]]], device=device, dtype=dtype)++ expected = torch.tensor([+ [[[[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],+ [0.5000, 0.5000, 0.0000, -0.5000, -0.5000],+ [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]],+ [[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],+ [[0.0000, 0.0000, 0.5000, 0.0000, 0.0000],+ [0.0000, 0.5000, 0.5000, 0.5000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, -0.5000, -0.5000, -0.5000, 0.0000],+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000]],+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]],+ [[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],+ [0.0000, 0.5000, 0.0000, 0.5000, 0.0000],+ [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],+ [0.0000, -0.5000, 0.0000, -0.5000, 0.0000],+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]]]], device=device, dtype=dtype)+edges = kornia.filters.spatial_gradient3d(inp)assert_allclose(edges, expected)- def test_gradcheck(self, device):- batch_size, channels, depth, height, width = 1, 2, 3, 5, 4- img = torch.rand(batch_size, channels, depth, height, width).to(device)+ def test_gradcheck(self, device, dtype):+ img = torch.rand(1, 1, 1, 3, 4, device=device, dtype=dtype)img = utils.tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.filters.spatial_gradient3d, (img,),raise_exception=True)- @pytest.mark.skip(reason="turn off all jit for a while")- def test_jit(self, device):- @torch.jit.script- def op_script(input):- return kornia.filters.spatial_gradient(input)- img = torch.rand(2, 3, 4, 5).to(device)+ @pytest.mark.skip("issue with device in kernel generation")+ def test_jit(self, device, dtype):+ img = torch.rand(2, 3, 1, 4, 5, device=device, dtype=dtype)+ op = kornia.filters.spatial_gradient3d+ op_script = torch.jit.script(op)+ expected = op(img)actual = op_script(img)- expected = kornia.filters.spatial_gradient(img)+ assert_allclose(actual, expected)++ def test_module(self, device, dtype):+ img = torch.rand(2, 3, 1, 4, 5, device=device, dtype=dtype)+ op = kornia.filters.spatial_gradient3d+ op_module = kornia.filters.SpatialGradient3d()+ expected = op(img)+ actual = op_module(img)assert_allclose(actual, expected)class TestSobel:- def test_shape(self, device):- inp = torch.zeros(1, 3, 4, 4).to(device)+ def test_shape(self, device, dtype):+ inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)sobel = kornia.filters.Sobel()assert sobel(inp).shape == (1, 3, 4, 4)- def test_shape_batch(self, device):- inp = torch.zeros(3, 2, 4, 4).to(device)+ def test_shape_batch(self, device, dtype):+ inp = torch.zeros(3, 2, 4, 4, device=device, dtype=dtype)sobel = kornia.filters.Sobel()assert sobel(inp).shape == (3, 2, 4, 4)- def test_magnitude(self, device):+ def test_magnitude(self, device, dtype):inp = torch.tensor([[[[0., 0., 0., 0., 0.],[0., 0., 1., 0., 0.],[0., 1., 1., 1., 0.],[0., 0., 1., 0., 0.],[0., 0., 0., 0., 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)expected = torch.tensor([[[[0., 1.4142, 2.0, 1.4142, 0.],@@ -273,43 +287,49 @@ class TestSobel:[2.0, 4.0000, 0.00, 4.0000, 2.0],[1.4142, 4.2426, 4.00, 4.2426, 1.4142],[0., 1.4142, 2.0, 1.4142, 0.],- ]]]).to(device)+ ]]], device=device, dtype=dtype)edges = kornia.filters.sobel(inp, normalized=False, eps=0.)assert_allclose(edges, expected)- def test_noncontiguous(self, device):+ def test_noncontiguous(self, device, dtype):batch_size = 3- inp = torch.rand(3, 5, 5).expand(batch_size, -1, -1, -1).to(device)+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)actual = kornia.filters.sobel(inp)expected = actualassert_allclose(actual, actual)- def test_gradcheck_unnorm(self, device):+ def test_gradcheck_unnorm(self, device, dtype):if "cuda" in str(device):pytest.skip("RuntimeError: Backward is not reentrant, i.e., running backward,")- batch_size, channels, height, width = 1, 2, 5, 4- img = torch.rand(batch_size, channels, height, width).to(device)+ batch_size, channels, height, width = 1, 1, 3, 4+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)img = utils.tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.filters.sobel, (img, False),raise_exception=True)- def test_gradcheck(self, device):+ def test_gradcheck(self, device, dtype):if "cuda" in str(device):pytest.skip("RuntimeError: Backward is not reentrant, i.e., running backward,")- batch_size, channels, height, width = 1, 2, 5, 4- img = torch.rand(batch_size, channels, height, width).to(device)+ batch_size, channels, height, width = 1, 1, 3, 4+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)img = utils.tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.filters.sobel, (img, True),raise_exception=True)- @pytest.mark.skip(reason="turn off all jit for a while")- def test_jit(self, device):- @torch.jit.script- def op_script(input):- return kornia.filters.sobel(input)- img = torch.rand(2, 3, 4, 5).to(device)+ def test_jit(self, device, dtype):+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ op = kornia.filters.sobel+ op_script = torch.jit.script(op)+ expected = op(img)actual = op_script(img)- expected = kornia.filters.sobel(img)+ assert_allclose(actual, expected)++ def test_module(self, device, dtype):+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ op = kornia.filters.sobel+ op_module = kornia.filters.Sobel()+ expected = op(img)+ actual = op_module(img)assert_allclose(actual, expected)