Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

:kissing: Implement separable_filter2d (#1385)

Dmytro Mishkin09c6a3f8ccd1
diff --git a/docs/source/filters.rst b/docs/source/filters.rst
index 6dba82a30..35e66038e 100644
--- a/docs/source/filters.rst
+++ b/docs/source/filters.rst
@@ -29,6 +29,7 @@ Filtering API
-------------
.. autofunction:: filter2d
+.. autofunction:: filter2d_separable
.. autofunction:: filter3d
Kernels
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.py
index 9bfd67fab..cea39ede2 100644
--- a/kornia/filters/__init__.py
+++ b/kornia/filters/__init__.py
@@ -1,7 +1,7 @@
from .blur import box_blur, BoxBlur
from .blur_pool import blur_pool2d, BlurPool2D, max_blur_pool2d, MaxBlurPool2D
from .canny import Canny, canny
-from .filter import filter2d, filter2D, filter3d, filter3D
+from .filter import filter2d, filter2D, filter2d_separable, filter3d, filter3D
from .gaussian import gaussian_blur2d, GaussianBlur2d
from .kernels import (
gaussian,
@@ -50,6 +50,7 @@ __all__ = [
"motion_blur",
"motion_blur3d",
"filter2d",
+ "filter2d_separable",
"filter3d",
"filter2D",
"filter3D",
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index adeef2698..030773413 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -73,10 +73,10 @@ def filter2d(
[0., 0., 0., 0., 0.]]]])
"""
if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input border_type is not torch.Tensor. Got {type(input)}")
+ raise TypeError(f"Input input is not torch.Tensor. Got {type(input)}")
if not isinstance(kernel, torch.Tensor):
- raise TypeError(f"Input border_type is not torch.Tensor. Got {type(kernel)}")
+ raise TypeError(f"Input kernel is not torch.Tensor. Got {type(kernel)}")
if not isinstance(border_type, str):
raise TypeError(f"Input border_type is not string. Got {type(border_type)}")
@@ -94,8 +94,8 @@ def filter2d(
if not len(input.shape) == 4:
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
- if not len(kernel.shape) == 3 and kernel.shape[0] != 1:
- raise ValueError(f"Invalid kernel shape, we expect 1xHxW. Got: {kernel.shape}")
+ if (not len(kernel.shape) == 3) and not ((kernel.shape[0] == 0) or (kernel.shape[0] == input.shape[0])):
+ raise ValueError(f"Invalid kernel shape, we expect 1xHxW or BxHxW. Got: {kernel.shape}")
# prepare kernel
b, c, h, w = input.shape
@@ -128,6 +128,58 @@ def filter2d(
return out
+def filter2d_separable(input: torch.Tensor,
+ kernel_x: torch.Tensor,
+ kernel_y: torch.Tensor,
+ border_type: str = 'reflect',
+ normalized: bool = False,
+ padding: str = 'same') -> torch.Tensor:
+ r"""Convolve a tensor with two 1d kernels, in x and y directions.
+
+ The function applies a given kernel to a tensor. The kernel is applied
+ independently at each depth channel of the tensor. Before applying the
+ kernel, the function applies padding according to the specified mode so
+ that the output remains in the same shape.
+
+ Args:
+ input: the input tensor with shape of
+ :math:`(B, C, H, W)`.
+ kernel_x: the kernel to be convolved with the input
+ tensor. The kernel shape must be :math:`(1, kW)` or :math:`(B, kW)`.
+ kernel_y: the kernel to be convolved with the input
+ tensor. The kernel shape must be :math:`(1, kH)` or :math:`(B, kH)`.
+ border_type: the padding mode to be applied before convolving.
+ The expected modes are: ``'constant'``, ``'reflect'``,
+ ``'replicate'`` or ``'circular'``.
+ normalized: If True, kernel will be L1 normalized.
+ padding: This defines the type of padding.
+ 2 modes available ``'same'`` or ``'valid'``.
+
+ Return:
+ torch.Tensor: the convolved tensor of same size and numbers of channels
+ as the input with shape :math:`(B, C, H, W)`.
+
+ Example:
+ >>> input = torch.tensor([[[
+ ... [0., 0., 0., 0., 0.],
+ ... [0., 0., 0., 0., 0.],
+ ... [0., 0., 5., 0., 0.],
+ ... [0., 0., 0., 0., 0.],
+ ... [0., 0., 0., 0., 0.],]]])
+ >>> kernel = torch.ones(1, 3)
+
+ >>> filter2d_separable(input, kernel, kernel, padding='same')
+ 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.]]]])
+ """
+ out_x = filter2d(input, kernel_x.unsqueeze(0), border_type, normalized, padding)
+ out = filter2d(out_x, kernel_y.unsqueeze(-1), border_type, normalized, padding)
+ return out
+
+
def filter3d(
input: torch.Tensor, kernel: torch.Tensor, border_type: str = 'replicate', normalized: bool = False
) -> torch.Tensor:
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 520441aad..74e104f44 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -4,12 +4,14 @@ import torch
import torch.nn as nn
import kornia
-from kornia.filters.kernels import get_gaussian_kernel2d
+from kornia.filters.kernels import get_gaussian_kernel1d, get_gaussian_kernel2d
-def gaussian_blur2d(
- input: torch.Tensor, kernel_size: Tuple[int, int], sigma: Tuple[float, float], border_type: str = 'reflect'
-) -> torch.Tensor:
+def gaussian_blur2d(input: torch.Tensor,
+ kernel_size: Tuple[int, int],
+ sigma: Tuple[float, float],
+ 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
@@ -24,6 +26,7 @@ def gaussian_blur2d(
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)`.
@@ -38,9 +41,14 @@ def gaussian_blur2d(
>>> 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)
+ 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 = kornia.filters.filter2d_separable(input, kernel_x[None], kernel_y[None], border_type)
+ else:
+ kernel: torch.Tensor = get_gaussian_kernel2d(kernel_size, sigma)
+ out = kornia.filters.filter2d(input, kernel[None], border_type)
+ return out
class GaussianBlur2d(nn.Module):
@@ -55,6 +63,7 @@ class GaussianBlur2d(nn.Module):
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.
@@ -72,11 +81,16 @@ class GaussianBlur2d(nn.Module):
torch.Size([2, 4, 5, 5])
"""
- def __init__(self, kernel_size: Tuple[int, int], sigma: Tuple[float, float], border_type: str = 'reflect') -> None:
+ def __init__(self,
+ kernel_size: Tuple[int, int],
+ sigma: Tuple[float, float],
+ border_type: str = 'reflect',
+ separable: bool = True) -> None:
super().__init__()
self.kernel_size: Tuple[int, int] = kernel_size
self.sigma: Tuple[float, float] = sigma
self.border_type = border_type
+ self.separable = separable
def __repr__(self) -> str:
return (
@@ -89,8 +103,14 @@ class GaussianBlur2d(nn.Module):
+ ', '
+ 'border_type='
+ self.border_type
+ + 'separable='
+ + str(self.separable)
+ ')'
)
def forward(self, input: torch.Tensor) -> torch.Tensor:
- return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type)
+ return gaussian_blur2d(input,
+ self.kernel_size,
+ self.sigma,
+ self.border_type,
+ self.separable)
diff --git a/test/filters/test_filters.py b/test/filters/test_filters.py
index 715830012..6af3e6314 100644
--- a/test/filters/test_filters.py
+++ b/test/filters/test_filters.py
@@ -268,6 +268,17 @@ class TestFilter2D:
actual = kornia.filter2d(inp, kernel, padding=padding)
assert_close(actual, actual)
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_separable(self, padding, device, dtype):
+ batch_size = 3
+ inp = torch.rand(3, 9, 9, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
+ kernel_x = torch.ones(1, 3, device=device, dtype=dtype)
+ kernel_y = torch.ones(1, 3, device=device, dtype=dtype)
+ kernel = kernel_y.t() @ kernel_x
+ out = kornia.filter2d(inp, kernel[None], padding=padding)
+ out_sep = kornia.filters.filter2d_separable(inp, kernel_x, kernel_y, padding=padding)
+ assert_close(out, out_sep)
+
def test_gradcheck(self, device):
kernel = torch.rand(1, 3, 3, device=device)
input = torch.ones(1, 1, 7, 8, device=device)
diff --git a/test/filters/test_gaussian.py b/test/filters/test_gaussian.py
index e7222da3d..fcdf8f8c1 100644
--- a/test/filters/test_gaussian.py
+++ b/test/filters/test_gaussian.py
@@ -40,12 +40,30 @@ def test_get_gaussian_kernel2d(ksize_x, ksize_y, sigma):
assert kernel.sum().item() == pytest.approx(1.0)
[email protected]("ksize_x", [5, 11])
[email protected]("ksize_y", [3, 7])
[email protected]("sigma", [1.5, 2.1])
+def test_separable(ksize_x, ksize_y, sigma, device, dtype):
+ input = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)
+ out = kornia.filters.gaussian_blur2d(input,
+ (ksize_x, ksize_y),
+ (sigma, sigma),
+ "replicate",
+ separable=False)
+ out_sep = kornia.filters.gaussian_blur2d(input,
+ (ksize_x, ksize_y),
+ (sigma, 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):
kernel_size = (5, 7)
sigma = (1.5, 2.1)
-
input = torch.rand(batch_shape, device=device, dtype=dtype)
actual = kornia.filters.gaussian_blur2d(input, kernel_size, sigma, "replicate")
assert actual.shape == batch_shape