Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(filters): add correlate2d/convolve2d/correlate3d/convolve3d aliases (#3604)

Tyson Cungd7fb2e2b60f8
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.py
index 4095dafe6..112daae4e 100644
--- a/kornia/filters/__init__.py
+++ b/kornia/filters/__init__.py
@@ -34,7 +34,7 @@ from .blur_pool import (
)
from .canny import Canny, canny
from .dissolving import StableDiffusionDissolving
-from .filter import fft_conv, filter2d, filter2d_separable, filter3d
+from .filter import convolve2d, convolve3d, correlate2d, correlate3d, fft_conv, filter2d, filter2d_separable, filter3d
from .gaussian import GaussianBlur2d, gaussian_blur2d, gaussian_blur2d_t
from .guided import GuidedBlur, guided_blur
from .in_range import InRange, in_range
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 893bdde7c..58e3d1643 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -208,7 +208,11 @@ def filter2d_separable(
def filter3d(
- input: torch.Tensor, kernel: torch.Tensor, border_type: str = "replicate", normalized: bool = False
+ input: torch.Tensor,
+ kernel: torch.Tensor,
+ border_type: str = "replicate",
+ normalized: bool = False,
+ behaviour: str = "corr",
) -> torch.Tensor:
r"""Convolve a tensor with a 3d kernel.
@@ -226,6 +230,8 @@ def filter3d(
The expected modes are: ``'constant'``,
``'replicate'`` or ``'circular'``.
normalized: If True, kernel will be L1 normalized.
+ behaviour: defines the convolution mode -- correlation (default), using pytorch conv3d,
+ or true convolution (kernel is flipped). The expected values are: ``'corr'``, ``'conv'``.
Return:
the convolved tensor of same size and numbers of channels
@@ -280,9 +286,17 @@ def filter3d(
f"Invalid border, gotcha {border_type}. Expected one of {_VALID_BORDERS}",
)
+ KORNIA_CHECK(
+ str(behaviour).lower() in _VALID_BEHAVIOUR,
+ f"Invalid behaviour mode, gotcha {behaviour}. Expected one of {_VALID_BEHAVIOUR}",
+ )
+
# prepare kernel
b, c, d, h, w = input.shape
- tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
+ if str(behaviour).lower() == "conv":
+ tmp_kernel = kernel.flip((-3, -2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)
+ else:
+ tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
if normalized:
bk, dk, hk, wk = kernel.shape
@@ -441,3 +455,149 @@ def fft_conv(
output = output[..., :crop_h, :crop_w].contiguous()
return output
+
+
+def correlate2d(
+ input: torch.Tensor,
+ kernel: torch.Tensor,
+ border_type: str = "reflect",
+ normalized: bool = False,
+ padding: str = "same",
+) -> torch.Tensor:
+ r"""Correlate a tensor with a 2d kernel.
+
+ Convenience alias for :func:`filter2d` with ``behaviour='corr'`` (cross-correlation).
+ See :func:`filter2d` for full documentation.
+
+ .. seealso:: :func:`convolve2d`, :func:`filter2d`
+
+ Args:
+ input: the input tensor with shape of :math:`(B, C, H, W)`.
+ kernel: the kernel to be correlated with the input tensor.
+ The kernel shape must be :math:`(1, kH, kW)` or :math:`(B, kH, kW)`.
+ 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:
+ Tensor: the correlated 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, 3)
+ >>> correlate2d(input, 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.]]]])
+ """
+ return filter2d(input, kernel, border_type=border_type, normalized=normalized, padding=padding, behaviour="corr")
+
+
+def convolve2d(
+ input: torch.Tensor,
+ kernel: torch.Tensor,
+ border_type: str = "reflect",
+ normalized: bool = False,
+ padding: str = "same",
+) -> torch.Tensor:
+ r"""Convolve a tensor with a 2d kernel using true convolution.
+
+ Convenience alias for :func:`filter2d` with ``behaviour='conv'`` (true convolution,
+ where the kernel is flipped before applying).
+ See :func:`filter2d` for full documentation.
+
+ .. seealso:: :func:`correlate2d`, :func:`filter2d`
+
+ Args:
+ input: the input tensor with shape of :math:`(B, C, H, W)`.
+ kernel: the kernel to be convolved with the input tensor.
+ The kernel shape must be :math:`(1, kH, kW)` or :math:`(B, kH, kW)`.
+ 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:
+ 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, 3)
+ >>> convolve2d(input, 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.]]]])
+ """
+ return filter2d(input, kernel, border_type=border_type, normalized=normalized, padding=padding, behaviour="conv")
+
+
+def correlate3d(
+ input: torch.Tensor,
+ kernel: torch.Tensor,
+ border_type: str = "replicate",
+ normalized: bool = False,
+) -> torch.Tensor:
+ r"""Correlate a tensor with a 3d kernel.
+
+ Convenience alias for :func:`filter3d` with ``behaviour='corr'`` (cross-correlation).
+ See :func:`filter3d` for full documentation.
+
+ .. seealso:: :func:`convolve3d`, :func:`filter3d`
+
+ Args:
+ input: the input tensor with shape of :math:`(B, C, D, H, W)`.
+ kernel: the kernel to be correlated with the input tensor.
+ The kernel shape must be :math:`(1, kD, kH, kW)` or :math:`(B, kD, kH, kW)`.
+ 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.
+
+ Return:
+ Tensor: the correlated tensor of same size and numbers of channels as the input.
+ """
+ return filter3d(input, kernel, border_type=border_type, normalized=normalized, behaviour="corr")
+
+
+def convolve3d(
+ input: torch.Tensor,
+ kernel: torch.Tensor,
+ border_type: str = "replicate",
+ normalized: bool = False,
+) -> torch.Tensor:
+ r"""Convolve a tensor with a 3d kernel using true convolution.
+
+ Convenience alias for :func:`filter3d` with ``behaviour='conv'`` (true convolution,
+ where the kernel is flipped before applying).
+ See :func:`filter3d` for full documentation.
+
+ .. seealso:: :func:`correlate3d`, :func:`filter3d`
+
+ Args:
+ input: the input tensor with shape of :math:`(B, C, D, H, W)`.
+ kernel: the kernel to be convolved with the input tensor.
+ The kernel shape must be :math:`(1, kD, kH, kW)` or :math:`(B, kD, kH, kW)`.
+ 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.
+
+ Return:
+ Tensor: the convolved tensor of same size and numbers of channels as the input.
+ """
+ return filter3d(input, kernel, border_type=border_type, normalized=normalized, behaviour="conv")
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index f58cea041..e8cd2381c 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -20,7 +20,16 @@ import pytest
import torch
from kornia.core._compat import torch_version_le
-from kornia.filters import fft_conv, filter2d, filter2d_separable, filter3d
+from kornia.filters import (
+ convolve2d,
+ convolve3d,
+ correlate2d,
+ correlate3d,
+ fft_conv,
+ filter2d,
+ filter2d_separable,
+ filter3d,
+)
from testing.base import BaseTester
@@ -1102,3 +1111,55 @@ class TestFilter2D_fftconv(BaseTester):
actual = op_optimized(data, kernel, padding=padding, normalized=normalized)
self.assert_close(actual, expected)
+
+
+class TestCorrelate2d:
+ def test_equivalent_to_filter2d_corr(self, device, dtype):
+ inp = torch.rand(1, 1, 7, 8, device=device, dtype=dtype)
+ kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ expected = filter2d(inp, kernel, behaviour="corr")
+ result = correlate2d(inp, kernel)
+ assert torch.allclose(result, expected)
+
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_smoke(self, border_type, padding, device, dtype):
+ inp = torch.ones(1, 1, 7, 8, device=device, dtype=dtype)
+ kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ out = correlate2d(inp, kernel, border_type=border_type, padding=padding)
+ assert isinstance(out, torch.Tensor)
+
+
+class TestConvolve2d:
+ def test_equivalent_to_filter2d_conv(self, device, dtype):
+ inp = torch.rand(1, 1, 7, 8, device=device, dtype=dtype)
+ kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ expected = filter2d(inp, kernel, behaviour="conv")
+ result = convolve2d(inp, kernel)
+ assert torch.allclose(result, expected)
+
+ def test_differs_from_correlate_asymmetric_kernel(self, device, dtype):
+ inp = torch.rand(1, 1, 7, 8, device=device, dtype=dtype)
+ # Asymmetric kernel so corr != conv
+ kernel = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]], device=device, dtype=dtype)
+ corr = correlate2d(inp, kernel)
+ conv = convolve2d(inp, kernel)
+ assert not torch.allclose(corr, conv)
+
+
+class TestCorrelate3d:
+ def test_equivalent_to_filter3d_corr(self, device, dtype):
+ inp = torch.rand(1, 1, 5, 7, 8, device=device, dtype=dtype)
+ kernel = torch.rand(1, 3, 3, 3, device=device, dtype=dtype)
+ expected = filter3d(inp, kernel, behaviour="corr")
+ result = correlate3d(inp, kernel)
+ assert torch.allclose(result, expected)
+
+
+class TestConvolve3d:
+ def test_equivalent_to_filter3d_conv(self, device, dtype):
+ inp = torch.rand(1, 1, 5, 7, 8, device=device, dtype=dtype)
+ kernel = torch.rand(1, 3, 3, 3, device=device, dtype=dtype)
+ expected = filter3d(inp, kernel, behaviour="conv")
+ result = convolve3d(inp, kernel)
+ assert torch.allclose(result, expected)