π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add RandomGaussianBlur with instance-level gaussian kernel generation (#1663)
Julien Denize92371287b620
diff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.pyindex be8213f47..a2ba68c3c 100644--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py@@ -1,26 +1,31 @@+import warningsfrom typing import Any, Dict, Optional, Tuplefrom torch import Tensor+from kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.constants import BorderType-from kornia.filters import gaussian_blur2d+from kornia.filters import gaussian_blur2d_tclass RandomGaussianBlur(IntensityAugmentationBase2D):- r"""Apply gaussian blur given tensor image or a batch of tensor images randomly.+ r"""Apply gaussian blur given tensor image or a batch of tensor images randomly. The standard deviation is+ sampled for each instance... image:: _static/img/RandomGaussianBlur.pngArgs:kernel_size: the size of the kernel.- sigma: the standard deviation of the kernel.+ sigma: the range for the standard deviation of the kernel.border_type: the padding mode to be applied before convolving.The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``.+ separable: run as composition of two 1d-convolutions.same_on_batch: apply the same transformation across the batch.p: probability of applying the transformation.keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False).+ silence_instantiation_warning: if True, silence the warning at instantiation.Shape:- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`@@ -34,11 +39,11 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):>>> input = torch.rand(1, 1, 5, 5)>>> blur = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)>>> blur(input)- tensor([[[[0.6699, 0.4645, 0.3193, 0.1741, 0.1955],- [0.5422, 0.6657, 0.6261, 0.6527, 0.5195],- [0.3826, 0.2638, 0.1902, 0.1620, 0.2141],- [0.6329, 0.6732, 0.5634, 0.4037, 0.2049],- [0.8307, 0.6753, 0.7147, 0.5768, 0.7097]]]])+ tensor([[[[0.5941, 0.5833, 0.5022, 0.4384, 0.3934],+ [0.5310, 0.4964, 0.4113, 0.3637, 0.3472],+ [0.4991, 0.4997, 0.4312, 0.3620, 0.3081],+ [0.6082, 0.5667, 0.4954, 0.3825, 0.3508],+ [0.7042, 0.6849, 0.6275, 0.4753, 0.4105]]]])To apply the exact augmenation again, you may take the advantage of the previous parameter state:>>> input = torch.randn(1, 3, 32, 32)@@ -52,17 +57,35 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):kernel_size: Tuple[int, int],sigma: Tuple[float, float],border_type: str = "reflect",+ separable: bool = True,same_on_batch: bool = False,p: float = 0.5,keepdim: bool = False,return_transform: Optional[bool] = None,+ silence_instantiation_warning: bool = False,) -> None:super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)- self.flags = dict(kernel_size=kernel_size, sigma=sigma, border_type=BorderType.get(border_type))++ if not silence_instantiation_warning:+ warnings.warn(+ "`RandomGaussianBlur` has changed its behavior and now randomly sample sigma for both axes. "+ "To retrieve old behavior please consider using kornia.filters.GaussianBlur2d",+ category=DeprecationWarning,+ )++ self.flags = dict(kernel_size=kernel_size, separable=separable, border_type=BorderType.get(border_type))+ self._param_generator = rg.RandomGaussianBlurGenerator(sigma)def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None) -> Tensor:- return gaussian_blur2d(input, flags["kernel_size"], flags["sigma"], flags["border_type"].name.lower())+ sigma = params["sigma"].to(device=input.device, dtype=input.dtype).unsqueeze(-1).expand(-1, 2)+ return gaussian_blur2d_t(+ input,+ self.flags["kernel_size"],+ sigma,+ self.flags["border_type"].name.lower(),+ separable=self.flags["separable"],+ )diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.pyindex 752703dd3..87f0f47f4 100644--- a/kornia/augmentation/random_generator/_2d/__init__.py+++ b/kornia/augmentation/random_generator/_2d/__init__.py@@ -3,6 +3,7 @@ from kornia.augmentation.random_generator._2d.color_jiggle import *from kornia.augmentation.random_generator._2d.color_jitter import *from kornia.augmentation.random_generator._2d.crop import *from kornia.augmentation.random_generator._2d.cutmix import *+from kornia.augmentation.random_generator._2d.gaussian_blur import *from kornia.augmentation.random_generator._2d.jigsaw import *from kornia.augmentation.random_generator._2d.mixup import *from kornia.augmentation.random_generator._2d.mosaic import *diff --git a/kornia/augmentation/random_generator/_2d/gaussian_blur.py b/kornia/augmentation/random_generator/_2d/gaussian_blur.pynew file mode 100644index 000000000..30cc2ca37--- /dev/null+++ b/kornia/augmentation/random_generator/_2d/gaussian_blur.py@@ -0,0 +1,54 @@+from typing import Dict, Tuple++import torch+from torch import Tensor+from torch.distributions import Uniform++from kornia.augmentation.random_generator.base import RandomGeneratorBase+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check+from kornia.utils.helpers import _extract_device_dtype+++class RandomGaussianBlurGenerator(RandomGeneratorBase):+ r"""Generate random gaussian blur parameters for a batch of images.++ Args:+ sigma: The range to uniformly sample the standard deviation for the Gaussian kernel.++ Returns:+ A dict of parameters to be passed for transformation.+ - sigma: element-wise standard deviation with a shape of (B,).++ Note:+ The generated random numbers are not reproducible across different devices and dtypes. By default,+ the parameters will be generated on CPU in float32. This can be changed by calling+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.+ """++ def __init__(self, sigma: Tuple[float, float] = (0.1, 2.0)) -> None:+ super().__init__()+ if sigma[1] < sigma[0]:+ raise TypeError(f"sigma_max should be higher than sigma_min: {sigma} passed.")++ self.sigma = sigma++ def __repr__(self) -> str:+ repr = f"sigma={self.sigma}"+ return repr++ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:+ if not isinstance(self.sigma, (torch.Tensor)):+ sigma = torch.tensor(self.sigma, device=device, dtype=dtype)+ else:+ sigma = sigma.to(device=device, dtype=dtype)++ _joint_range_check(sigma, "sigma", (0, float('inf')))++ self.sigma_sampler = Uniform(sigma[0], sigma[1], validate_args=False)++ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:+ batch_size = batch_shape[0]+ _common_param_check(batch_size, same_on_batch)+ _device, _dtype = _extract_device_dtype([self.sigma])+ sigma = _adapted_rsampling((batch_size,), self.sigma_sampler, same_on_batch)+ return dict(sigma=sigma.to(device=_device, dtype=_dtype))diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.pyindex 153ba2dfd..c399e2829 100644--- a/kornia/filters/__init__.py+++ b/kornia/filters/__init__.py@@ -3,7 +3,7 @@ from .blur_pool import BlurPool2D, MaxBlurPool2D, blur_pool2d, edge_aware_blur_pfrom .canny import Canny, cannyfrom .dexined import DexiNedfrom .filter import filter2d, filter2d_separable, filter3d-from .gaussian import GaussianBlur2d, gaussian_blur2d+from .gaussian import GaussianBlur2d, gaussian_blur2d, gaussian_blur2d_tfrom .kernels import (gaussian,get_binary_kernel2d,@@ -12,7 +12,9 @@ from .kernels import (get_gaussian_discrete_kernel1d,get_gaussian_erf_kernel1d,get_gaussian_kernel1d,+ get_gaussian_kernel1d_t,get_gaussian_kernel2d,+ get_gaussian_kernel2d_t,get_hanning_kernel1d,get_hanning_kernel2d,get_laplacian_kernel1d,@@ -34,9 +36,11 @@ __all__ = ["get_binary_kernel2d","get_box_kernel2d","get_gaussian_kernel1d",+ "get_gaussian_kernel1d_t","get_gaussian_discrete_kernel1d","get_gaussian_erf_kernel1d","get_gaussian_kernel2d",+ "get_gaussian_kernel2d_t","get_hanning_kernel1d","get_hanning_kernel2d","get_laplacian_kernel1d",@@ -48,6 +52,7 @@ __all__ = ["get_sobel_kernel2d","get_diff_kernel2d","gaussian_blur2d",+ "gaussian_blur2d_t","laplacian","laplacian_1d","unsharp_mask",diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex 6efe9fa75..606e92ab1 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -181,7 +181,7 @@ def filter2d_separable([0., 5., 5., 5., 0.],[0., 0., 0., 0., 0.]]]])"""- out_x = filter2d(input, kernel_x.unsqueeze(0), border_type, normalized, padding)+ out_x = filter2d(input, kernel_x.unsqueeze(-2), border_type, normalized, padding)out = filter2d(out_x, kernel_y.unsqueeze(-1), border_type, normalized, padding)return outdiff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.pyindex 66c824de4..c32bab9a6 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -4,7 +4,7 @@ import torchimport torch.nn as nnfrom .filter import filter2d, filter2d_separable-from .kernels import get_gaussian_kernel1d, get_gaussian_kernel2d+from .kernels import get_gaussian_kernel1d_t, get_gaussian_kernel2d_tdef gaussian_blur2d(@@ -43,13 +43,58 @@ def gaussian_blur2d(>>> output.shapetorch.Size([2, 4, 5, 5])"""+ device, dtype = input.device, input.dtype+ sigma_t = torch.tensor(sigma, device=device, dtype=dtype).unsqueeze(0)++ return gaussian_blur2d_t(input, kernel_size, sigma_t, border_type, separable)+++def gaussian_blur2d_t(+ input: torch.Tensor,+ kernel_size: Tuple[int, int],+ sigma: torch.Tensor,+ border_type: str = 'reflect',+ separable: bool = True,+) -> torch.Tensor:+ r"""Create an operator that blurs a tensor using a Gaussian filter.++ .. image:: _static/img/gaussian_blur2d.png++ The operator smooths the given tensor with a gaussian kernel by convolving+ it to each channel. It supports batched operation.++ Arguments:+ input: the input tensor with shape :math:`(B,C,H,W)`.+ kernel_size: the size of the kernel.+ sigma: the standard deviation of the kernel with shape :math:`(B,2)`.+ border_type: the padding mode to be applied before convolving.+ The expected modes are: ``'constant'``, ``'reflect'``,+ ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.+ separable: run as composition of two 1d-convolutions.++ Returns:+ the blurred tensor with shape :math:`(B, C, H, W)`.++ .. note::+ See a working example `here <https://kornia-tutorials.readthedocs.io/en/latest/+ gaussian_blur.html>`__.++ Examples:+ >>> input = torch.rand(2, 4, 5, 5)+ >>> output = gaussian_blur2d_t(input, (3, 3), torch.tensor([[1.5, 1.5]]))+ >>> output.shape+ torch.Size([2, 4, 5, 5])+ """+ device, dtype = input.device, input.dtype+ sigma = sigma.to(device=device, dtype=dtype)+if separable:- kernel_x: torch.Tensor = get_gaussian_kernel1d(kernel_size[1], sigma[1])- kernel_y: torch.Tensor = get_gaussian_kernel1d(kernel_size[0], sigma[0])- out = filter2d_separable(input, kernel_x[None], kernel_y[None], border_type)+ kernel_x: torch.Tensor = get_gaussian_kernel1d_t(kernel_size[1], sigma[:, 1])+ kernel_y: torch.Tensor = get_gaussian_kernel1d_t(kernel_size[0], sigma[:, 0])+ out = filter2d_separable(input, kernel_x, kernel_y, border_type)else:- kernel: torch.Tensor = get_gaussian_kernel2d(kernel_size, sigma)- out = filter2d(input, kernel[None], border_type)+ kernel: torch.Tensor = get_gaussian_kernel2d_t(kernel_size, sigma)+ out = filter2d(input, kernel, border_type)return outdiff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 13d458591..7a17c8da4 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -5,6 +5,7 @@ from typing import List, Tupleimport torchfrom kornia.core import Tensor, as_tensor, stack, tensor, zeros+from kornia.testing import KORNIA_CHECK_SHAPEdef normalize_kernel2d(input: Tensor) -> Tensor:@@ -15,15 +16,21 @@ def normalize_kernel2d(input: Tensor) -> Tensor:return input / (norm.unsqueeze(-1).unsqueeze(-1))-def gaussian(window_size: int, sigma: float) -> Tensor:- device, dtype = None, None- if isinstance(sigma, Tensor):- device, dtype = sigma.device, sigma.dtype- x = torch.arange(window_size, device=device, dtype=dtype) - window_size // 2+def gaussian(window_size: int, sigma: float) -> torch.Tensor:+ sigma_t = torch.tensor(sigma)++ return gaussian_t(window_size, sigma_t)+++def gaussian_t(window_size: int, sigma: torch.Tensor) -> torch.Tensor:+ device, dtype = sigma.device, sigma.dtype+ sigma = sigma.unsqueeze(-1)+ batch_size = sigma.shape[0]+ x = (torch.arange(window_size, device=device, dtype=dtype) - window_size // 2).expand(batch_size, -1)if window_size % 2 == 0:x = x + 0.5- gauss = torch.exp(-(x**2.0) / (2 * sigma**2))- return gauss / gauss.sum()+ gauss = torch.exp(-x.pow(2.0) / (2 * sigma.pow(2.0)))+ return gauss / gauss.sum(-1, keepdim=True)def gaussian_discrete_erf(window_size: int, sigma) -> Tensor:@@ -351,22 +358,56 @@ def get_gaussian_kernel1d(kernel_size: int, sigma: float, force_even: bool = Falforce_even: overrides requirement for odd kernel size.Returns:- 1D tensor with gaussian filter coefficients.+ gaussian filter coefficientsShape:- - Output: :math:`(\text{kernel_size})`+ - Output: :math:`(B, \text{kernel_size})`.Examples:>>> get_gaussian_kernel1d(3, 2.5)- tensor([0.3243, 0.3513, 0.3243])+ tensor([[0.3243, 0.3513, 0.3243]])>>> get_gaussian_kernel1d(5, 1.5)- tensor([0.1201, 0.2339, 0.2921, 0.2339, 0.1201])+ tensor([[0.1201, 0.2339, 0.2921, 0.2339, 0.1201]])+ """+ sigma_t = torch.tensor(sigma).unsqueeze(0)++ return get_gaussian_kernel1d_t(kernel_size, sigma_t, force_even)+++def get_gaussian_kernel1d_t(kernel_size: int, sigma: torch.Tensor, force_even: bool = False) -> torch.Tensor:+ r"""Function that returns Gaussian filter coefficients.++ Args:+ kernel_size: filter size. It should be odd and positive.+ sigma: gaussian standard deviation with shape of+ :math:`(B)`.+ force_even: overrides requirement for odd kernel size.++ Returns:+ gaussian filter coefficients++ Shape:+ - Output: :math:`(B, \text{kernel_size})`.++ Examples:++ >>> get_gaussian_kernel1d_t(3, torch.tensor([2.5]))+ tensor([[0.3243, 0.3513, 0.3243]])++ >>> get_gaussian_kernel1d_t(5, torch.tensor([1.5]))+ tensor([[0.1201, 0.2339, 0.2921, 0.2339, 0.1201]])++ >>> get_gaussian_kernel1d_t(5, torch.tensor([1.5, 0.7]))+ tensor([[0.1201, 0.2339, 0.2921, 0.2339, 0.1201],+ [0.0096, 0.2054, 0.5699, 0.2054, 0.0096]])"""+if not isinstance(kernel_size, int) or ((kernel_size % 2 == 0) and not force_even) or (kernel_size <= 0):raise TypeError("kernel_size must be an odd positive integer. " "Got {}".format(kernel_size))- window_1d: Tensor = gaussian(kernel_size, sigma)++ window_1d: torch.Tensor = gaussian_t(kernel_size, sigma)return window_1d@@ -428,41 +469,98 @@ def get_gaussian_erf_kernel1d(kernel_size: int, sigma: float, force_even: bool =return window_1d-def get_gaussian_kernel2d(kernel_size: Tuple[int, int], sigma: Tuple[float, float], force_even: bool = False) -> Tensor:+def get_gaussian_kernel2d(+ kernel_size: Tuple[int, int], sigma: Tuple[float, float], force_even: bool = False+) -> torch.Tensor:r"""Function that returns Gaussian filter matrix coefficients.Args:kernel_size: filter sizes in the x and y direction.Sizes should be odd and positive.- sigma: gaussian standard deviation in the x and y- direction.+ sigma: gaussian standard deviation in the x and y.force_even: overrides requirement for odd kernel size.Returns:2D tensor with gaussian filter matrix coefficients.Shape:- - Output: :math:`(\text{kernel_size}_x, \text{kernel_size}_y)`+ - Output: :math:`(B, \text{kernel_size}_x, \text{kernel_size}_y)`Examples:- >>> get_gaussian_kernel2d((3, 3), (1.5, 1.5))- tensor([[0.0947, 0.1183, 0.0947],- [0.1183, 0.1478, 0.1183],- [0.0947, 0.1183, 0.0947]])++ >>> get_gaussian_kernel2d((5, 5), (1.5, 1.5))+ tensor([[[0.0144, 0.0281, 0.0351, 0.0281, 0.0144],+ [0.0281, 0.0547, 0.0683, 0.0547, 0.0281],+ [0.0351, 0.0683, 0.0853, 0.0683, 0.0351],+ [0.0281, 0.0547, 0.0683, 0.0547, 0.0281],+ [0.0144, 0.0281, 0.0351, 0.0281, 0.0144]]])+>>> get_gaussian_kernel2d((3, 5), (1.5, 1.5))- tensor([[0.0370, 0.0720, 0.0899, 0.0720, 0.0370],- [0.0462, 0.0899, 0.1123, 0.0899, 0.0462],- [0.0370, 0.0720, 0.0899, 0.0720, 0.0370]])+ tensor([[[0.0370, 0.0720, 0.0899, 0.0720, 0.0370],+ [0.0462, 0.0899, 0.1123, 0.0899, 0.0462],+ [0.0370, 0.0720, 0.0899, 0.0720, 0.0370]]])+ """++ sigma_t = torch.tensor(sigma).unsqueeze(0)++ return get_gaussian_kernel2d_t(kernel_size, sigma_t, force_even)+++def get_gaussian_kernel2d_t(+ kernel_size: Tuple[int, int], sigma: torch.Tensor, force_even: bool = False+) -> torch.Tensor:+ r"""Function that returns Gaussian filter matrix coefficients.++ Args:+ kernel_size: filter sizes in the x and y direction.+ Sizes should be odd and positive.+ sigma: gaussian standard deviation in the x and y+ direction with shape of :math:`(B, 2)`.+ force_even: overrides requirement for odd kernel size.++ Returns:+ 2D tensor with gaussian filter matrix coefficients.++ Shape:+ - Output: :math:`(B, \text{kernel_size}_x, \text{kernel_size}_y)`++ Examples:++ >>> get_gaussian_kernel2d_t((5, 5), torch.tensor([[1.5, 1.5]]))+ tensor([[[0.0144, 0.0281, 0.0351, 0.0281, 0.0144],+ [0.0281, 0.0547, 0.0683, 0.0547, 0.0281],+ [0.0351, 0.0683, 0.0853, 0.0683, 0.0351],+ [0.0281, 0.0547, 0.0683, 0.0547, 0.0281],+ [0.0144, 0.0281, 0.0351, 0.0281, 0.0144]]])++ >>> get_gaussian_kernel2d_t((3, 5), torch.tensor([[1.5, 1.5]]))+ tensor([[[0.0370, 0.0720, 0.0899, 0.0720, 0.0370],+ [0.0462, 0.0899, 0.1123, 0.0899, 0.0462],+ [0.0370, 0.0720, 0.0899, 0.0720, 0.0370]]])++ >>> get_gaussian_kernel2d_t((5, 5), torch.tensor([[1.5, 1.5], [0.5, 0.5]]))+ tensor([[[1.4419e-02, 2.8084e-02, 3.5073e-02, 2.8084e-02, 1.4419e-02],+ [2.8084e-02, 5.4700e-02, 6.8312e-02, 5.4700e-02, 2.8084e-02],+ [3.5073e-02, 6.8312e-02, 8.5312e-02, 6.8312e-02, 3.5073e-02],+ [2.8084e-02, 5.4700e-02, 6.8312e-02, 5.4700e-02, 2.8084e-02],+ [1.4419e-02, 2.8084e-02, 3.5073e-02, 2.8084e-02, 1.4419e-02]],+ <BLANKLINE>+ [[6.9625e-08, 2.8089e-05, 2.0755e-04, 2.8089e-05, 6.9625e-08],+ [2.8089e-05, 1.1332e-02, 8.3731e-02, 1.1332e-02, 2.8089e-05],+ [2.0755e-04, 8.3731e-02, 6.1869e-01, 8.3731e-02, 2.0755e-04],+ [2.8089e-05, 1.1332e-02, 8.3731e-02, 1.1332e-02, 2.8089e-05],+ [6.9625e-08, 2.8089e-05, 2.0755e-04, 2.8089e-05, 6.9625e-08]]])"""if not isinstance(kernel_size, tuple) or len(kernel_size) != 2:raise TypeError(f"kernel_size must be a tuple of length two. Got {kernel_size}")- if not isinstance(sigma, tuple) or len(sigma) != 2:- raise TypeError(f"sigma must be a tuple of length two. Got {sigma}")++ KORNIA_CHECK_SHAPE(sigma, ["B", "2"])+ksize_x, ksize_y = kernel_size- sigma_x, sigma_y = sigma- kernel_x: Tensor = get_gaussian_kernel1d(ksize_x, sigma_x, force_even)- kernel_y: Tensor = get_gaussian_kernel1d(ksize_y, sigma_y, force_even)- kernel_2d: Tensor = torch.matmul(kernel_x.unsqueeze(-1), kernel_y.unsqueeze(-1).t())+ sigma_x, sigma_y = sigma[:, 0], sigma[:, 1]+ kernel_x: torch.Tensor = get_gaussian_kernel1d_t(ksize_x, sigma_x, force_even)+ kernel_y: torch.Tensor = get_gaussian_kernel1d_t(ksize_y, sigma_y, force_even)+ kernel_2d: torch.Tensor = torch.matmul(kernel_x.unsqueeze(-1), kernel_y.unsqueeze(-1).transpose(2, 1))return kernel_2ddiff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.pyindex f9de71a4d..aff69da8f 100644--- a/kornia/geometry/transform/elastic_transform.py+++ b/kornia/geometry/transform/elastic_transform.py@@ -3,7 +3,8 @@ from typing import Tupleimport torchimport torch.nn.functional as F-from kornia.filters import filter2d, get_gaussian_kernel2d+from kornia.filters import filter2d+from kornia.filters.kernels import get_gaussian_kernel2d_tfrom kornia.utils import create_meshgrid__all__ = ["elastic_transform2d"]@@ -74,9 +75,15 @@ def elastic_transform2d(if not len(noise.shape) == 4 or noise.shape[1] != 2:raise ValueError(f"Invalid noise shape, we expect Bx2xHxW. Got: {noise.shape}")+ device, dtype = image.device, image.dtype+ if isinstance(sigma, tuple):+ sigma_t = torch.tensor(sigma, device=device, dtype=dtype)+ elif isinstance(sigma, torch.Tensor):+ sigma_t = sigma.to(device=device, dtype=dtype)+# Get Gaussian kernel for 'y' and 'x' displacement- kernel_x: torch.Tensor = get_gaussian_kernel2d(kernel_size, (sigma[0], sigma[0]))[None]- kernel_y: torch.Tensor = get_gaussian_kernel2d(kernel_size, (sigma[1], sigma[1]))[None]+ kernel_x: torch.Tensor = get_gaussian_kernel2d_t(kernel_size, sigma_t[0].expand(2).unsqueeze(0))+ kernel_y: torch.Tensor = get_gaussian_kernel2d_t(kernel_size, sigma_t[1].expand(2).unsqueeze(0))# Convolve over a random displacement matrix and scale them with 'alpha'disp_x: torch.Tensor = noise[:, :1]diff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.pyindex 9db60bea1..14fe50b5c 100644--- a/kornia/metrics/ssim.py+++ b/kornia/metrics/ssim.py@@ -75,7 +75,7 @@ def ssim(raise ValueError(f"img1 and img2 shapes must be the same. Got: {img1.shape} and {img2.shape}")# prepare kernel- kernel: torch.Tensor = get_gaussian_kernel2d((window_size, window_size), (1.5, 1.5)).unsqueeze(0)+ kernel: torch.Tensor = get_gaussian_kernel2d((window_size, window_size), (1.5, 1.5))# compute coefficientsC1: float = (0.01 * max_val) ** 2diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex fa1acd743..ab8119896 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -3332,15 +3332,86 @@ class TestRandomEqualize(BaseTester):pass-class TestGaussianBlur:+class TestRandomGaussianBlur(BaseTester):# TODO: improve and implement more meaningful smoke tests e.g check for a consistent# return values such a Tensor variable.@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")def test_smoke(self):f = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.0)- repr = "RandomGaussianBlur(p=1.0, p_batch=1.0, same_on_batch=False)"+ repr = "RandomGaussianBlur(sigma=(0.1, 2.0), p=1.0, p_batch=1.0, same_on_batch=False)"assert str(f) == repr+ @pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])+ def test_cardinality(self, batch_shape, device, dtype):+ kernel_size = (5, 7)+ sigma = (1.5, 2.1)+ input = torch.rand(batch_shape, device=device, dtype=dtype)+ aug = RandomGaussianBlur(kernel_size, sigma, "replicate")+ actual = aug(input)+ 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, 3)+ sigma = (1.5, 2.1)+ aug = RandomGaussianBlur(kernel_size, sigma, "replicate")+ actual = aug(input)+ self.assert_close(actual, actual)++ def test_gradcheck(self, device, dtype):+ torch.manual_seed(0)++ # test parameters+ batch_shape = (3, 3, 5, 5)+ kernel_size = (3, 3)+ sigma = (1.5, 1.5)++ # evaluate function gradient+ input = torch.rand(batch_shape, device=device, dtype=dtype)+ input = utils.tensor_to_gradcheck_var(input) # to var+ assert gradcheck(RandomGaussianBlur(kernel_size, sigma, "replicate", p=1.0), (input,), raise_exception=True)++ @pytest.mark.xfail(+ reason="might fail due to the sampling distribution gradcheck errors. "+ "See: https://github.com/pytorch/pytorch/issues/78346."+ )+ def test_gradcheck_class_non_deterministic(self, device, dtype):+ torch.manual_seed(0)++ # test parameters+ batch_shape = (3, 3, 5, 5)+ kernel_size = (3, 3)+ sigma = (1.5, 2.1)++ # evaluate function gradient+ input = torch.rand(batch_shape, device=device, dtype=dtype)+ input = utils.tensor_to_gradcheck_var(input) # to var+ assert gradcheck(RandomGaussianBlur(kernel_size, sigma, "replicate", p=1.0), (input,), raise_exception=True)++ def test_jit(self, device, dtype):+ op = kornia.filters.gaussian_blur2d_t+ op_script = torch.jit.script(op)+ func_params = [(3, 3), torch.tensor([1.5, 1.5]).view(1, -1)]+ params = [(3, 3), torch.tensor([1.5, 1.5]).view(1, -1)]++ img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)+ self.assert_close(op(img, *params), op_script(img, *func_params))++ def test_module(self, device, dtype):+ func_params = [(3, 3), torch.tensor([1.5, 1.5]).view(1, -1)]+ params = [(3, 3), (1.5, 1.5)]+ op = kornia.filters.gaussian_blur2d_t+ op_module = RandomGaussianBlur(*params)++ img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)+ self.assert_close(op(img, *func_params), op_module(img))++ @pytest.mark.skip(reason="not implemented yet")+ def test_exception(self, device, dtype):+ pass+class TestRandomInvert(BaseTester):def test_smoke(self, device, dtype):diff --git a/test/filters/test_gaussian.py b/test/filters/test_gaussian.pyindex ec3c339b3..17bae18c4 100644--- a/test/filters/test_gaussian.py+++ b/test/filters/test_gaussian.py@@ -11,7 +11,7 @@ from kornia.testing import assert_close@pytest.mark.parametrize("sigma", [1.5, 5.0])def test_get_gaussian_kernel(window_size, sigma):kernel = kornia.filters.get_gaussian_kernel1d(window_size, sigma)- assert kernel.shape == (window_size,)+ assert kernel.shape == (1, window_size)assert kernel.sum().item() == pytest.approx(1.0)@@ -36,7 +36,7 @@ def test_get_gaussian_erf_kernel(window_size, sigma):@pytest.mark.parametrize("sigma", [1.5, 2.1])def test_get_gaussian_kernel2d(ksize_x, ksize_y, sigma):kernel = kornia.filters.get_gaussian_kernel2d((ksize_x, ksize_y), (sigma, sigma))- assert kernel.shape == (ksize_x, ksize_y)+ assert kernel.shape == (1, ksize_x, ksize_y)assert kernel.sum().item() == pytest.approx(1.0)@@ -51,6 +51,34 @@ def test_separable(ksize_x, ksize_y, sigma, device, dtype):assert_close(out, out_sep)[email protected]("window_size", [5, 11])[email protected]("sigma", [torch.tensor([1.5, 5.0]), torch.tensor([1.5, 5.0])])+def test_get_gaussian_kernel_t(window_size, sigma):+ kernel = kornia.filters.get_gaussian_kernel1d_t(window_size, sigma)+ assert kernel.shape == (2, window_size)+ assert_close(kernel.sum(1), torch.ones(2))++[email protected]("ksize_x", [5, 11])[email protected]("ksize_y", [3, 7])[email protected]("sigma", [torch.tensor([[1.5, 2.1], [1.5, 2.1]]), torch.tensor([[1.5, 2.1], [3.5, 2.1]])])+def test_get_gaussian_kernel2d_t(ksize_x, ksize_y, sigma):+ kernel = kornia.filters.get_gaussian_kernel2d_t((ksize_x, ksize_y), sigma)+ assert kernel.shape == (2, ksize_x, ksize_y)+ assert_close(kernel.sum([1, 2]), torch.ones(2))++[email protected]("ksize_x", [5, 11])[email protected]("ksize_y", [3, 7])[email protected]("sigma", [torch.tensor([[1.5, 2.1], [1.5, 2.1]]), torch.tensor([[1.5, 2.1], [2.5, 2.1]])])+def test_separable_t(ksize_x, ksize_y, sigma, device, dtype):+ input = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)+ out = kornia.filters.gaussian_blur2d_t(input, (ksize_x, ksize_y), sigma, "replicate", separable=False)+ out_sep = kornia.filters.gaussian_blur2d_t(input, (ksize_x, ksize_y), sigma, "replicate", separable=True)++ assert_close(out, out_sep)++class TestGaussianBlur2d:@pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])def test_cardinality(self, batch_shape, device, dtype):