Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(filters): export correlate2d, convolve2d, correlate3d and convolve3d (#5249)

Dmytro Mishkinc727a04210fa
diff --git a/changelog.d/5249.added.md b/changelog.d/5249.added.md
new file mode 100644
index 000000000..ad00971a1
--- /dev/null
+++ b/changelog.d/5249.added.md
@@ -0,0 +1 @@
+`correlate2d`, `convolve2d`, `correlate3d` and `convolve3d` are now listed in `kornia.filters.__all__`, so `from kornia.filters import *` brings them, and appear on the Filtering API page and in the API-surface inventory. They were already importable from `kornia.filters` by name, and equal `filter2d` / `filter3d` with `behaviour='corr'` / `'conv'`. The two 2-D docstrings now state the output shape for `padding='valid'`, and each of the four has an example that shows how correlation and convolution differ.
diff --git a/docs/source/filters.filtering_api.rst b/docs/source/filters.filtering_api.rst
index ac51fe363..424e92434 100644
--- a/docs/source/filters.filtering_api.rst
+++ b/docs/source/filters.filtering_api.rst
@@ -6,5 +6,9 @@ Filtering API
Convolve an image with your own kernel. These are the primitives the blur and edge operators are built on.
.. autofunction:: filter2d
+.. autofunction:: correlate2d
+.. autofunction:: convolve2d
.. autofunction:: filter2d_separable
+.. autofunction:: correlate3d
+.. autofunction:: convolve3d
.. autofunction:: filter3d
diff --git a/docs/source/filters.rst b/docs/source/filters.rst
index 459e62ae1..39d63d5d9 100644
--- a/docs/source/filters.rst
+++ b/docs/source/filters.rst
@@ -19,7 +19,9 @@ counterpart on the same page.
* - :doc:`Thresholding <filters.segmentation>`
- Range thresholding and Otsu's threshold.
* - :doc:`filters.filtering_api`
- - Apply your own 2D, separable or 3D kernels with :func:`filter2d`, :func:`filter2d_separable` and :func:`filter3d`.
+ - Apply your own 2D, separable or 3D kernels with :func:`filter2d`, :func:`filter2d_separable` and :func:`filter3d`,
+ or by correlation or convolution with :func:`correlate2d`, :func:`convolve2d`, :func:`correlate3d` and
+ :func:`convolve3d`.
* - :doc:`filters.kernels`
- Gaussian, Hanning, Laplacian and motion kernels used by the filters above.
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.py
index 112daae4e..720fa72d2 100644
--- a/kornia/filters/__init__.py
+++ b/kornia/filters/__init__.py
@@ -94,6 +94,10 @@ __all__ = [
"blur_pool2d",
"box_blur",
"canny",
+ "convolve2d",
+ "convolve3d",
+ "correlate2d",
+ "correlate3d",
"edge_aware_blur_pool2d",
"fft_conv",
"filter2d",
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index bdc9fb1c3..91f6c63fc 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -488,23 +488,26 @@ def correlate2d(
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)`.
+ the correlated tensor. With ``padding='same'`` it has the input's shape :math:`(B, C, H, W)`. With
+ ``padding='valid'`` it has shape :math:`(B, C, H - kH + 1, W - kW + 1)`.
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')
+ Correlating an impulse gives the kernel rotated by 180 degrees; :func:`convolve2d` gives the kernel itself.
+
+ >>> input = torch.zeros(1, 1, 5, 5)
+ >>> input[..., 2, 2] = 1.0
+ >>> kernel = torch.arange(1.0, 10.0).reshape(1, 3, 3)
+ >>> correlate2d(input, kernel)
tensor([[[[0., 0., 0., 0., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
+ [0., 9., 8., 7., 0.],
+ [0., 6., 5., 4., 0.],
+ [0., 3., 2., 1., 0.],
[0., 0., 0., 0., 0.]]]])
+
+ With ``padding='valid'`` the output loses ``kH - 1`` rows and ``kW - 1`` columns:
+
+ >>> correlate2d(input, kernel, padding='valid').shape
+ torch.Size([1, 1, 3, 3])
"""
return filter2d(input, kernel, border_type=border_type, normalized=normalized, padding=padding, behaviour="corr")
@@ -519,7 +522,7 @@ def convolve2d(
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).
+ where the kernel is flipped along both spatial axes, ``H`` and ``W``, before applying).
See :func:`filter2d` for full documentation.
.. seealso:: :func:`correlate2d`, :func:`filter2d`
@@ -534,23 +537,26 @@ def convolve2d(
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)`.
+ the convolved tensor. With ``padding='same'`` it has the input's shape :math:`(B, C, H, W)`. With
+ ``padding='valid'`` it has shape :math:`(B, C, H - kH + 1, W - kW + 1)`.
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')
+ Convolving an impulse gives the kernel itself; :func:`correlate2d` gives it rotated by 180 degrees.
+
+ >>> input = torch.zeros(1, 1, 5, 5)
+ >>> input[..., 2, 2] = 1.0
+ >>> kernel = torch.arange(1.0, 10.0).reshape(1, 3, 3)
+ >>> convolve2d(input, kernel)
tensor([[[[0., 0., 0., 0., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
+ [0., 1., 2., 3., 0.],
+ [0., 4., 5., 6., 0.],
+ [0., 7., 8., 9., 0.],
[0., 0., 0., 0., 0.]]]])
+
+ With ``padding='valid'`` the output loses ``kH - 1`` rows and ``kW - 1`` columns:
+
+ >>> convolve2d(input, kernel, padding='valid').shape
+ torch.Size([1, 1, 3, 3])
"""
return filter2d(input, kernel, border_type=border_type, normalized=normalized, padding=padding, behaviour="conv")
@@ -577,7 +583,21 @@ def correlate3d(
normalized: If True, kernel will be L1 normalized.
Return:
- Tensor: the correlated tensor of same size and numbers of channels as the input.
+ the correlated tensor, with the input's shape :math:`(B, C, D, H, W)`.
+
+ Example:
+ Correlation applies the kernel as given. A single tap at the kernel's first corner, index ``(0, 0, 0)`` in
+ ``(D, H, W)``, makes each output voxel copy the input voxel one step back along all three axes. An impulse at
+ the centre ``(1, 1, 1)`` of a 3x3x3 volume therefore lands in the volume's last corner, ``(2, 2, 2)``.
+ :func:`convolve3d` puts it in the first corner, ``(0, 0, 0)``.
+
+ >>> input = torch.zeros(1, 1, 3, 3, 3)
+ >>> input[0, 0, 1, 1, 1] = 1.0 # the impulse, at the centre of the volume
+ >>> kernel = torch.zeros(1, 3, 3, 3)
+ >>> kernel[0, 0, 0, 0] = 1.0 # the tap, at the kernel's first corner
+ >>> output = correlate3d(input, kernel)
+ >>> output[0, 0].nonzero() # (D, H, W) index of the one non-zero output voxel
+ tensor([[2, 2, 2]])
"""
return filter3d(input, kernel, border_type=border_type, normalized=normalized, behaviour="corr")
@@ -591,7 +611,7 @@ def convolve3d(
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).
+ where the kernel is flipped along all three axes, ``D``, ``H`` and ``W``, before applying).
See :func:`filter3d` for full documentation.
.. seealso:: :func:`correlate3d`, :func:`filter3d`
@@ -605,6 +625,20 @@ def convolve3d(
normalized: If True, kernel will be L1 normalized.
Return:
- Tensor: the convolved tensor of same size and numbers of channels as the input.
+ the convolved tensor, with the input's shape :math:`(B, C, D, H, W)`.
+
+ Example:
+ Convolution flips the kernel along all three axes, which moves a tap at the kernel's first corner, index
+ ``(0, 0, 0)`` in ``(D, H, W)``, to its last corner. Each output voxel then copies the input voxel one step
+ ahead along all three axes, so an impulse at the centre ``(1, 1, 1)`` of a 3x3x3 volume lands in the volume's
+ first corner, ``(0, 0, 0)``. :func:`correlate3d` puts it in the last corner, ``(2, 2, 2)``.
+
+ >>> input = torch.zeros(1, 1, 3, 3, 3)
+ >>> input[0, 0, 1, 1, 1] = 1.0 # the impulse, at the centre of the volume
+ >>> kernel = torch.zeros(1, 3, 3, 3)
+ >>> kernel[0, 0, 0, 0] = 1.0 # the tap, at the kernel's first corner
+ >>> output = convolve3d(input, kernel)
+ >>> output[0, 0].nonzero() # (D, H, W) index of the one non-zero output voxel
+ tensor([[0, 0, 0]])
"""
return filter3d(input, kernel, border_type=border_type, normalized=normalized, behaviour="conv")
diff --git a/tests/api_surface.json b/tests/api_surface.json
index f87c4ad9a..4b2d44c6d 100644
--- a/tests/api_surface.json
+++ b/tests/api_surface.json
@@ -274,6 +274,10 @@
"blur_pool2d",
"box_blur",
"canny",
+ "convolve2d",
+ "convolve3d",
+ "correlate2d",
+ "correlate3d",
"edge_aware_blur_pool2d",
"fft_conv",
"filter2d",
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index 21d239740..87da2d0b2 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -1127,6 +1127,66 @@ class TestFilter2D_fftconv(BaseTester):
self.assert_close(actual, expected)
+class TestCorrelateConvolveExports:
+ """The four correlate/convolve aliases are public in every sense kornia uses (#5161)."""
+
+ NAMES = ("correlate2d", "convolve2d", "correlate3d", "convolve3d")
+
+ def test_from_import_names_the_defining_objects(self):
+ import importlib
+
+ from kornia.filters import convolve2d, convolve3d, correlate2d, correlate3d
+
+ defining = importlib.import_module("kornia.filters.filter")
+ imported = {
+ "correlate2d": correlate2d,
+ "convolve2d": convolve2d,
+ "correlate3d": correlate3d,
+ "convolve3d": convolve3d,
+ }
+ assert set(imported) == set(self.NAMES)
+ for name, func in imported.items():
+ assert func is getattr(defining, name), name
+ assert func.__module__ == "kornia.filters.filter", name
+
+ @pytest.mark.parametrize("name", NAMES)
+ def test_listed_in_all(self, name):
+ import kornia.filters as KF
+
+ # `from kornia.filters import *` binds exactly the names in `__all__`.
+ assert name in KF.__all__
+
+ def test_all_is_well_formed(self):
+ import kornia.filters as KF
+
+ assert len(KF.__all__) == len(set(KF.__all__))
+ assert all(hasattr(KF, name) for name in KF.__all__)
+
+
+class TestCorrelateConvolveShapes(BaseTester):
+ """The output shapes the four docstrings state, for odd and even kernels."""
+
+ @pytest.mark.parametrize("func", [correlate2d, convolve2d])
+ @pytest.mark.parametrize("kernel_size", [(1, 1), (3, 3), (2, 2), (4, 3), (2, 5)])
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_cardinality_2d(self, func, kernel_size, padding, device, dtype):
+ b, c, h, w = 2, 3, 7, 8
+ kh, kw = kernel_size
+ inp = torch.ones(b, c, h, w, device=device, dtype=dtype)
+ kernel = torch.ones(1, kh, kw, device=device, dtype=dtype)
+ expected = (b, c, h, w) if padding == "same" else (b, c, h - kh + 1, w - kw + 1)
+ # the shape does not depend on the border; "constant" also runs in half precision on old torch
+ assert func(inp, kernel, border_type="constant", padding=padding).shape == expected
+
+ @pytest.mark.parametrize("func", [correlate3d, convolve3d])
+ @pytest.mark.parametrize("kernel_size", [(1, 1, 1), (3, 3, 3), (2, 2, 2), (4, 3, 2)])
+ def test_cardinality_3d(self, func, kernel_size, device, dtype):
+ inp = torch.ones(2, 3, 5, 7, 8, device=device, dtype=dtype)
+ kernel = torch.ones(1, *kernel_size, device=device, dtype=dtype)
+ # the shape does not depend on the border; "constant" also runs in half precision on old torch
+ assert func(inp, kernel, border_type="constant").shape == inp.shape
+
+
class TestCorrelate2d(BaseTester):
def test_equivalent_to_filter2d_corr(self, device, dtype):
inp = torch.rand(1, 1, 7, 8, device=device, dtype=dtype)