Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(filters): Convention blocks and pins for filter2d, filter3d, fft_conv and the kernel builders (batch 11a) (#5230)

Dmytro Mishkin7b5d67dc92e7
diff --git a/changelog.d/5230.added.md b/changelog.d/5230.added.md
new file mode 100644
index 000000000..dd18580ed
--- /dev/null
+++ b/changelog.d/5230.added.md
@@ -0,0 +1 @@
+Convention blocks for `filter2d`, `filter2d_separable`, `filter3d`, `fft_conv` and the kernel builders: correlation vs `behaviour='conv'`, the `border_type` vocabulary, the `(k - 1) // 2` anchor of an even kernel, kernel batch and normalisation rules, the Rodrigues axis-angle vector used by `get_motion_kernel3d`, and the orientation, sign and normalisation of every derivative kernel. A new Filtering section on the Conventions page maps the border modes, the correlation rule and the even-kernel anchor to scipy and OpenCV. `fft_conv` and ten kernel builders are added to the API reference.
diff --git a/docs/source/filters.filtering_api.rst b/docs/source/filters.filtering_api.rst
index 424e92434..855140c57 100644
--- a/docs/source/filters.filtering_api.rst
+++ b/docs/source/filters.filtering_api.rst
@@ -3,7 +3,8 @@ Filtering API
.. currentmodule:: kornia.filters
-Convolve an image with your own kernel. These are the primitives the blur and edge operators are built on.
+Filter an image with your own kernel, by correlation (the default) or convolution. The box, Gaussian and motion blurs
+and :func:`laplacian` are built on :func:`filter2d`, :func:`filter2d_separable` and :func:`filter3d`.
.. autofunction:: filter2d
.. autofunction:: correlate2d
@@ -12,3 +13,4 @@ Convolve an image with your own kernel. These are the primitives the blur and ed
.. autofunction:: correlate3d
.. autofunction:: convolve3d
.. autofunction:: filter3d
+.. autofunction:: fft_conv
diff --git a/docs/source/filters.kernels.rst b/docs/source/filters.kernels.rst
index 7f040caaf..df488de9b 100644
--- a/docs/source/filters.kernels.rst
+++ b/docs/source/filters.kernels.rst
@@ -10,8 +10,18 @@ Kernel generators, useful with the :doc:`filters.filtering_api` or to inspect wh
.. autofunction:: get_gaussian_erf_kernel1d
.. autofunction:: get_gaussian_discrete_kernel1d
.. autofunction:: get_gaussian_kernel2d
+.. autofunction:: get_gaussian_kernel3d
+.. autofunction:: get_box_kernel1d
+.. autofunction:: get_box_kernel2d
+.. autofunction:: get_binary_kernel2d
.. autofunction:: get_hanning_kernel1d
.. autofunction:: get_hanning_kernel2d
.. autofunction:: get_laplacian_kernel1d
.. autofunction:: get_laplacian_kernel2d
+.. autofunction:: laplacian_1d
+.. autofunction:: get_spatial_gradient_kernel2d
+.. autofunction:: get_spatial_gradient_kernel3d
+.. autofunction:: get_sobel_kernel2d
+.. autofunction:: get_diff_kernel2d
.. autofunction:: get_motion_kernel2d
+.. autofunction:: get_motion_kernel3d
diff --git a/docs/source/filters.rst b/docs/source/filters.rst
index 39d63d5d9..9e498b833 100644
--- a/docs/source/filters.rst
+++ b/docs/source/filters.rst
@@ -21,9 +21,9 @@ counterpart on the same page.
* - :doc:`filters.filtering_api`
- 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`.
+ :func:`convolve3d`; :func:`fft_conv` filters in the frequency domain.
* - :doc:`filters.kernels`
- - Gaussian, Hanning, Laplacian and motion kernels used by the filters above.
+ - Gaussian, box, Hanning, Laplacian, gradient and motion kernels used by the filters above.
.. toctree::
:hidden:
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index ab41cbea4..f5f38e973 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -543,6 +543,86 @@ is a ``[row, col]`` index and ``border_type`` takes torch's pad names. Below, ``
The equivalences cover empty ``geodesic`` windows too: scipy, scikit-image and kornia all return ``-inf`` from
such a window in a dilation and ``+inf`` in an erosion, whatever the data range.
+.. _filtering-conventions:
+
+Filtering
+---------
+
+:doc:`kornia.filters </filters>` follows torch's vocabulary: its kernels are correlated by default, ``border_type``
+takes the :func:`torch.nn.functional.pad` mode names, and an even kernel is anchored where
+``F.conv2d(padding='same')`` anchors it. The correlation matches ``cv2.filter2D`` and ``scipy.ndimage.correlate``; the
+border names and the even-kernel anchor do not.
+
+- :func:`~kornia.filters.filter2d`, :func:`~kornia.filters.filter3d` and :func:`~kornia.filters.fft_conv`
+ **correlate** by default, as ``cv2.filter2D`` and ``scipy.ndimage.correlate`` do; ``behaviour='conv'`` flips the
+ kernel first, as ``scipy.ndimage.convolve`` does. :func:`~kornia.filters.correlate2d` and
+ :func:`~kornia.filters.convolve2d` are :func:`~kornia.filters.filter2d` with ``behaviour`` fixed to ``'corr'`` and
+ ``'conv'``; :func:`~kornia.filters.correlate3d` and :func:`~kornia.filters.convolve3d` are the same for
+ :func:`~kornia.filters.filter3d`.
+- :func:`~kornia.filters.filter2d_separable` takes ``kernel_x`` (along ``W``) before ``kernel_y``, the order of
+ ``cv2.sepFilter2D(src, ddepth, kernelX, kernelY)``.
+
+The border modes, shown padding ``a b c d`` by two samples on each side. :doc:`kornia.morphology </morphology>` uses
+the same names for its non-``geodesic`` borders:
+
+.. list-table::
+ :header-rows: 1
+
+ * - kornia ``border_type`` (the ``F.pad`` mode)
+ - pads ``a b c d`` to
+ - ``scipy.ndimage`` ``mode``
+ - OpenCV ``borderType``
+ * - ``reflect``, the default of ``filter2d``, ``filter2d_separable`` and ``fft_conv``
+ - ``c b | a b c d | c b``
+ - ``mirror``
+ - ``BORDER_REFLECT_101``, the ``cv2.filter2D`` default
+ * - ``replicate``, the default of ``filter3d``
+ - ``a a | a b c d | d d``
+ - ``nearest``
+ - ``BORDER_REPLICATE``
+ * - ``circular``
+ - ``c d | a b c d | a b``
+ - ``wrap``
+ - ``BORDER_WRAP``, which ``cv2.filter2D`` rejects for small kernels
+ * - ``constant``
+ - ``0 0 | a b c d | 0 0``
+ - ``constant`` with ``cval=0``
+ - ``BORDER_CONSTANT`` with value 0
+ * - no kornia mode
+ - ``b a | a b c d | d c``
+ - ``reflect``, the scipy default
+ - ``BORDER_REFLECT``
+
+An even kernel has no centre tap. The filters anchor a kernel ``k`` taps long at ``(k - 1) // 2``, the anchor of
+``F.conv2d(padding='same')``. OpenCV and scipy anchor it at ``k // 2`` by default, and so does the default ``origin`` of
+:func:`~kornia.morphology.erosion` (see `Morphology`_), so along every even axis a correlated output sits one pixel
+before theirs; ``behaviour='conv'`` needs no shift (below). An odd kernel is anchored at its centre by all of them.
+For a kernel ``K`` of shape ``(kh, kw)``, with the border mapped by the table above:
+
+- ``filter2d(x, K[None])`` equals ``scipy.ndimage.correlate(x, K, origin=o)`` with ``o = -1`` on each even axis and
+ ``0`` on each odd one, and ``cv2.filter2D(x, -1, K, anchor=((kw - 1) // 2, (kh - 1) // 2))``.
+- ``filter2d(x, K[None], behaviour='conv')`` equals ``scipy.ndimage.convolve(x, K)`` at scipy's default origin, even
+ for an even ``K``.
+
+The kernel builders against their references:
+
+- :func:`~kornia.filters.get_gaussian_kernel1d` samples the Gaussian: for an odd ``k`` and ``sigma > 0`` it equals
+ ``cv2.getGaussianKernel(k, sigma)`` and the weights ``scipy.ndimage.gaussian_filter1d`` applies with
+ ``radius=k // 2``. :func:`~kornia.filters.get_gaussian_erf_kernel1d` is the pixel-integrated Gaussian and
+ :func:`~kornia.filters.get_gaussian_discrete_kernel1d` is Lindeberg's discrete Gaussian,
+ ``scipy.special.ive(abs(n), sigma**2)`` normalized, except for a large ``sigma`` (in float16, any ``sigma`` once
+ ``kernel_size`` is 5 or more), where its Bessel terms drift or overflow
+ (`#5227 <https://github.com/kornia/kornia/issues/5227>`_).
+- :func:`~kornia.filters.get_hanning_kernel1d` is the symmetric window of ``numpy.hanning(k)``,
+ ``scipy.signal.windows.hann(k)`` and ``torch.hann_window(k, periodic=False)``; torch's default periodic window
+ differs.
+- :func:`~kornia.filters.get_spatial_gradient_kernel2d` with ``('sobel', 1)`` stacks the outer products of OpenCV's
+ ``getDerivKernels(1, 0, 3)`` and ``getDerivKernels(0, 1, 3)``, and answers 8 to a unit slope, as ``cv2.Sobel`` and
+ ``scipy.ndimage.sobel`` do; scikit-image's ``sobel_h`` and ``sobel_v`` answer 2.
+- :func:`~kornia.filters.get_laplacian_kernel2d` of size 3 is the 8-neighbour stencil and estimates :math:`3 \nabla^2`,
+ where ``scipy.ndimage.laplace`` and ``cv2.Laplacian(ksize=1)`` return :math:`\nabla^2`, ``cv2.Laplacian(ksize=3)``
+ :math:`4 \nabla^2` and ``skimage.filters.laplace`` :math:`-\nabla^2`.
+
.. _two-view-conventions:
Two-view geometry
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 91f6c63fc..28d55f46d 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -59,12 +59,40 @@ def filter2d(
padding: str = "same",
behaviour: str = "corr",
) -> torch.Tensor:
- r"""Convolve a tensor with a 2d kernel.
+ r"""Filter a tensor with a 2d kernel, by cross-correlation unless ``behaviour='conv'``.
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.
+ independently at each channel of the tensor. With ``padding='same'`` the
+ input is first padded according to ``border_type``, so that the output
+ keeps the input's height and width.
+
+ Convention:
+ - The default ``behaviour='corr'`` is cross-correlation,
+ :math:`out[y, x] = \sum_{i, j} k[i, j] \, input[y + i - a_y, x + j - a_x]`, anchored at
+ :math:`(a_y, a_x)` = ``((kH - 1) // 2, (kW - 1) // 2)``: the centre of an odd kernel and, for an even size,
+ the tap before the middle. ``behaviour='conv'`` flips the kernel on both axes and keeps the anchor.
+ - ``border_type`` takes the :func:`torch.nn.functional.pad` mode names, and the default ``'reflect'`` mirrors
+ about the edge pixel without repeating it. :ref:`Filtering <filtering-conventions>` maps the modes and the
+ anchor onto scipy and OpenCV. With ``padding='same'``, ``'reflect'`` needs each axis longer than
+ ``k // 2`` for a kernel ``k`` taps long along it, and ``'circular'`` at least that long; a shorter axis
+ raises.
+ - A :math:`(1, kH, kW)` kernel is shared by the whole batch, and a :math:`(B, kH, kW)` kernel gives each
+ sample its own, shared by the sample's channels; there are no per-channel kernels.
+ - ``normalized=True`` divides each kernel by the sum of its absolute values, so a zero-sum derivative kernel
+ keeps its sign.
+ - The kernel is cast to the input's dtype and device and stays differentiable; the output has the input's
+ dtype.
+ - Known defects:
+
+ - a kernel batch that divides the input batch without matching it is not rejected: with 2 kernels for 4
+ samples, sample ``i`` is filtered with kernel ``i % 2``
+ (`#5154 <https://github.com/kornia/kornia/issues/5154>`_).
+ - an integer input casts the kernel to its dtype, so a fractional kernel truncates to 0: a uint8 image
+ filtered with a box kernel comes back as zeros, or the call raises where torch has no integer
+ convolution (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
+ - ``padding`` and ``border_type`` are checked case-insensitively but used as given: ``padding='SAME'``
+ returns the ``'valid'`` output and ``border_type='REFLECT'`` raises
+ (`#5156 <https://github.com/kornia/kornia/issues/5156>`_).
Args:
input: the input tensor with shape of
@@ -78,12 +106,12 @@ def filter2d(
padding: This defines the type of padding.
2 modes available ``'same'`` or ``'valid'``.
behaviour: defines the convolution mode -- correlation (default), using pytorch conv2d,
- or true convolution (kernel is flipped). 2 modes available ``'corr'`` or ``'conv'``.
-
+ or true convolution (kernel is flipped). 2 modes available ``'corr'`` or ``'conv'``.
Return:
- Tensor: the convolved tensor of same size and numbers of channels
- as the input with shape :math:`(B, C, H, W)`.
+ the filtered 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)`, and its pixel ``(0, 0)`` is the
+ ``'same'`` output at the anchor ``(a_y, a_x)``.
Example:
>>> input = torch.tensor([[[
@@ -160,12 +188,18 @@ def filter2d_separable(
normalized: bool = False,
padding: str = "same",
) -> torch.Tensor:
- r"""Convolve a tensor with two 1d kernels, in x and y directions.
+ r"""Correlate a tensor with two 1d kernels, one along x and one along y.
- 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.
+ The function applies the given kernels to a tensor. They are applied
+ independently at each channel of the tensor. With ``padding='same'`` the
+ input is first padded according to ``border_type``, so that the output
+ keeps the input's height and width.
+
+ Convention:
+ See the Convention block on :func:`~kornia.filters.filter2d`. The result equals
+ :func:`~kornia.filters.filter2d` with the outer-product kernel ``kernel_y[:, :, None] * kernel_x[:, None, :]``,
+ the even-size anchor included: ``kernel_x`` runs along ``W`` and comes first. There is no ``behaviour``
+ argument, so the kernels are always correlated. ``normalized=True`` normalizes each 1d kernel.
Args:
input: the input tensor with shape of
@@ -182,8 +216,8 @@ def filter2d_separable(
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 filtered tensor, of the shape :func:`~kornia.filters.filter2d` returns for the same ``padding``:
+ :math:`(B, C, H, W)` with ``padding='same'``.
Example:
>>> input = torch.tensor([[[
@@ -213,20 +247,28 @@ def filter3d(
normalized: bool = False,
behaviour: str = "corr",
) -> torch.Tensor:
- r"""Convolve a tensor with a 3d kernel.
+ r"""Filter a tensor with a 3d kernel, by cross-correlation unless ``behaviour='conv'``.
The function applies a given kernel to a tensor. The kernel is applied
- independently at each depth channel of the tensor. Before applying the
+ independently at each 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.
+ Convention:
+ - See the Convention block on :func:`~kornia.filters.filter2d`, applied to the ``(D, H, W)`` axes with the
+ anchor ``((kD - 1) // 2, (kH - 1) // 2, (kW - 1) // 2)``.
+ - The default ``border_type`` is ``'replicate'``, where :func:`~kornia.filters.filter2d` defaults to
+ ``'reflect'``. There is no ``padding`` argument: the output always has the input's shape.
+ - Known defect: ``normalized=True`` raises for some non-contiguous kernels, such as a permuted one
+ (`#5159 <https://github.com/kornia/kornia/issues/5159>`_).
+
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'``,
+ The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``.
normalized: If True, kernel will be L1 normalized.
behaviour: defines the convolution mode -- correlation (default), using pytorch conv3d,
@@ -338,18 +380,31 @@ def fft_conv(
(`'valid'`). Boundary handling is performed in the spatial domain prior
to the FFT.
- This function is recommended when the kernel size is larger than
- approximately (20 x 20). For large kernels, FFT-based convolution is
- computationally more efficient than direct spatial convolution,
- reducing complexity from O(H * W * kH * kW) to approximately
- O(H * W log(H * W)). For small kernels, however, direct convolution
- is usually faster due to lower constant overhead.
+ Unlike :func:`~kornia.filters.filter2d`'s, its cost barely grows with the
+ kernel size, so it pays off only for large kernels; the crossover depends
+ on the device and the image size.
+
+ Convention:
+ - See the Convention block on :func:`~kornia.filters.filter2d`: for the same arguments and a finite input
+ ``fft_conv`` returns the same result, to roundoff. A NaN or inf in a channel of the input makes that
+ channel's whole output non-finite, where :func:`~kornia.filters.filter2d` keeps it to the pixels whose
+ window reaches it.
+ - Known defects:
+
+ - one input sample with a batch of kernels is broadcast, one output per kernel, where
+ :func:`~kornia.filters.filter2d` raises (`#5154 <https://github.com/kornia/kornia/issues/5154>`_).
+ - an integer input truncates a fractional kernel to 0, as in :func:`~kornia.filters.filter2d`, and the
+ result is in torch's default floating dtype (float32) instead of the input's
+ (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
+ - with ``padding='valid'`` and a kernel taller or wider than the input, it returns a wrongly sized tensor
+ where :func:`~kornia.filters.filter2d` raises (`#5285 <https://github.com/kornia/kornia/issues/5285>`_).
Args:
input: Input tensor of shape :math:`(B, C, H, W)`.
- kernel: Convolution kernel of shape :math:`(B, kH, kW)`. Each batch
- element provides one kernel, which is shared across all channels
- of the corresponding input batch.
+ kernel: Convolution kernel of shape :math:`(1, kH, kW)`, shared by the
+ whole batch, or :math:`(B, kH, kW)`, where each batch element
+ provides one kernel, which is shared across all channels of the
+ corresponding input batch.
border_type: Padding mode applied to the input before convolution.
Supported values are ``'constant'``, ``'reflect'``,
``'replicate'``, and ``'circular'``.
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 6c3b84ea5..ae4f069b1 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -118,11 +118,18 @@ def gaussian(
) -> torch.Tensor:
r"""Compute the gaussian values based on the window and sigma values.
+ Convention:
+ See the Convention block on :func:`~kornia.filters.get_gaussian_kernel1d`, which validates the size and
+ calls this function; ``gaussian`` does not validate it. In a floating ``dtype``, for an even ``window_size``
+ the Gaussian is centred at ``mean - 0.5``: the default ``mean`` centres the kernel on the middle of the
+ window, halfway between the two middle samples, and an explicit ``mean=m`` centres it at ``m - 0.5``.
+
Args:
window_size: the size which drives the filter amount.
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`.
- mean: Mean of the Gaussian function (center). If not provided, it defaults to
- ``window_size // 2``. If a tensor, should be in a shape :math:`(B, 1)`.
+ mean: Mean of the Gaussian function (center); see the Convention block for an even
+ ``window_size``. If not provided, it defaults to ``window_size // 2``. If a tensor,
+ should be in a shape :math:`(B, 1)`.
device: This value will be used if sigma is a float. Device desired to compute.
dtype: This value will be used if sigma is a float. Dtype desired for compute.
@@ -343,7 +350,22 @@ def gaussian_discrete(
def laplacian_1d(
window_size: int, *, device: Optional[torch.device] = None, dtype: torch.dtype = torch.float32
) -> torch.Tensor:
- """One could also use the Laplacian of Gaussian formula to design the filter."""
+ r"""Return the 1D Laplacian kernel of :func:`~kornia.filters.get_laplacian_kernel1d` without checking the size.
+
+ Convention:
+ See the Convention block on :func:`~kornia.filters.get_laplacian_kernel1d`, which validates the size and
+ calls this function. ``laplacian_1d`` accepts any positive size; an even one puts the negative tap at
+ ``window_size // 2``, off the middle of the kernel.
+
+ Args:
+ window_size: the number of taps.
+ device: tensor device desired to create the kernel
+ dtype: tensor dtype desired to create the kernel
+
+ Returns:
+ 1D tensor with shape :math:`(\text{window_size},)`.
+
+ """
# TODO: add default dtype as None when kornia relies on torch > 1.12
filter_1d = torch.ones(window_size, device=device, dtype=dtype)
middle = window_size // 2
@@ -356,6 +378,15 @@ def get_box_kernel1d(
) -> torch.Tensor:
r"""Return a 1-D box filter.
+ Convention:
+ - For a floating ``dtype`` every tap is ``1 / kernel_size``; an even ``kernel_size`` is accepted.
+ - Known defects:
+
+ - the kernel is a stride-0 view of a single value, so writing one tap in place changes every tap
+ (`#5160 <https://github.com/kornia/kornia/issues/5160>`_).
+ - an integer ``dtype`` truncates ``1 / kernel_size``, so every tap is 0 once ``kernel_size`` is above 1
+ (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
+
Args:
kernel_size: the size of the kernel.
device: the desired device of returned tensor.
@@ -363,7 +394,7 @@ def get_box_kernel1d(
Returns:
A tensor with shape :math:`(1, \text{kernel\_size})`, filled with the value
- :math:`\frac{1}{\text{kernel\_size}}`.
+ :math:`\frac{1}{\text{kernel\_size}}` for a floating ``dtype``.
"""
scale = torch.tensor(1.0 / kernel_size, device=device, dtype=dtype)
@@ -375,14 +406,18 @@ def get_box_kernel2d(
) -> torch.Tensor:
r"""Return a 2-D box filter.
+ Convention:
+ See the Convention block on :func:`~kornia.filters.get_box_kernel1d`; ``kernel_size`` is ``(k_y, k_x)``.
+
Args:
- kernel_size: the size of the kernel.
+ kernel_size: the size of the kernel, an integer or ``(k_y, k_x)``.
device: the desired device of returned tensor.
dtype: the desired data type of returned tensor.
Returns:
A tensor with shape :math:`(1, \text{kernel\_size}[0], \text{kernel\_size}[1])`,
- filled with the value :math:`\frac{1}{\text{kernel\_size}[0] \times \text{kernel\_size}[1]}`.
+ filled with the value :math:`\frac{1}{\text{kernel\_size}[0] \times \text{kernel\_size}[1]}` for a
+ floating ``dtype``.
"""
ky, kx = _unpack_2d_ks(kernel_size)
@@ -393,9 +428,23 @@ def get_box_kernel2d(
def get_binary_kernel2d(
window_size: tuple[int, int] | int, *, device: Optional[torch.device] = None, dtype: torch.dtype = torch.float32
) -> torch.Tensor:
- """Create a binary kernel to extract the patches.
+ r"""Create a binary kernel to extract the patches.
If the window size is HxW will create a (H*W)x1xHxW kernel.
+
+ Convention:
+ Channel ``i`` is one-hot at ``(i // k_x, i % k_x)`` for ``window_size=(k_y, k_x)``, in row-major order, so
+ :func:`torch.nn.functional.conv2d` of an image with the kernel stacks each pixel's neighbourhood in that
+ order, the layout :func:`~kornia.filters.median_blur` builds on.
+
+ Args:
+ window_size: the window size, an integer or ``(k_y, k_x)``.
+ device: tensor device desired to create the kernel
+ dtype: tensor dtype desired to create the kernel
+
+ Returns:
+ the kernel with shape :math:`(k_y k_x, 1, k_y, k_x)`.
+
"""
# TODO: add default dtype as None when kornia relies on torch > 1.12
@@ -523,14 +572,24 @@ def get_diff_kernel3d_2nd_order(
def get_sobel_kernel2d(*, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
- """Return 1st order gradient for sobel operator."""
+ """Return 1st order gradient for sobel operator.
+
+ Convention:
+ See the Convention block on :func:`~kornia.filters.get_spatial_gradient_kernel2d`; this is
+ ``get_spatial_gradient_kernel2d('sobel', 1)``, of shape :math:`(2, 3, 3)`.
+ """
kernel_x = get_sobel_kernel_3x3(device=device, dtype=dtype)
kernel_y = kernel_x.transpose(0, 1)
return torch.stack([kernel_x, kernel_y])
def get_diff_kernel2d(*, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
- """Return 1st order gradient for diff operator."""
+ """Return 1st order gradient for diff operator.
+
+ Convention:
+ See the Convention block on :func:`~kornia.filters.get_spatial_gradient_kernel2d`; this is
+ ``get_spatial_gradient_kernel2d('diff', 1)``, of shape :math:`(2, 3, 3)`.
+ """
kernel_x = get_diff_kernel_3x3(device=device, dtype=dtype)
kernel_y = kernel_x.transpose(0, 1)
return torch.stack([kernel_x, kernel_y])
@@ -566,6 +625,29 @@ def get_spatial_gradient_kernel2d(
r"""Return kernel for 1st or 2nd order image gradients.
Uses one of the following operators: sobel, diff.
+
+ Convention:
+ - ``order=1`` stacks :math:`(\partial_x, \partial_y)` along the first axis and ``order=2`` stacks
+ :math:`(\partial_{xx}, \partial_{xy}, \partial_{yy})`. Correlated with an image, as
+ :func:`~kornia.filters.filter2d` does, an ``order=1`` channel is positive where the values increase with
+ the column (x) or the row (y), and an ``order=2`` channel is positive on :math:`x^2`, :math:`xy` and
+ :math:`y^2` respectively.
+ - The kernels are raw integer stencils, not derivative estimates. Per unit slope Sobel answers 8 and
+ ``'diff'`` answers 2; per unit second derivative Sobel answers 64 on all three channels, while ``'diff'``
+ answers 1 on :math:`\partial_{xx}` and :math:`\partial_{yy}` and 4 on :math:`\partial_{xy}`.
+ - Known defect: ``mode`` is checked case-insensitively but used as given, so ``'Sobel'`` raises
+ (`#5156 <https://github.com/kornia/kornia/issues/5156>`_).
+
+ Args:
+ mode: ``'sobel'`` or ``'diff'``.
+ order: the derivative order, 1 or 2.
+ device: tensor device desired to create the kernel
+ dtype: tensor dtype desired to create the kernel
+
+ Returns:
+ the kernels with shape :math:`(2, 3, 3)` for ``order=1``, and :math:`(3, 5, 5)` (Sobel) or
+ :math:`(3, 3, 3)` (diff) for ``order=2``.
+
"""
KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
@@ -587,9 +669,32 @@ def get_spatial_gradient_kernel2d(
def get_spatial_gradient_kernel3d(
mode: str, order: int, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
- r"""Return kernel for 1st or 2nd order scale pyramid gradients.
+ r"""Return kernel for 1st or 2nd order gradients of a volume.
+
+ Convention:
+ - Only ``mode='diff'`` exists; ``'sobel'`` passes the mode check and raises ``NotImplementedError``.
+ - ``order=1`` stacks :math:`(\partial_x, \partial_y, \partial_z)` and ``order=2`` stacks
+ :math:`(\partial_{xx}, \partial_{yy}, \partial_{zz}, \partial_{xy}, \partial_{yz}, \partial_{xz})`, an
+ order that differs from the 2d :math:`(\partial_{xx}, \partial_{xy}, \partial_{yy})`. The stack has a
+ singleton second axis that :func:`~kornia.filters.get_spatial_gradient_kernel2d` lacks.
+ - In a floating ``dtype`` every channel is in derivative units: it answers 1 to a unit slope or a unit
+ second derivative, unlike the raw 2d stencils.
+ - Known defects:
+
+ - ``mode`` is checked case-insensitively but used as given, so ``'Diff'`` raises
+ (`#5156 <https://github.com/kornia/kornia/issues/5156>`_).
+ - a signed integer ``dtype`` truncates the half and quarter taps to 0, so the first-order channels and
+ the mixed second-order ones are all zero (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
+
+ Args:
+ mode: ``'diff'``.
+ order: the derivative order, 1 or 2.
+ device: tensor device desired to create the kernel
+ dtype: tensor dtype desired to create the kernel
+
+ Returns:
+ the kernels with shape :math:`(3, 1, 3, 3, 3)` for ``order=1`` and :math:`(6, 1, 3, 3, 3)` for ``order=2``.
- Uses one of the following operators: sobel, diff.
"""
KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
@@ -614,6 +719,22 @@ def get_gaussian_kernel1d(
) -> torch.Tensor:
r"""Return Gaussian filter coefficients.
+ Convention:
+ - In a floating ``dtype`` the kernel samples :math:`\exp(-n^2 / 2\sigma^2)` at the offsets :math:`n` of its
+ taps from its centre, integers for an odd size and half-integers for an even one, and is normalized to
+ sum 1; :ref:`Filtering <filtering-conventions>` names the matching scipy and OpenCV kernels.
+ :func:`~kornia.filters.get_gaussian_erf_kernel1d` integrates the Gaussian over each pixel instead, and
+ :func:`~kornia.filters.get_gaussian_discrete_kernel1d` is the discrete Gaussian.
+ - ``force_even=True`` also accepts an even ``kernel_size``, and in a floating ``dtype`` the kernel is then
+ symmetric about the middle of the window, ``(kernel_size - 1) / 2``.
+ - A tensor ``sigma`` of shape :math:`(B, 1)` gives one kernel per row.
+ - Known defects:
+
+ - a Python ``int`` ``sigma`` raises, while the 2d and 3d builders accept integers
+ (`#5157 <https://github.com/kornia/kornia/issues/5157>`_).
+ - an integer ``dtype`` truncates a fractional ``sigma``, and uint8 also wraps the negative offsets, so the
+ taps before the centre are wrong (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
+
Args:
kernel_size: filter size. It should be odd and positive.
sigma: gaussian standard deviation.
@@ -659,6 +780,20 @@ def get_gaussian_discrete_kernel1d(
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
+ Convention:
+ - See the Convention block on :func:`~kornia.filters.get_gaussian_kernel1d`. In a floating ``dtype`` this
+ kernel is Lindeberg's discrete Gaussian :math:`e^{-\sigma^2} I_{|n|}(\sigma^2)`, with :math:`I_n` the
+ modified Bessel function of the first kind, normalized over the window: the smoothing kernel of discrete
+ scale space.
+ - Known defects:
+
+ - the tap count is not always ``kernel_size``: ``kernel_size=1`` gives 3 taps, and an even size with
+ ``force_even=True`` gives one more than asked (`#5158 <https://github.com/kornia/kornia/issues/5158>`_).
+ - the Bessel terms are computed unscaled and overflow, so the kernel is all NaN for a large ``sigma``
+ (from about 7 in float32) and, in float16, for any ``sigma > 0`` once ``kernel_size`` is 5 or more. In
+ float64, before it overflows at a ``sigma`` of about 19, it drifts from the discrete Gaussian from about
+ 9 and is no longer unimodal from about 14 (`#5227 <https://github.com/kornia/kornia/issues/5227>`_).
+
Args:
kernel_size: filter size. It should be odd and positive.
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
@@ -667,7 +802,8 @@ def get_gaussian_discrete_kernel1d(
dtype: This value will be used if sigma is a float. Dtype desired for compute.
Returns:
- 1D tensor with gaussian filter coefficients. With shape :math:`(B, \text{kernel_size})`
+ 1D tensor with gaussian filter coefficients. With shape :math:`(B, \text{kernel_size})` for an odd
+ ``kernel_size`` greater than 1 (see the known defects).
Examples:
>>> get_gaussian_discrete_kernel1d(3, 2.5)
@@ -696,6 +832,14 @@ def get_gaussian_erf_kernel1d(
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
+ Convention:
+ - See the Convention block on :func:`~kornia.filters.get_gaussian_kernel1d`. In a floating ``dtype`` this
+ kernel integrates the Gaussian over each pixel, :math:`\Phi((n + 1/2) / \sigma) - \Phi((n - 1/2) / \sigma)`
+ with :math:`\Phi` the normal CDF, so it blurs more than the sampled kernel: for :math:`\sigma` of
+ about 1 or more, on a window wide enough for the tails, its variance is :math:`\sigma^2 + 1/12`.
+ - Known defect: with ``force_even=True`` an even kernel is centred on tap ``kernel_size // 2`` instead of
+ the middle of the window, so it is not symmetric (`#5158 <https://github.com/kornia/kornia/issues/5158>`_).
+
Args:
kernel_size: filter size. It should be odd and positive.
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
@@ -731,6 +875,12 @@ def get_gaussian_kernel2d(
) -> torch.Tensor:
r"""Return Gaussian filter matrix coefficients.
+ Convention:
+ See the Convention block on :func:`~kornia.filters.get_gaussian_kernel1d`. ``kernel_size`` is
+ ``(k_y, k_x)`` and ``sigma`` is :math:`(\sigma_y, \sigma_x)`, y first as in the output
+ :math:`(B, k_y, k_x)`, which is the outer product of the two 1d kernels. A tensor ``sigma`` of shape
+ :math:`(B, 2)` gives one kernel per row.
+
Args:
kernel_size: filter sizes in the y and x direction. Sizes should be odd and positive.
sigma: gaussian standard deviation in the y and x.
@@ -742,7 +892,7 @@ def get_gaussian_kernel2d(
2D tensor with gaussian filter matrix coefficients.
Shape:
- - Output: :math:`(B, \text{kernel_size}_x, \text{kernel_size}_y)`
+ - Output: :math:`(B, \text{kernel_size}_y, \text{kernel_size}_x)`
Examples:
>>> get_gaussian_kernel2d((5, 5), (1.5, 1.5))
@@ -788,6 +938,12 @@ def get_gaussian_kernel3d(
) -> torch.Tensor:
r"""Return Gaussian filter matrix coefficients.
+ Convention:
+ See the Convention block on :func:`~kornia.filters.get_gaussian_kernel1d`. ``kernel_size`` is
+ ``(k_z, k_y, k_x)`` and ``sigma`` is :math:`(\sigma_z, \sigma_y, \sigma_x)`, z first as in the output
+ :math:`(B, k_z, k_y, k_x)`, which is the outer product of the three 1d kernels. A tensor ``sigma`` of shape
+ :math:`(B, 3)` gives one kernel per row.
+
Args:
kernel_size: filter sizes in the z, y and x direction. Sizes should be odd and positive.
sigma: gaussian standard deviation in the z, y and x direction.
@@ -799,7 +955,7 @@ def get_gaussian_kernel3d(
3D tensor with gaussian filter matrix coefficients.
Shape:
- - Output: :math:`(B, \text{kernel_size}_x, \text{kernel_size}_y, \text{kernel_size}_z)`
+ - Output: :math:`(B, \text{kernel_size}_z, \text{kernel_size}_y, \text{kernel_size}_x)`
Examples:
>>> get_gaussian_kernel3d((3, 3, 3), (1.5, 1.5, 1.5))
@@ -843,6 +999,15 @@ def get_laplacian_kernel1d(
) -> torch.Tensor:
r"""Return the coefficients of a 1D Laplacian filter.
+ Convention:
+ - In a floating ``dtype``, or a signed integer one wide enough to hold ``1 - kernel_size``, the kernel is
+ all ones with the centre tap set to ``1 - kernel_size``, so it sums to 0. Size 3 is the second difference
+ ``[1, -2, 1]``; a larger size is not a wider second difference, and size 5 answers 5 to a unit second
+ derivative.
+ - The negative centre makes the response positive where the values curve upwards.
+ - Known defect: uint8 wraps the negative centre, to 252 for size 5
+ (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
+
Args:
kernel_size: filter size. It should be odd and at least 3.
device: tensor device desired to create the kernel
@@ -855,7 +1020,7 @@ def get_laplacian_kernel1d(
BaseError: if ``kernel_size`` is even, not positive, or ``1``: a single tap is the all-zero kernel.
Shape:
- - Output: math:`(\text{kernel_size})`
+ - Output: :math:`(\text{kernel_size})`
Examples:
>>> get_laplacian_kernel1d(3)
@@ -875,7 +1040,15 @@ def get_laplacian_kernel1d(
def get_laplacian_kernel2d(
kernel_size: tuple[int, int] | int, *, device: Optional[torch.device] = None, dtype: torch.dtype = torch.float32
) -> torch.Tensor:
- r"""Return Gaussian filter matrix coefficients.
+ r"""Return Laplacian filter matrix coefficients.
+
+ Convention:
+ See the Convention block on :func:`~kornia.filters.get_laplacian_kernel1d`: in a floating ``dtype``, or a
+ signed integer one wide enough to hold :math:`1 - k_y k_x`, all ones with the centre set to
+ :math:`1 - k_y k_x` for ``kernel_size=(k_y, k_x)``. Size 3 is the 8-neighbour stencil, which answers 3 to a
+ unit :math:`\partial_{xx}` or :math:`\partial_{yy}`, so it estimates :math:`3 \nabla^2`; size 5 estimates
+ :math:`25 \nabla^2`. :ref:`Filtering <filtering-conventions>` compares it with the scipy, OpenCV and
+ scikit-image Laplacians.
Args:
kernel_size: filter size should be odd, and at least 3 along one axis.
@@ -890,7 +1063,7 @@ def get_laplacian_kernel2d(
it is ``1`` or ``(1, 1)``: a :math:`1 \times 1` kernel is the all-zero kernel.
Shape:
- - Output: :math:`(\text{kernel_size}_x, \text{kernel_size}_y)`
+ - Output: :math:`(\text{kernel_size}_y, \text{kernel_size}_x)`
Examples:
>>> get_laplacian_kernel2d(3)
@@ -1054,21 +1227,23 @@ def get_hysteresis_kernel(device: Optional[torch.device] = None, dtype: Optional
def get_hanning_kernel1d(
kernel_size: int, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
- r"""Return Hanning (also known as Hann) kernel, used in signal processing and KCF tracker.
+ r"""Return Hanning (also known as Hann) kernel.
- .. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
- \\qquad 0 \\leq n \\leq M-1
+ .. math:: w(n) = 0.5 - 0.5 \cos\left(\frac{2\pi n}{M - 1}\right) \qquad 0 \leq n \leq M - 1
- See further in numpy docs https://numpy.org/doc/stable/reference/generated/numpy.hanning.html
+ Convention:
+ This is the symmetric window of size :math:`M`: both end taps are 0, so only :math:`M - 2` samples carry
+ weight, and it is not normalized, its taps summing to :math:`(M - 1) / 2`. An even size is accepted and is
+ symmetric about :math:`(M - 1) / 2`. :ref:`Filtering <filtering-conventions>` names the matching numpy and
+ torch windows.
Args:
- kernel_size: The size the of the kernel. It should be positive.
+ kernel_size: The size of the kernel, an integer greater than 2.
device: tensor device desired to create the kernel
dtype: tensor dtype desired to create the kernel
Returns:
- 1D tensor with Hanning filter coefficients. Shape math:`(\text{kernel_size})`
- .. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
+ 1D tensor with Hanning filter coefficients. Shape :math:`(\text{kernel_size})`.
Examples:
>>> get_hanning_kernel1d(4)
@@ -1086,16 +1261,19 @@ def get_hanning_kernel2d(
device: Optional[Union[str, torch.device]] = None,
dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
- r"""Return 2d Hanning kernel, used in signal processing and KCF tracker.
+ r"""Return 2d Hanning kernel.
+
+ Convention:
+ See the Convention block on :func:`~kornia.filters.get_hanning_kernel1d`. For ``kernel_size=(k_y, k_x)``
+ the kernel is the outer product of the 1d windows of sizes ``k_y`` (along ``H``) and ``k_x`` (along ``W``).
Args:
- kernel_size: The size of the kernel for the filter. It should be positive.
+ kernel_size: The size of the kernel for the filter, an integer or ``(k_y, k_x)``, each greater than 2.
device: tensor device desired to create the kernel
dtype: tensor dtype desired to create the kernel
Returns:
- 2D tensor with Hanning filter coefficients. Shape: math:`(\text{kernel_size[0], kernel_size[1]})`
- .. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
+ 2D tensor with Hanning filter coefficients. Shape :math:`(k_y, k_x)`.
"""
kernel_size = _unpack_2d_ks(kernel_size)
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index d693d0fcd..a537a0f2a 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -32,8 +32,28 @@ def get_motion_kernel2d(
) -> torch.Tensor:
r"""Return 2D motion blur filter.
+ Convention:
+ - ``direction`` is clamped to ``[-1, 1]`` and weighs the line linearly before it is rotated: ``1`` gives
+ ``[0.4, 0.3, 0.2, 0.1, 0]`` along the middle row of a size-5 kernel, heavy at the left end and 0 at the
+ right, so only ``kernel_size - 1`` taps carry weight; ``-1`` mirrors it and ``0`` is uniform.
+ - ``angle`` is in degrees and turns the line counter-clockwise as displayed (row 0 at the top), as
+ :func:`~kornia.geometry.transform.rotate` does: at ``90`` the heavy end moves from the left to the bottom.
+ - Because :func:`~kornia.filters.filter2d` correlates, the streak that the kernel draws from a bright point
+ is heaviest on the side opposite the kernel's heavy end: to the point's right at ``angle=0``,
+ ``direction=1``.
+ - The rotation resamples the line with ``mode``: ``'nearest'`` copies each pixel from the nearest tap, so the
+ number of taps changes with the angle (3 at 45 degrees, 7 at 25 for a size-5 line), and ``'bilinear'``
+ spreads the weight off the line.
+ - A floating tensor ``angle`` of shape :math:`(B,)` gives :math:`(B, k, k)` in its dtype. A tensor
+ ``direction`` must match it in length, dtype and device; a float ``direction`` is not broadcast, so it
+ raises for ``B > 1``.
+ - Known defect: with ``'nearest'``, at angles where the rotated line falls on sampling ties, such as 30 or
+ 60 degrees, roundoff breaks the ties, so the kernel can change with the dtype, the device or a full turn
+ added to the angle; on MPS a tensor angle and the same float angle can blur differently
+ (`#5181 <https://github.com/kornia/kornia/issues/5181>`_).
+
Args:
- kernel_size: motion kernel width and height. It should be odd and positive.
+ kernel_size: motion kernel width and height, an odd integer of at least 3.
angle: angle of the motion blur in degrees (anti-clockwise rotation).
direction: 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),
@@ -112,11 +132,22 @@ def get_motion_kernel3d(
) -> torch.Tensor:
r"""Return 3D motion blur filter.
+ Convention:
+ See the Convention block on :func:`~kornia.filters.get_motion_kernel2d` for ``direction`` and ``mode``.
+ ``angle`` is a Rodrigues axis-angle vector ``(rx, ry, rz)`` in degrees, as applied by
+ :func:`~kornia.geometry.transform.rotate3d`: its direction is the rotation axis and its norm is the
+ rotation angle. :func:`~kornia.geometry.transform.rotate3d` and the 3D motion blurs call the components
+ ``yaw``, ``pitch`` and ``roll``, but they are not composed Euler rotations. The unrotated line lies along x,
+ so with the default ``mode='nearest'`` yaw alone leaves the kernel unchanged (``'bilinear'`` resamples it
+ off the line); a positive pitch alone turns the line's -x end, the heavy end for a positive ``direction``,
+ towards +z, and a positive roll alone turns the line clockwise as displayed, the opposite of the 2d
+ ``angle``.
+
Args:
- kernel_size: motion kernel width, height and depth. It should be odd and positive.
- angle: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
+ kernel_size: motion kernel width, height and depth, an odd integer of at least 3.
+ angle: Rodrigues axis-angle vector ``(rx, ry, rz)`` in degrees, not Euler angles.
If tensor, it must be :math:`(B, 3)`.
- If tuple, it must be (yaw, pitch, raw).
+ If tuple, it must be ``(rx, ry, rz)``.
direction: 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),
while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index 87da2d0b2..cb0f96ba4 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -18,8 +18,10 @@
import pytest
import torch
+import torch.nn.functional as F
from kornia.core._compat import torch_version_le
+from kornia.core.exceptions import BaseError
from kornia.filters import (
convolve2d,
convolve3d,
@@ -29,9 +31,35 @@ from kornia.filters import (
filter2d,
filter2d_separable,
filter3d,
+ gaussian,
+ get_binary_kernel2d,
+ get_box_kernel1d,
+ get_box_kernel2d,
+ get_diff_kernel2d,
+ get_gaussian_discrete_kernel1d,
+ get_gaussian_erf_kernel1d,
+ get_gaussian_kernel1d,
+ get_gaussian_kernel2d,
+ get_gaussian_kernel3d,
+ get_hanning_kernel1d,
+ get_hanning_kernel2d,
+ get_laplacian_kernel1d,
+ get_laplacian_kernel2d,
+ get_motion_kernel2d,
+ get_motion_kernel3d,
+ get_sobel_kernel2d,
+ get_spatial_gradient_kernel2d,
+ get_spatial_gradient_kernel3d,
+ laplacian_1d,
)
-from testing.base import BaseTester
+from testing.base import (
+ BaseTester,
+ _probe_zeros,
+ _supports_kernel_probe,
+ supports_nearest_3d_grid_sample,
+ supports_reflect_padding,
+)
class TestFilter2D(BaseTester):
@@ -1237,3 +1265,896 @@ class TestConvolve3d(BaseTester):
expected = filter3d(inp, kernel, behaviour="conv")
result = convolve3d(inp, kernel)
self.assert_close(result, expected)
+
+
+# ----------------------------------------------------------------------------------------------------------------------
+# Convention and wart pins: the filtering API and the kernel builders.
+
+
+def _replicate_padding_3d_op(device_type: str, dtype: torch.dtype) -> None:
+ F.pad(_probe_zeros(device_type, dtype, 1, 1, 2, 2, 2), (1, 1, 1, 1, 1, 1), mode="replicate")
+
+
+def _nearest_2d_grid_sample_op(device_type: str, dtype: torch.dtype) -> None:
+ grid = _probe_zeros(device_type, dtype, 1, 1, 1, 2)
+ F.grid_sample(_probe_zeros(device_type, dtype, 1, 1, 2, 2), grid, mode="nearest", align_corners=True)
+
+
+def _supports_replicate_padding_3d(device: torch.device, dtype: torch.dtype) -> bool:
+ return _supports_kernel_probe(_replicate_padding_3d_op, device.type, dtype)
+
+
+def _supports_nearest_2d_grid_sample(device: torch.device, dtype: torch.dtype) -> bool:
+ return _supports_kernel_probe(_nearest_2d_grid_sample_op, device.type, dtype)
+
+
+def _rand(*shape: int, device, dtype, seed: int = 0) -> torch.Tensor:
+ """Draw on CPU from a private generator, then move, so the values do not depend on the device."""
+ generator = torch.Generator().manual_seed(seed)
+ return torch.rand(*shape, generator=generator).to(device=device, dtype=dtype)
+
+
+def _delta(shape: tuple[int, ...], index: tuple[int, ...], device, dtype) -> torch.Tensor:
+ out = torch.zeros(shape, device=device, dtype=dtype)
+ out[index] = 1.0
+ return out
+
+
+def _peaks(out: torch.Tensor) -> list[list[int]]:
+ """Positions of the entries above 0.5 in ``out[0, 0]`` (an FFT result carries roundoff elsewhere)."""
+ return (out[0, 0].float().abs() > 0.5).nonzero().tolist()
+
+
+_FILTER2D_FNS = {"filter2d": filter2d, "fft_conv": fft_conv}
+
+
+def _fft_guard(name: str, device: torch.device, dtype: torch.dtype) -> None:
+ """Skip fft_conv where the device has no FFT for the dtype (fft_conv computes a CPU half input in float32)."""
+ if name != "fft_conv" or device.type == "cpu":
+ return
+ try:
+ torch.fft.rfftn(torch.zeros(3, 5, device=device, dtype=dtype))
+ except (RuntimeError, NotImplementedError):
+ pytest.skip("this device has no FFT for this dtype, which fft_conv needs")
+
+
+class TestConventionsFilter2d(BaseTester):
+ @pytest.mark.parametrize("name", ["filter2d", "fft_conv"])
+ def test_convention_filter2d_is_correlation(self, name, device, dtype):
+ _fft_guard(name, device, dtype)
+ fn = _FILTER2D_FNS[name]
+ image = _delta((1, 1, 6, 9), (0, 0, 2, 5), device, dtype)
+ kernel = _delta((1, 3, 3), (0, 0, 2), device, dtype) # one weight on the up-right neighbour
+ # correlation: out[y, x] = image[y - 1, x + 1], so the delta lands one row down and one column left
+ assert _peaks(fn(image, kernel, border_type="constant")) == [[3, 4]]
+ # behaviour='conv' flips the kernel first
+ assert _peaks(fn(image, kernel, border_type="constant", behaviour="conv")) == [[1, 6]]
+ # relabel: transposing the image and the kernel transposes the output
+ transposed = fn(image.transpose(-2, -1), kernel.transpose(-2, -1), border_type="constant")
+ assert _peaks(transposed) == [[4, 3]]
+
+ def test_convention_filter3d_is_correlation(self, device, dtype):
+ volume = _delta((1, 1, 5, 6, 7), (0, 0, 1, 4, 5), device, dtype) # D != H != W
+ kernel = _delta((1, 3, 3, 3), (0, 0, 2, 1), device, dtype)
+ # correlation: out[z, y, x] = volume[z - 1, y + 1, x]
+ assert _peaks(filter3d(volume, kernel, border_type="constant")) == [[2, 3, 5]]
+ assert _peaks(filter3d(volume, kernel, border_type="constant", behaviour="conv")) == [[0, 5, 5]]
+ # relabel: swapping D and W in the volume and the kernel reverses the output coordinates
+ swapped = filter3d(volume.permute(0, 1, 4, 3, 2), kernel.permute(0, 3, 2, 1), border_type="constant")
+ assert _peaks(swapped) == [[5, 3, 2]]
+
+ @pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "fft_conv"])
+ def test_convention_filter2d_reflect_excludes_the_edge_pixel(self, name, device, dtype):
+ _fft_guard(name, device, dtype)
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ ys, xs = torch.meshgrid(torch.arange(5), torch.arange(7), indexing="ij")
+ ramp = (xs + 10 * ys).float()[None, None] # value = x + 10 y on a 5 x 7 image
+ # One weight on the up-left neighbour: out[y, x] = padded[y - 1, x - 1]. torch's reflect mirrors about the edge
+ # pixel without repeating it (scipy 'mirror', OpenCV BORDER_REFLECT_101), so row and column -1 read row and
+ # column 1; scipy's 'reflect' would read row and column 0.
+ rows, cols = [1, 0, 1, 2, 3], [1, 0, 1, 2, 3, 4, 5]
+ expected = ramp[:, :, rows][:, :, :, cols].to(device=device, dtype=dtype)
+ image = ramp.to(device=device, dtype=dtype)
+ if name == "filter2d_separable":
+ tap = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)
+ default, reflect = filter2d_separable(image, tap, tap), filter2d_separable(image, tap, tap, "reflect")
+ else:
+ kernel = _delta((1, 3, 3), (0, 0, 0), device, dtype)
+ fn = _FILTER2D_FNS[name]
+ default, reflect = fn(image, kernel), fn(image, kernel, border_type="reflect")
+ self.assert_close(default, expected)
+ self.assert_close(reflect, expected)
+
+ def test_convention_filter3d_default_border_is_replicate(self, device, dtype):
+ if not _supports_replicate_padding_3d(device, dtype):
+ pytest.skip("replication_pad3d is unavailable for this device/dtype")
+ zs, ys, xs = torch.meshgrid(torch.arange(3), torch.arange(4), torch.arange(5), indexing="ij")
+ ramp = (xs + 10 * ys + 100 * zs).float()[None, None] # at most 234, exact in bfloat16
+ # One weight at the kernel's corner: out[z, y, x] = padded[z - 1, y - 1, x - 1]. filter3d defaults to
+ # 'replicate' (filter2d to 'reflect'), so index -1 reads the edge sample 0 on every axis.
+ expected = ramp[:, :, [0, 0, 1]][:, :, :, [0, 0, 1, 2]][:, :, :, :, [0, 0, 1, 2, 3]]
+ volume = ramp.to(device=device, dtype=dtype)
+ kernel = _delta((1, 3, 3, 3), (0, 0, 0, 0), device, dtype)
+ self.assert_close(filter3d(volume, kernel), expected.to(device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "fft_conv"])
+ def test_convention_filter2d_even_kernel_centre(self, name, device, dtype):
+ _fft_guard(name, device, dtype)
+
+ # A single weight at the kernel's first tap. The anchor of a (kH, kW) kernel is ((kH - 1) // 2, (kW - 1) // 2),
+ # the anchor of torch's F.conv2d(padding='same'): a (4, 2) kernel moves the delta by (+1, 0). An anchor at
+ # k // 2 (the OpenCV and scipy default, and kornia.morphology's) would move it by (+2, +1).
+ def run(image, kh, kw):
+ if name == "filter2d_separable":
+ kernel_x = _delta((1, kw), (0, 0), device, dtype)
+ kernel_y = _delta((1, kh), (0, 0), device, dtype)
+ return filter2d_separable(image, kernel_x, kernel_y, border_type="constant")
+ return _FILTER2D_FNS[name](image, _delta((1, kh, kw), (0, 0, 0), device, dtype), border_type="constant")
+
+ image = _delta((1, 1, 6, 9), (0, 0, 2, 5), device, dtype)
+ assert _peaks(run(image, 4, 2)) == [[3, 5]]
+ # relabel: the transposed image with the transposed (2, 4) kernel gives the transposed position
+ assert _peaks(run(image.transpose(-2, -1), 2, 4)) == [[5, 3]]
+ if name == "filter2d_separable":
+ return # no behaviour argument
+ # behaviour='conv' flips the kernel, putting the weight at its last tap (3, 1), and keeps the anchor (1, 0):
+ # the delta moves by (-2, -1). An anchor at k // 2 would move it by (-1, 0).
+ fn = _FILTER2D_FNS[name]
+ conv = fn(image, _delta((1, 4, 2), (0, 0, 0), device, dtype), border_type="constant", behaviour="conv")
+ assert _peaks(conv) == [[0, 4]]
+ kernel_t = _delta((1, 2, 4), (0, 0, 0), device, dtype)
+ conv_t = fn(image.transpose(-2, -1), kernel_t, border_type="constant", behaviour="conv")
+ assert _peaks(conv_t) == [[4, 0]]
+
+ @pytest.mark.parametrize("name", ["filter2d", "fft_conv"])
+ def test_convention_filter2d_conv_equals_scipy_convolve_for_an_even_kernel(self, name, device, dtype):
+ _fft_guard(name, device, dtype)
+ # scipy 1.17.1, numpy 2.0.0:
+ # image = np.random.default_rng(0).integers(0, 3, (5, 7)).astype(float)
+ # ndi.convolve(image, [[1, 2, 3, 4], [5, 6, 7, 8]], mode="constant", cval=0.0) # default origin
+ image = [[2, 1, 1, 0, 0, 0, 0], [0, 0, 2, 1, 2, 1, 1], [2, 2, 1, 1, 1, 2, 0], [2, 2, 0, 1, 2, 1, 0]]
+ image += [[2, 2, 2, 0, 0, 2, 0]]
+ expected = [[27, 34, 25, 24, 13, 13, 7], [21, 34, 44, 51, 44, 39, 23], [41, 56, 46, 39, 39, 33, 20]]
+ expected += [[38, 53, 46, 34, 32, 29, 16], [36, 42, 30, 26, 12, 14, 16]]
+ image_t = torch.tensor(image, device=device, dtype=dtype)[None, None]
+ expected_t = torch.tensor(expected, device=device, dtype=dtype)[None, None]
+ kernel = torch.tensor([[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]]], device=device, dtype=dtype)
+ fn = _FILTER2D_FNS[name]
+ self.assert_close(fn(image_t, kernel, "constant", behaviour="conv"), expected_t)
+ # relabel: transposing the image and the kernel transposes the output
+ conv_t = fn(image_t.transpose(-2, -1), kernel.transpose(-2, -1), "constant", behaviour="conv")
+ self.assert_close(conv_t, expected_t.transpose(-2, -1))
+
+ def test_convention_filter3d_even_kernel_centre(self, device, dtype):
+ volume = _delta((1, 1, 5, 6, 7), (0, 0, 1, 4, 3), device, dtype)
+ kernel = _delta((1, 4, 2, 6), (0, 0, 0, 0), device, dtype)
+ # anchor ((4 - 1) // 2, (2 - 1) // 2, (6 - 1) // 2) = (1, 0, 2) on (D, H, W)
+ assert _peaks(filter3d(volume, kernel, border_type="constant")) == [[2, 4, 5]]
+ swapped = filter3d(volume.permute(0, 1, 4, 3, 2), kernel.permute(0, 3, 2, 1), border_type="constant")
+ assert _peaks(swapped) == [[5, 4, 2]]
+
+ @pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "fft_conv"])
+ def test_convention_filter2d_valid_output_is_the_same_output_cropped(self, name, device, dtype):
+ _fft_guard(name, device, dtype)
+ image = _rand(2, 1, 6, 9, device=device, dtype=dtype)
+ kernel_y = _rand(1, 4, device=device, dtype=dtype, seed=1)
+ kernel_x = _rand(1, 5, device=device, dtype=dtype, seed=2)
+ outs = {}
+ for padding in ("same", "valid"):
+ if name == "filter2d_separable":
+ outs[padding] = filter2d_separable(image, kernel_x, kernel_y, "constant", padding=padding)
+ else:
+ kernel = kernel_y[:, :, None] * kernel_x[:, None, :]
+ outs[padding] = _FILTER2D_FNS[name](image, kernel, "constant", padding=padding)
+ # 'valid' returns (H - kH + 1, W - kW + 1), the 'same' output from the anchor ((4 - 1) // 2, (5 - 1) // 2) on
+ assert outs["valid"].shape == (2, 1, 3, 5)
+ self.assert_close(outs["valid"], outs["same"][..., 1:4, 2:7])
+
+ def test_convention_filter2d_separable_equals_filter2d_with_the_outer_product(self, device, dtype):
+ image = _rand(2, 3, 6, 9, device=device, dtype=dtype)
+ kernel_x = _rand(2, 4, device=device, dtype=dtype, seed=1) # per-sample, even, along W
+ kernel_y = _rand(2, 3, device=device, dtype=dtype, seed=2) # per-sample, along H
+ out = filter2d_separable(image, kernel_x, kernel_y, border_type="constant")
+ outer = kernel_y[:, :, None] * kernel_x[:, None, :] # (B, kH, kW)
+ # the separable path rounds its intermediate row pass, a few ulp apart from one pass in half precision
+ half = dtype in (torch.float16, torch.bfloat16)
+ self.assert_close(out, filter2d(image, outer, border_type="constant"), low_tolerance=half)
+
+ def test_convention_filter2d_kernel_batch_is_per_sample_not_per_channel(self, device, dtype):
+ # B = C = 3, so a per-sample and a per-channel reading of three kernels would differ
+ image = _rand(3, 3, 5, 7, device=device, dtype=dtype)
+ kernels = _rand(3, 3, 3, device=device, dtype=dtype, seed=1)
+ out = filter2d(image, kernels, border_type="constant")
+ shared = filter2d(image, kernels[:1], border_type="constant")
+ for i in range(3):
+ for c in range(3):
+ plane = image[i : i + 1, c : c + 1]
+ self.assert_close(out[i : i + 1, c : c + 1], filter2d(plane, kernels[i : i + 1], "constant"))
+ self.assert_close(shared[i : i + 1, c : c + 1], filter2d(plane, kernels[:1], "constant"))
+ # one sample with C kernels is not read as one kernel per channel
+ with pytest.raises((RuntimeError, BaseError)):
+ filter2d(image[:1], kernels, border_type="constant")
+
+ @pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "fft_conv", "filter3d"])
+ def test_convention_filter2d_normalized_divides_by_the_absolute_sum(self, name, device, dtype):
+ _fft_guard(name, device, dtype)
+ taps = torch.tensor([[1.0, 2.0, -4.0]], device=device, dtype=dtype) # sum -1, absolute sum 7
+ if name == "filter2d_separable":
+ image = _rand(1, 2, 5, 7, device=device, dtype=dtype)
+ taps_y = torch.tensor([[3.0, -1.0]], device=device, dtype=dtype) # sum 2, absolute sum 4
+
+ def call(*kernels, **kwargs):
+ return filter2d_separable(image, *kernels, "constant", **kwargs)
+
+ kernels, divided = (taps, taps_y), (taps / 7, taps_y / 4)
+ else:
+ fn = filter3d if name == "filter3d" else _FILTER2D_FNS[name]
+ image = _rand(1, 2, *((3,) if name == "filter3d" else ()), 5, 7, device=device, dtype=dtype)
+ # two rows (two depth slices in 3-D) with absolute sums 7 and 4: the whole kernel's is 11
+ rows = torch.tensor([[1.0, 2.0, -4.0], [3.0, 0.0, 1.0]], device=device, dtype=dtype)
+ kernel = rows[None, :, None] if name == "filter3d" else rows[None]
+
+ def call(*kernels, **kwargs):
+ return fn(image, *kernels, "constant", **kwargs)
+
+ kernels, divided = (kernel,), (kernel / 11,)
+ self.assert_close(call(*kernels, normalized=True), call(*divided))
+ # the default is normalized=False
+ self.assert_close(call(*kernels), call(*kernels, normalized=False))
+
+ @pytest.mark.parametrize("name", ["filter2d", "fft_conv", "filter3d"])
+ def test_convention_filter2d_casts_the_kernel_to_the_input_dtype_and_device(self, name, device, dtype):
+ _fft_guard(name, device, dtype)
+ fn = filter3d if name == "filter3d" else _FILTER2D_FNS[name]
+ spatial = (3, 5, 7) if name == "filter3d" else (5, 7)
+ image = _rand(1, 2, *spatial, device=device, dtype=dtype)
+ kernel = torch.rand(1, *((3,) * len(spatial)), dtype=torch.float64, generator=torch.Generator().manual_seed(1))
+ kernel.requires_grad_(True) # a float64 CPU leaf
+ out = fn(image, kernel, "constant")
+ assert out.dtype == dtype
+ assert out.device == image.device
+ self.assert_close(out, fn(image, kernel.detach().to(device=device, dtype=dtype), "constant"))
+ # the cast keeps the kernel on the autograd graph
+ out.float().sum().backward()
+ assert kernel.grad is not None
+ assert kernel.grad.dtype == torch.float64
+
+ @pytest.mark.parametrize("border_type, too_narrow, wide_enough", [("reflect", 2, 3), ("circular", 1, 2)])
+ def test_convention_filter2d_reflect_and_circular_need_the_axis_longer_than_the_pad(
+ self, border_type, too_narrow, wide_enough, device, dtype
+ ):
+ if border_type == "reflect" and not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ # A kernel 4 wide pads 1 column before and 2 after. reflect needs every pad shorter than the axis, circular
+ # at most as long; a narrower axis raises.
+ kernel = _rand(1, 1, 4, device=device, dtype=dtype)
+ out = filter2d(_rand(1, 1, 3, wide_enough, device=device, dtype=dtype), kernel, border_type)
+ assert out.shape == (1, 1, 3, wide_enough)
+ with pytest.raises((RuntimeError, BaseError)):
+ filter2d(_rand(1, 1, 3, too_narrow, device=device, dtype=dtype), kernel, border_type)
+ # constant padding runs on any size
+ assert filter2d(_rand(1, 1, 3, 1, device=device, dtype=dtype), kernel, "constant").shape == (1, 1, 3, 1)
+
+ @pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "filter3d"])
+ def test_wart_kernel_batch_dividing_the_input_batch_is_applied_cyclically_5154(self, name, device, dtype):
+ """Two kernels for four samples are not rejected: sample i is filtered with kernel i % 2 (#5154)."""
+ if name == "filter2d_separable":
+ image = _rand(4, 1, 5, 7, device=device, dtype=dtype)
+ kernel_x = _rand(2, 3, device=device, dtype=dtype, seed=1)
+ kernel_y = _rand(2, 3, device=device, dtype=dtype, seed=2)
+
+ def run(x, lo, hi):
+ return filter2d_separable(x, kernel_x[lo:hi], kernel_y[lo:hi], "constant")
+
+ else:
+ fn = filter3d if name == "filter3d" else filter2d
+ image = _rand(4, 1, *((3,) if name == "filter3d" else ()), 5, 7, device=device, dtype=dtype)
+ kernels = _rand(2, *((3,) if name == "filter3d" else ()), 3, 3, device=device, dtype=dtype, seed=1)
+
+ def run(x, lo, hi):
+ return fn(x, kernels[lo:hi], "constant")
+
+ out = run(image, 0, 2)
+ assert out.shape == image.shape
+ for i in range(4):
+ self.assert_close(out[i : i + 1], run(image[i : i + 1], i % 2, i % 2 + 1))
+
+ def test_wart_fft_conv_broadcasts_one_sample_over_the_kernel_batch_5154(self, device, dtype):
+ """fft_conv returns a batch of 4 for one sample and 4 kernels, where filter2d raises (#5154)."""
+ _fft_guard("fft_conv", device, dtype)
+ image = _rand(1, 1, 5, 7, device=device, dtype=dtype)
+ kernels = _rand(4, 3, 3, device=device, dtype=dtype, seed=1)
+ out = fft_conv(image, kernels, border_type="constant")
+ assert out.shape == (4, 1, 5, 7)
+ for j in range(4):
+ self.assert_close(out[j : j + 1], fft_conv(image, kernels[j : j + 1], border_type="constant"))
+
+ @pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "filter3d", "fft_conv"])
+ def test_wart_integer_input_truncates_a_fractional_kernel_to_zero_5155(self, name, device, dtype):
+ """An integer input casts the kernel to its dtype: a 1/9 box kernel turns a constant 100 image to 0 (#5155)."""
+ if name != "fft_conv" and device.type != "cpu":
+ pytest.skip("integer convolution raises on this device, so there is no truncated result to pin (#5155)")
+ spatial = (3, 5, 7) if name == "filter3d" else (5, 7)
+ image = torch.full((1, 1, *spatial), 100, dtype=torch.uint8, device=device)
+ if name == "filter2d_separable":
+ third = torch.full((1, 3), 1 / 3, device=device, dtype=dtype)
+ out = filter2d_separable(image, third, third, "constant")
+ elif name == "filter3d":
+ out = filter3d(image, torch.full((1, 3, 3, 3), 1 / 27, device=device, dtype=dtype), "constant")
+ else:
+ out = _FILTER2D_FNS[name](image, torch.full((1, 3, 3), 1 / 9, device=device, dtype=dtype), "constant")
+ # the interior of a box-filtered constant image is 100 in floating point
+ assert out[..., 2, 3].flatten()[0].item() == 0
+
+ @pytest.mark.parametrize("name", ["filter2d", "fft_conv"])
+ def test_wart_uppercase_padding_returns_the_valid_size_5156(self, name, device, dtype):
+ """padding='SAME' passes the case-insensitive check but misses the 'same' branch: valid size (#5156)."""
+ _fft_guard(name, device, dtype)
+ image = _rand(1, 1, 5, 7, device=device, dtype=dtype)
+ kernel = _rand(1, 3, 3, device=device, dtype=dtype, seed=1)
+ assert _FILTER2D_FNS[name](image, kernel, "constant", padding="SAME").shape == (1, 1, 3, 5)
+
+ @pytest.mark.parametrize(
+ "case",
+ ["filter2d_border_type", "fft_conv_border_type", "filter3d_border_type", "kernel2d_mode", "kernel3d_mode"],
+ )
+ def test_wart_uppercase_border_type_or_mode_passes_validation_then_raises_5156(self, case, device, dtype):
+ """'REFLECT', 'Replicate', 'Sobel' and 'Diff' pass the case-insensitive check, then fail to dispatch (#5156)."""
+ image = _rand(1, 1, 5, 7, device=device, dtype=dtype)
+ kernel = _rand(1, 3, 3, device=device, dtype=dtype, seed=1)
+ calls = {
+ "filter2d_border_type": lambda: filter2d(image, kernel, border_type="REFLECT"),
+ "fft_conv_border_type": lambda: fft_conv(image, kernel, border_type="REFLECT"),
+ "filter3d_border_type": lambda: filter3d(image[:, :, None], kernel[:, None], border_type="Replicate"),
+ "kernel2d_mode": lambda: get_spatial_gradient_kernel2d("Sobel", 1, device=device, dtype=dtype),
+ "kernel3d_mode": lambda: get_spatial_gradient_kernel3d("Diff", 1, device=device, dtype=dtype),
+ }
+ # the error comes from past the check (torch's F.pad or the kernel dispatch), not from kornia's validation
+ with pytest.raises(Exception) as error:
+ calls[case]()
+ assert not isinstance(error.value, BaseError)
+
+ def test_wart_filter3d_normalized_rejects_a_non_contiguous_kernel_5159(self, device, dtype):
+ """filter3d(normalized=True) calls .view on the kernel, which fails for a permuted kernel (#5159)."""
+ volume = _rand(1, 1, 5, 6, 7, device=device, dtype=dtype)
+ kernel = _rand(1, 3, 4, 5, device=device, dtype=dtype, seed=1).permute(0, 3, 2, 1) # (1, 5, 4, 3)
+ assert not kernel.is_contiguous()
+ out = filter3d(volume, kernel.contiguous(), "constant", normalized=True)
+ assert out.shape == volume.shape
+ with pytest.raises(RuntimeError):
+ filter3d(volume, kernel, "constant", normalized=True)
+
+ def test_wart_fft_conv_valid_padding_with_a_kernel_larger_than_the_input_5285(self, device, dtype):
+ """With padding='valid', a 7 x 3 kernel on a 5 x 6 image gives fft_conv a 4 x 4 output (#5285)."""
+ _fft_guard("fft_conv", device, dtype)
+ image = _rand(1, 1, 5, 6, device=device, dtype=dtype)
+ kernel = _rand(1, 7, 3, device=device, dtype=dtype, seed=1)
+ with pytest.raises((RuntimeError, BaseError)):
+ filter2d(image, kernel, "constant", padding="valid")
+ assert fft_conv(image, kernel, "constant", padding="valid").shape == (1, 1, 4, 4)
+
+
+# (name, factory(device, dtype), shape) for non-square sizes, so every axis order is visible
+_KERNEL_SHAPES = [
+ ("get_box_kernel1d", lambda d, t: get_box_kernel1d(4, device=d, dtype=t), (1, 4)),
+ ("get_box_kernel2d", lambda d, t: get_box_kernel2d((3, 4), device=d, dtype=t), (1, 3, 4)),
+ ("gaussian", lambda d, t: gaussian(5, 1.0, device=d, dtype=t), (1, 5)),
+ ("get_gaussian_kernel1d", lambda d, t: get_gaussian_kernel1d(5, 1.0, device=d, dtype=t), (1, 5)),
+ ("get_gaussian_erf_kernel1d", lambda d, t: get_gaussian_erf_kernel1d(5, 1.0, device=d, dtype=t), (1, 5)),
+ ("get_gaussian_discrete_kernel1d", lambda d, t: get_gaussian_discrete_kernel1d(5, 1.0, device=d, dtype=t), (1, 5)),
+ ("get_gaussian_kernel2d", lambda d, t: get_gaussian_kernel2d((3, 5), (1.0, 1.0), device=d, dtype=t), (1, 3, 5)),
+ (
+ "get_gaussian_kernel3d",
+ lambda d, t: get_gaussian_kernel3d((3, 5, 7), (1.0, 1.0, 1.0), device=d, dtype=t),
+ (1, 3, 5, 7),
+ ),
+ ("get_laplacian_kernel1d", lambda d, t: get_laplacian_kernel1d(5, device=d, dtype=t), (5,)),
+ ("get_laplacian_kernel2d", lambda d, t: get_laplacian_kernel2d((3, 5), device=d, dtype=t), (3, 5)),
+ ("get_hanning_kernel1d", lambda d, t: get_hanning_kernel1d(5, device=d, dtype=t), (5,)),
+ ("get_hanning_kernel2d", lambda d, t: get_hanning_kernel2d((3, 5), device=d, dtype=t), (3, 5)),
+ ("get_binary_kernel2d", lambda d, t: get_binary_kernel2d((3, 5), device=d, dtype=t), (15, 1, 3, 5)),
+ ("get_sobel_kernel2d", lambda d, t: get_sobel_kernel2d(device=d, dtype=t), (2, 3, 3)),
+ ("get_diff_kernel2d", lambda d, t: get_diff_kernel2d(device=d, dtype=t), (2, 3, 3)),
+ ("sobel_order2", lambda d, t: get_spatial_gradient_kernel2d("sobel", 2, device=d, dtype=t), (3, 5, 5)),
+ ("diff_order2", lambda d, t: get_spatial_gradient_kernel2d("diff", 2, device=d, dtype=t), (3, 3, 3)),
+ ("diff3d_order1", lambda d, t: get_spatial_gradient_kernel3d("diff", 1, device=d, dtype=t), (3, 1, 3, 3, 3)),
+ ("diff3d_order2", lambda d, t: get_spatial_gradient_kernel3d("diff", 2, device=d, dtype=t), (6, 1, 3, 3, 3)),
+ (
+ "get_motion_kernel2d",
+ lambda d, t: get_motion_kernel2d(5, torch.tensor(30.0, device=d, dtype=t)),
+ (1, 5, 5),
+ ),
+ (
+ "get_motion_kernel3d",
+ lambda d, t: get_motion_kernel3d(5, torch.tensor([[0.0, 30.0, 0.0]], device=d, dtype=t)),
+ (1, 5, 5, 5),
+ ),
+]
+
+# (name, builder(size, device, dtype), rejected sizes, accepted sizes, the rule kornia states in its message)
+_KERNEL_SIZE_RULES = [
+ (
+ "get_gaussian_kernel1d",
+ lambda k, d, t: get_gaussian_kernel1d(k, 1.0, device=d, dtype=t),
+ [0, 2, 4],
+ [1, 3],
+ "an odd integer bigger than 0",
+ ),
+ (
+ "get_gaussian_kernel1d_force_even",
+ lambda k, d, t: get_gaussian_kernel1d(k, 1.0, True, device=d, dtype=t),
+ [0],
+ [1, 2, 4],
+ "an even or odd integer bigger than 0",
+ ),
+ (
+ "get_gaussian_erf_kernel1d",
+ lambda k, d, t: get_gaussian_erf_kernel1d(k, 1.0, device=d, dtype=t),
+ [0, 4],
+ [3],
+ "an odd integer bigger than 0",
+ ),
+ (
+ "get_gaussian_discrete_kernel1d",
+ lambda k, d, t: get_gaussian_discrete_kernel1d(k, 1.0, device=d, dtype=t),
+ [0, 4],
+ [3],
+ "an odd integer bigger than 0",
+ ),
+ (
+ "get_gaussian_kernel2d",
+ lambda k, d, t: get_gaussian_kernel2d((3, k), (1.0, 1.0), device=d, dtype=t),
+ [0, 4],
+ [1, 3],
+ "an odd integer bigger than 0",
+ ),
+ (
+ "get_gaussian_kernel3d",
+ lambda k, d, t: get_gaussian_kernel3d((3, 5, k), (1.0, 1.0, 1.0), device=d, dtype=t),
+ [0, 4],
+ [1, 3],
+ "an odd integer bigger than 0",
+ ),
+ (
+ "get_laplacian_kernel1d",
+ lambda k, d, t: get_laplacian_kernel1d(k, device=d, dtype=t),
+ [0, 4],
+ [3], # 1 is rejected too, as the all-zero kernel, with its own message (#5175)
+ "an odd integer bigger than 0",
+ ),
+ (
+ "get_laplacian_kernel2d",
+ lambda k, d, t: get_laplacian_kernel2d((3, k), device=d, dtype=t),
+ [0, 4],
+ [1, 3],
+ "an odd integer bigger than 0",
+ ),
+ (
+ "get_hanning_kernel1d",
+ lambda k, d, t: get_hanning_kernel1d(k, device=d, dtype=t),
+ [1, 2],
+ [3, 4],
+ "an even or odd integer bigger than 2",
+ ),
+ (
+ "get_hanning_kernel2d",
+ lambda k, d, t: get_hanning_kernel2d((3, k), device=d, dtype=t),
+ [1, 2],
+ [3, 4],
+ "an even or odd integer bigger than 2",
+ ),
+ # the motion builders take their device and dtype from a tensor angle; a float angle builds on the CPU
+ (
+ "get_motion_kernel2d",
+ lambda k, d, t: get_motion_kernel2d(k, 0.0),
+ [1, 4],
+ [3, 5],
+ "an odd integer bigger than 2",
+ ),
+ (
+ "get_motion_kernel3d",
+ lambda k, d, t: get_motion_kernel3d(k, (0.0, 0.0, 0.0)),
+ [1, 4],
+ [3, 5],
+ "an odd integer bigger than 2",
+ ),
+]
+
+_UNIT_SUM_KERNELS = [
+ ("gaussian", lambda d, t: gaussian(5, 1.5, device=d, dtype=t)),
+ ("get_gaussian_kernel1d", lambda d, t: get_gaussian_kernel1d(7, 1.5, device=d, dtype=t)),
+ ("get_gaussian_erf_kernel1d", lambda d, t: get_gaussian_erf_kernel1d(7, 1.5, device=d, dtype=t)),
+ ("get_gaussian_discrete_kernel1d", lambda d, t: get_gaussian_discrete_kernel1d(7, 1.5, device=d, dtype=t)),
+ ("get_gaussian_kernel2d", lambda d, t: get_gaussian_kernel2d((3, 5), (1.0, 1.5), device=d, dtype=t)),
+ ("get_gaussian_kernel3d", lambda d, t: get_gaussian_kernel3d((3, 5, 7), (0.7, 1.0, 1.5), device=d, dtype=t)),
+ ("get_box_kernel1d", lambda d, t: get_box_kernel1d(4, device=d, dtype=t)),
+ ("get_box_kernel2d", lambda d, t: get_box_kernel2d((3, 4), device=d, dtype=t)),
+ (
+ "get_motion_kernel2d",
+ lambda d, t: get_motion_kernel2d(
+ 5, torch.tensor(30.0, device=d, dtype=t), torch.tensor(0.5, device=d, dtype=t)
+ ),
+ ),
+ (
+ "get_motion_kernel3d",
+ lambda d, t: get_motion_kernel3d(
+ 5, torch.tensor([[10.0, 30.0, 20.0]], device=d, dtype=t), torch.tensor([0.5], device=d, dtype=t)
+ ),
+ ),
+]
+
+
+def _kernel_guard(name: str, device: torch.device, dtype: torch.dtype, values: bool = True) -> None:
+ """Skip a builder whose kernel cannot be built, or whose ``values`` are not usable, on this device/dtype."""
+ if values and name == "get_gaussian_discrete_kernel1d" and dtype == torch.float16:
+ pytest.skip("get_gaussian_discrete_kernel1d overflows to NaN in float16 (#5227)")
+ if name == "get_motion_kernel2d" and not _supports_nearest_2d_grid_sample(device, dtype):
+ pytest.skip("2D grid_sample (nearest) is unavailable for this device/dtype")
+ if name == "get_motion_kernel3d" and not supports_nearest_3d_grid_sample(device, dtype):
+ pytest.skip("3D grid_sample (nearest) is unavailable for this device/dtype")
+
+
+def _grid(*sizes: int, centre: tuple[int, ...], device, dtype) -> tuple[torch.Tensor, ...]:
+ """Integer coordinate grids (ij order) shifted so that ``centre`` is the origin."""
+ axes = [torch.arange(n) - c for n, c in zip(sizes, centre)]
+ return tuple(g.to(device=device, dtype=dtype) for g in torch.meshgrid(*axes, indexing="ij"))
+
+
+def _correlate_at(kernel: torch.Tensor, field: torch.Tensor, centre: tuple[int, ...]) -> torch.Tensor:
+ """Correlate a stack of kernels ``(N, *k)`` with ``field`` at one point, as filter2d / filter3d do."""
+ window = tuple(slice(c - k // 2, c + k // 2 + 1) for c, k in zip(centre, kernel.shape[1:]))
+ dims = tuple(range(-len(centre), 0))
+ return (kernel * field[window]).sum(dims)
+
+
+class TestConventionsKernels(BaseTester):
+ @pytest.mark.parametrize("name, factory, shape", _KERNEL_SHAPES, ids=[case[0] for case in _KERNEL_SHAPES])
+ def test_convention_kernel_builder_output_shapes(self, name, factory, shape, device, dtype):
+ _kernel_guard(name, device, dtype, values=False)
+ kernel = factory(device, dtype)
+ assert kernel.shape == shape
+ assert kernel.dtype == dtype
+ assert kernel.device.type == device.type
+
+ @pytest.mark.parametrize(
+ "name, build, rejected, accepted, rule", _KERNEL_SIZE_RULES, ids=[case[0] for case in _KERNEL_SIZE_RULES]
+ )
+ def test_convention_kernel_builder_size_rules(self, name, build, rejected, accepted, rule, device, dtype):
+ for size in rejected:
+ with pytest.raises(BaseError, match=f"Kernel size must be {rule}\\."):
+ build(size, device, dtype)
+ for size in accepted:
+ build(size, device, dtype)
+
+ @pytest.mark.parametrize("name, factory", _UNIT_SUM_KERNELS, ids=[case[0] for case in _UNIT_SUM_KERNELS])
+ def test_convention_smoothing_kernels_sum_to_one(self, name, factory, device, dtype):
+ _kernel_guard(name, device, dtype)
+ kernel = factory(device, dtype)
+ sums = kernel.flatten(1).sum(-1)
+ self.assert_close(sums, torch.ones_like(sums))
+
+ @pytest.mark.parametrize(
+ "name, expected",
+ [
+ ("get_gaussian_kernel1d", [0.00962006, 0.2054237, 0.56991249, 0.2054237, 0.00962006]),
+ ("get_gaussian_erf_kernel1d", [0.01589041, 0.22154163, 0.52513592, 0.22154163, 0.01589041]),
+ ("get_gaussian_discrete_kernel1d", [0.01881815, 0.15514675, 0.6520702, 0.15514675, 0.01881815]),
+ ],
+ )
+ def test_convention_gaussian_kernel1d_variants_sampled_erf_discrete(self, name, expected, device, dtype):
+ # kernel_size 5, sigma 0.7, normalised to sum 1 (numpy, scipy 1.17.1, opencv 5.0.0; n = arange(-2, 3)):
+ # sampled: cv2.getGaussianKernel(5, 0.7), i.e. exp(-n**2 / (2 * 0.7**2))
+ # erf: the pixel-integrated Gaussian, scipy.special.ndtr((n + 0.5) / 0.7) - ndtr((n - 0.5) / 0.7)
+ # discrete: Lindeberg's discrete Gaussian, scipy.special.ive(abs(n), 0.7**2)
+ _kernel_guard(name, device, dtype)
+ builders = {
+ "get_gaussian_kernel1d": get_gaussian_kernel1d,
+ "get_gaussian_erf_kernel1d": get_gaussian_erf_kernel1d,
+ "get_gaussian_discrete_kernel1d": get_gaussian_discrete_kernel1d,
+ }
+ kernel = builders[name](5, 0.7, device=device, dtype=dtype)
+ self.assert_close(kernel, torch.tensor([expected], device=device, dtype=dtype))
+
+ def test_convention_gaussian_even_window_centres_at_mean_minus_half(self, device, dtype):
+ # The default mean window_size // 2 = 2 puts the centre of a 4-sample window at 1.5: symmetric
+ default = gaussian(4, 1.0, device=device, dtype=dtype)
+ self.assert_close(default, default.flip(-1))
+ self.assert_close(get_gaussian_kernel1d(4, 1.0, force_even=True, device=device, dtype=dtype), default)
+ # an explicit mean=1 on an even window centres at 0.5, so samples 0 and 1 weigh the same
+ shifted = gaussian(4, 1.0, mean=1.0, device=device, dtype=dtype)
+ self.assert_close(shifted[:, 0], shifted[:, 1])
+ assert shifted[0, 1] > shifted[0, 2]
+ # an odd window centres at the mean itself
+ odd = gaussian(5, 1.0, mean=1.0, device=device, dtype=dtype)
+ assert int(odd[0].float().argmax()) == 1
+ self.assert_close(odd[:, 0], odd[:, 2])
+
+ def test_convention_gaussian_kernel2d_sizes_and_sigmas_are_y_then_x(self, device, dtype):
+ kernel = get_gaussian_kernel2d((7, 9), (1.0, 2.0), device=device, dtype=dtype)
+ assert kernel.shape == (1, 7, 9)
+ along_y = get_gaussian_kernel1d(7, 1.0, device=device, dtype=dtype)[0]
+ along_x = get_gaussian_kernel1d(9, 2.0, device=device, dtype=dtype)[0]
+ self.assert_close(kernel[0], along_y[:, None] * along_x[None, :])
+ # relabel: swapping both tuples transposes the kernel
+ swapped = get_gaussian_kernel2d((9, 7), (2.0, 1.0), device=device, dtype=dtype)
+ self.assert_close(swapped[0], kernel[0].T)
+
+ def test_convention_gaussian_kernel3d_sizes_and_sigmas_are_z_y_x(self, device, dtype):
+ kernel = get_gaussian_kernel3d((3, 5, 7), (0.7, 1.0, 1.5), device=device, dtype=dtype)
+ assert kernel.shape == (1, 3, 5, 7)
+ along_z = get_gaussian_kernel1d(3, 0.7, device=device, dtype=dtype)[0]
+ along_y = get_gaussian_kernel1d(5, 1.0, device=device, dtype=dtype)[0]
+ along_x = get_gaussian_kernel1d(7, 1.5, device=device, dtype=dtype)[0]
+ self.assert_close(kernel[0], along_z[:, None, None] * along_y[None, :, None] * along_x[None, None, :])
+
+ @pytest.mark.parametrize("ndim", [1, 2, 3])
+ def test_convention_gaussian_kernel_batched_sigma_gives_one_kernel_per_row(self, ndim, device, dtype):
+ builder = {1: get_gaussian_kernel1d, 2: get_gaussian_kernel2d, 3: get_gaussian_kernel3d}[ndim]
+ sizes = (3, 5, 7)[:ndim]
+ size_arg = sizes[0] if ndim == 1 else sizes
+ sigma = torch.tensor([[0.8, 1.2, 1.6][:ndim], [1.5, 0.6, 1.1][:ndim]], device=device, dtype=dtype) # (B, ndim)
+ kernels = builder(size_arg, sigma)
+ assert kernels.shape == (2, *sizes)
+ for b in range(2):
+ self.assert_close(kernels[b : b + 1], builder(size_arg, sigma[b : b + 1]))
+
+ def test_convention_laplacian_kernels_are_ones_with_a_balancing_negative_centre(self, device, dtype):
+ def ones_with_centre(shape, centre):
+ out = torch.ones(shape, device=device, dtype=dtype)
+ out[tuple(s // 2 for s in shape)] = centre
+ return out
+
+ self.assert_close(get_laplacian_kernel1d(3, device=device, dtype=dtype), ones_with_centre((3,), -2.0))
+ self.assert_close(get_laplacian_kernel1d(5, device=device, dtype=dtype), ones_with_centre((5,), -4.0))
+ kernel = get_laplacian_kernel2d(3, device=device, dtype=dtype) # the 8-neighbour stencil
+ self.assert_close(kernel, ones_with_centre((3, 3), -8.0))
+ self.assert_close(get_laplacian_kernel2d((3, 5), device=device, dtype=dtype), ones_with_centre((3, 5), -14.0))
+ # the negative centre makes the response positive on a convex field: 3 per unit d2/dx2 or d2/dy2
+ ys, xs = _grid(9, 11, centre=(3, 6), device=device, dtype=dtype)
+ for field in (xs * xs / 2, ys * ys / 2):
+ self.assert_close(
+ _correlate_at(kernel[None], field, (3, 6)), torch.tensor([3.0], device=device, dtype=dtype)
+ )
+
+ def test_convention_laplacian_1d_puts_an_even_kernels_negative_tap_at_k_half(self, device, dtype):
+ # laplacian_1d does not validate the size: an even one is accepted and its centre tap sits at k // 2
+ self.assert_close(
+ laplacian_1d(4, device=device, dtype=dtype), torch.tensor([1.0, 1.0, -3.0, 1.0], device=device, dtype=dtype)
+ )
+ expected = torch.tensor([1.0, 1.0, 1.0, -5.0, 1.0, 1.0], device=device, dtype=dtype)
+ self.assert_close(laplacian_1d(6, device=device, dtype=dtype), expected)
+
+ def test_convention_binary_kernel2d_is_a_row_major_one_hot_stack(self, device, dtype):
+ kernel = get_binary_kernel2d((3, 5), device=device, dtype=dtype)
+ # channel i is one-hot at (i // 5, i % 5)
+ self.assert_close(kernel, torch.eye(15, device=device, dtype=dtype).view(15, 1, 3, 5))
+
+ @pytest.mark.parametrize(
+ "name, scale", [("get_sobel_kernel2d", 8.0), ("sobel", 8.0), ("get_diff_kernel2d", 2.0), ("diff", 2.0)]
+ )
+ def test_convention_spatial_gradient_kernel2d_stacks_dx_then_dy(self, name, scale, device, dtype):
+ builders = {"get_sobel_kernel2d": get_sobel_kernel2d, "get_diff_kernel2d": get_diff_kernel2d}
+ if name in builders:
+ kernel = builders[name](device=device, dtype=dtype)
+ else:
+ kernel = get_spatial_gradient_kernel2d(name, 1, device=device, dtype=dtype)
+ ys, xs = _grid(9, 11, centre=(3, 6), device=device, dtype=dtype)
+ field = 2 * xs + 3 * ys # d/dx = 2, d/dy = 3
+ # channel 0 estimates d/dx and channel 1 d/dy, positive for values increasing with column / row, in raw
+ # units: Sobel 8 and diff 2 per unit slope
+ expected = torch.tensor([2 * scale, 3 * scale], device=device, dtype=dtype)
+ self.assert_close(_correlate_at(kernel, field, (3, 6)), expected)
+ # relabel: transposing the field swaps the channels
+ self.assert_close(_correlate_at(kernel, field.T, (6, 3)), expected.flip(0))
+
+ @pytest.mark.parametrize("mode, scales", [("sobel", (64.0, 64.0, 64.0)), ("diff", (1.0, 4.0, 1.0))])
+ def test_convention_spatial_gradient_kernel2d_order2_stacks_dxx_dxy_dyy(self, mode, scales, device, dtype):
+ kernel = get_spatial_gradient_kernel2d(mode, 2, device=device, dtype=dtype)
+ ys, xs = _grid(9, 11, centre=(3, 6), device=device, dtype=dtype)
+ # unit d2/dx2, d2/dxdy and d2/dy2 fields; row f of the response holds the three channels' answers to field f
+ fields = (xs * xs / 2, xs * ys, ys * ys / 2)
+ response = torch.stack([_correlate_at(kernel, field, (3, 6)) for field in fields])
+ self.assert_close(response, torch.diag(torch.tensor(scales, device=device, dtype=dtype)))
+
+ def test_convention_spatial_gradient_kernel3d_is_diff_only_in_derivative_units(self, device, dtype):
+ zs, ys, xs = _grid(7, 9, 11, centre=(3, 4, 6), device=device, dtype=dtype) # D != H != W
+ first = get_spatial_gradient_kernel3d("diff", 1, device=device, dtype=dtype)
+ assert first.shape == (3, 1, 3, 3, 3)
+ # (d/dx, d/dy, d/dz) in unit slope
+ response = _correlate_at(first[:, 0], xs + 2 * ys + 3 * zs, (3, 4, 6))
+ self.assert_close(response, torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype))
+ second = get_spatial_gradient_kernel3d("diff", 2, device=device, dtype=dtype)
+ assert second.shape == (6, 1, 3, 3, 3)
+ # (dxx, dyy, dzz, dxy, dyz, dxz), each in unit curvature
+ fields = (xs * xs / 2, ys * ys / 2, zs * zs / 2, xs * ys, ys * zs, xs * zs)
+ response = torch.stack([_correlate_at(second[:, 0], field, (3, 4, 6)) for field in fields])
+ self.assert_close(response, torch.eye(6, device=device, dtype=dtype))
+ with pytest.raises(NotImplementedError):
+ get_spatial_gradient_kernel3d("sobel", 1, device=device, dtype=dtype)
+
+ def test_convention_motion_kernel2d_angle_is_degrees_counterclockwise(self, device, dtype):
+ _kernel_guard("get_motion_kernel2d", device, dtype)
+
+ def heaviest(angle: float) -> tuple[int, int]:
+ angle_t = torch.tensor(angle, device=device, dtype=dtype)
+ kernel = get_motion_kernel2d(5, angle_t, torch.tensor(1.0, device=device, dtype=dtype))[0]
+ return divmod(int(kernel.float().flatten().argmax()), 5)
+
+ # direction=+1 weighs the unrotated line's left end most
+ assert heaviest(0.0) == (2, 0)
+ # +90 degrees turns it counter-clockwise as displayed (row 0 at the top): the left end goes to the bottom
+ assert heaviest(90.0) == (4, 2)
+ assert heaviest(-90.0) == (0, 2)
+ assert heaviest(30.0) == (3, 0)
+
+ def test_convention_motion_kernel2d_direction_weights_the_back_end(self, device, dtype):
+ _kernel_guard("get_motion_kernel2d", device, dtype)
+
+ def kernel(direction: float) -> torch.Tensor:
+ angle = torch.tensor(0.0, device=device, dtype=dtype)
+ return get_motion_kernel2d(5, angle, torch.tensor(direction, device=device, dtype=dtype))[0]
+
+ # direction=+1 is a linear ramp down from the left end whose far tap is 0: only k - 1 taps weigh
+ forward = torch.zeros(5, 5, device=device, dtype=dtype)
+ forward[2] = torch.tensor([0.4, 0.3, 0.2, 0.1, 0.0], device=device, dtype=dtype)
+ self.assert_close(kernel(1.0), forward)
+ self.assert_close(kernel(-1.0), forward.flip(-1))
+ uniform = torch.zeros(5, 5, device=device, dtype=dtype)
+ uniform[2] = 0.2
+ self.assert_close(kernel(0.0), uniform)
+ # in between, the ramp's slope is linear in direction: 0.5 weighs the taps 0.3 down to 0.1
+ half = torch.zeros(5, 5, device=device, dtype=dtype)
+ half[2] = torch.tensor([0.3, 0.25, 0.2, 0.15, 0.1], device=device, dtype=dtype)
+ self.assert_close(kernel(0.5), half)
+ self.assert_close(kernel(-0.5), half.flip(-1))
+ # direction is clamped to [-1, 1], at both ends
+ self.assert_close(kernel(5.0), forward)
+ self.assert_close(kernel(-5.0), forward.flip(-1))
+
+ def test_convention_motion_kernel2d_batched_angle_needs_a_matching_direction(self, device, dtype):
+ _kernel_guard("get_motion_kernel2d", device, dtype)
+ angles = torch.tensor([0.0, 30.0, 90.0], device=device, dtype=dtype)
+ directions = torch.tensor([1.0, -0.5, 0.0], device=device, dtype=dtype)
+ kernels = get_motion_kernel2d(5, angles, directions)
+ assert kernels.shape == (3, 5, 5)
+ assert kernels.dtype == dtype
+ for b in range(3):
+ self.assert_close(kernels[b : b + 1], get_motion_kernel2d(5, angles[b], directions[b]))
+ with pytest.raises(BaseError, match="direction and angle must have the same length"):
+ get_motion_kernel2d(5, angles, 1.0)
+
+ def test_convention_motion_kernel2d_nearest_drops_off_axis_taps(self, device, dtype):
+ _kernel_guard("get_motion_kernel2d", device, dtype)
+ angle = torch.tensor(45.0, device=device, dtype=dtype)
+ direction = torch.tensor(0.0, device=device, dtype=dtype)
+ nearest = get_motion_kernel2d(5, angle, direction, mode="nearest")[0]
+ # at 45 degrees nearest resampling keeps 3 of the 5 taps of the uniform line, each 1/3
+ kept = nearest[nearest > 0]
+ assert kept.numel() == 3
+ self.assert_close(kept, torch.full((3,), 1 / 3, device=device, dtype=dtype))
+ # bilinear resampling spreads the weight off the line instead
+ bilinear = get_motion_kernel2d(5, angle, direction, mode="bilinear")[0]
+ assert int((bilinear > 0).sum()) > 5
+
+ def test_convention_motion_kernel3d_angle_is_an_axis_angle_vector(self, device, dtype):
+ _kernel_guard("get_motion_kernel3d", device, dtype)
+
+ def kernel(angles: tuple[float, float, float]) -> torch.Tensor:
+ angle_t = torch.tensor([angles], device=device, dtype=dtype)
+ return get_motion_kernel3d(5, angle_t, torch.tensor([1.0], device=device, dtype=dtype))[0]
+
+ def heaviest(angles: tuple[float, float, float]) -> tuple[int, int, int]:
+ index = int(kernel(angles).float().flatten().argmax())
+ return (index // 25, index // 5 % 5, index % 5) # (d, h, w)
+
+ # direction=+1 weighs the unrotated line's -x end most
+ assert heaviest((0.0, 0.0, 0.0)) == (2, 2, 0)
+ # positive pitch (about y) sends that end to +z
+ assert heaviest((0.0, 90.0, 0.0)) == (4, 2, 2)
+ # positive roll (about z) sends it to -y: clockwise as displayed, opposite to get_motion_kernel2d's angle
+ assert heaviest((0.0, 0.0, 90.0)) == (2, 0, 2)
+ # the line lies along x, so yaw (about x) alone leaves the kernel unchanged
+ self.assert_close(kernel((90.0, 0.0, 0.0)), kernel((0.0, 0.0, 0.0)))
+
+ # Rodrigues' formula for (90, 90, 0): rotate through 90 * sqrt(2) degrees about (1, 1, 0) / sqrt(2).
+ # The heavy-end direction (-1, 0, 0) becomes (-0.19715, -0.80285, 0.56264), unlike either Euler
+ # composition (0, 0, 1) or (0, -1, 0). Nearest resampling keeps the three central line taps, whose weights
+ # on the size-5 line are 0.1, 0.2 and 0.3, renormalised below in (depth, row, column) order.
+ expected = torch.zeros(5, 5, 5, device=device, dtype=dtype)
+ expected[1, 3, 2] = 1 / 6
+ expected[2, 2, 2] = 1 / 3
+ expected[3, 1, 2] = 1 / 2
+ self.assert_close(kernel((90.0, 90.0, 0.0)), expected)
+
+ def test_wart_gaussian_discrete_kernel1d_tap_count_is_not_kernel_size_5158(self, device, dtype):
+ """get_gaussian_discrete_kernel1d gives 3 taps for kernel_size=1 and k + 1 for an even force_even k (#5158)."""
+ assert get_gaussian_discrete_kernel1d(1, 1.0, device=device, dtype=dtype).shape == (1, 3)
+ even = get_gaussian_discrete_kernel1d(4, 1.0, force_even=True, device=device, dtype=dtype)
+ assert even.shape == (1, 5)
+
+ def test_wart_gaussian_erf_kernel1d_even_kernel_peaks_at_k_half_5158(self, device, dtype):
+ """get_gaussian_erf_kernel1d(force_even=True) samples about k // 2, so an even kernel is off-centre (#5158)."""
+ kernel = get_gaussian_erf_kernel1d(4, 1.0, force_even=True, device=device, dtype=dtype)[0]
+ # the sampled get_gaussian_kernel1d with the same arguments is symmetric about (k - 1) / 2 = 1.5
+ assert int(kernel.float().argmax()) == 2
+ assert kernel[2] > kernel[1]
+
+ def test_wart_gaussian_discrete_kernel1d_overflows_to_nan_5227(self, device, dtype):
+ """get_gaussian_discrete_kernel1d computes its Bessel terms unscaled and overflows to NaN (#5227)."""
+ # the smallest failing sigma depends on the dtype: about 6.8 in float32 and bfloat16, about 19 in float64;
+ # in float16 every sigma > 0 fails once kernel_size is 5 or more
+ sigma = {torch.float16: 1.0, torch.bfloat16: 7.0, torch.float32: 7.0, torch.float64: 20.0}[dtype]
+ kernel = get_gaussian_discrete_kernel1d(5, sigma, device=device, dtype=dtype)
+ assert bool(torch.isnan(kernel).all())
+
+ def test_wart_gaussian_discrete_kernel1d_drifts_in_float64_for_a_large_sigma_5227(self, device, dtype):
+ """Before it overflows, the float64 discrete kernel drifts from the discrete Gaussian (#5227)."""
+ if dtype != torch.float64:
+ pytest.skip("the drift shows in float64; the other dtypes overflow first (#5227)")
+ kernel = get_gaussian_discrete_kernel1d(85, 14.0, device=device, dtype=dtype)[0]
+ # scipy.special.ive(abs(n), 14.0**2) is unimodal; here tap 39 (n = -3) dips below tap 38 (n = -4)
+ assert kernel[39] < kernel[38]
+
+ @pytest.mark.parametrize(
+ "builder", [get_gaussian_kernel1d, get_gaussian_erf_kernel1d, get_gaussian_discrete_kernel1d]
+ )
+ def test_wart_gaussian_kernel1d_rejects_a_python_int_sigma_5157(self, builder, device, dtype):
+ """The 1d Gaussian builders raise for sigma=1, where the 2d builder accepts sigma=(1, 1) (#5157)."""
+ with pytest.raises((BaseError, AttributeError)):
+ builder(5, 1, device=device, dtype=dtype)
+ assert builder(5, 1.0, device=device, dtype=dtype).shape == (1, 5)
+ assert get_gaussian_kernel2d((5, 5), (1, 1), device=device, dtype=dtype).shape == (1, 5, 5)
+
+ @pytest.mark.parametrize("case", ["box_int32", "gaussian_uint8", "laplacian_uint8", "gradient3d_int32"])
+ def test_wart_kernel_builders_truncate_or_wrap_in_an_integer_dtype_5155(self, case, device):
+ """An integer dtype truncates fractional taps to 0, and uint8 wraps the negative ones (#5155)."""
+ if case == "box_int32":
+ assert bool((get_box_kernel1d(3, device=device, dtype=torch.int32) == 0).all())
+ elif case == "gaussian_uint8":
+ # the offsets -2 and -1 wrap to 254 and 255, so the taps before the centre vanish
+ kernel = get_gaussian_kernel1d(5, 1.5, device=device, dtype=torch.uint8)[0]
+ assert kernel[:2].tolist() == [0, 0]
+ assert bool((kernel[2:] > 0).all())
+ elif case == "laplacian_uint8":
+ assert get_laplacian_kernel1d(5, device=device, dtype=torch.uint8).tolist() == [1, 1, 252, 1, 1]
+ else:
+ # the first-order taps are +-0.5
+ assert bool((get_spatial_gradient_kernel3d("diff", 1, device=device, dtype=torch.int32) == 0).all())
+
+ def test_wart_motion_kernel2d_nearest_ties_change_with_a_full_turn_5181(self):
+ """At a sampling-tie angle roundoff picks the tap: 30 and -330 degrees build other kernels (#5181)."""
+ # a float angle builds the kernel on the CPU in float32, whatever the test device
+ difference = get_motion_kernel2d(5, 30.0, 1.0) - get_motion_kernel2d(5, -330.0, 1.0)
+ assert float(difference.abs().max()) > 0.1
+
+ def test_wart_motion_kernel2d_on_mps_differs_from_cpu_for_some_angles_5181(self, device, dtype):
+ """A tensor angle builds get_motion_kernel2d on its own device, and MPS gives other kernels (#5181)."""
+ if device.type != "mps":
+ pytest.skip("#5181 compares the kernel built on MPS with the one built on the CPU")
+ _kernel_guard("get_motion_kernel2d", torch.device("cpu"), dtype)
+ # every whole degree, including 120 and 210
+ angles = torch.arange(0.0, 360.0, 1.0, dtype=dtype)
+ directions = torch.full_like(angles, 0.3)
+ on_cpu = get_motion_kernel2d(7, angles, directions)
+ on_mps = get_motion_kernel2d(7, angles.to(device), directions.to(device)).cpu()
+ # a sampling tie rounded the other way moves a tap weight (about 0.18), far beyond half-precision roundoff
+ differing = (on_mps.float() - on_cpu.float()).abs().flatten(1).amax(1) > 0.05
+ if not bool(differing.any()):
+ pytest.skip("this MPS backend rounds the sampling ties like the CPU (#5181)")
+ # a Python-float angle builds the kernel on the CPU in float32, equal to the CPU tensor-angle kernel
+ on_cpu_f32 = get_motion_kernel2d(7, angles.float(), directions.float())
+ for index in differing.nonzero().flatten().tolist():
+ from_float = get_motion_kernel2d(7, float(angles[index]), float(directions[index]))
+ assert from_float.device.type == "cpu"
+ self.assert_close(from_float[0], on_cpu_f32[index])
+
+ @pytest.mark.parametrize("ndim", [1, 2])
+ def test_wart_box_kernel_is_a_stride_zero_view_5160(self, ndim, device, dtype):
+ """get_box_kernel1d/2d return an expanded view of one scalar, so writing one tap rewrites all (#5160)."""
+ if ndim == 1:
+ kernel = get_box_kernel1d(3, device=device, dtype=dtype)
+ else:
+ kernel = get_box_kernel2d((3, 4), device=device, dtype=dtype)
+ kernel[(0,) * kernel.dim()] = 0.0
+ assert bool((kernel == 0).all())
diff --git a/tests/filters/test_hanning.py b/tests/filters/test_hanning.py
index 51f703364..c5cb0e666 100644
--- a/tests/filters/test_hanning.py
+++ b/tests/filters/test_hanning.py
@@ -15,12 +15,14 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
from kornia.filters import get_hanning_kernel1d, get_hanning_kernel2d
-from testing.base import assert_close
+from testing.base import BaseTester, assert_close
@pytest.mark.parametrize("window_size", [5, 11])
@@ -52,3 +54,24 @@ def test_get_hanning_kernel2d_3x4(device, dtype):
)
assert kernel.shape == (3, 4)
assert_close(kernel, expected)
+
+
+class TestConventionsHanningKernels(BaseTester):
+ @pytest.mark.parametrize("window_size", [4, 5, 6])
+ def test_convention_hanning_kernel1d_is_the_unnormalised_symmetric_window(self, window_size, device, dtype):
+ kernel = get_hanning_kernel1d(window_size, device=device, dtype=dtype)
+ # numpy.hanning, torch.hann_window(periodic=False): 0.5 - 0.5 cos(2 pi n / (k - 1)), zero at both ends
+ n = torch.arange(window_size, dtype=torch.float64)
+ expected = (0.5 - 0.5 * torch.cos(2 * math.pi * n / (window_size - 1))).to(device=device, dtype=dtype)
+ half = dtype in (torch.float16, torch.bfloat16) # the cosine is evaluated in the kernel's dtype
+ self.assert_close(kernel, expected, low_tolerance=half)
+ # not normalised: the taps sum to (k - 1) / 2
+ total = torch.tensor((window_size - 1) / 2, device=device, dtype=dtype)
+ self.assert_close(kernel.sum(), total, low_tolerance=half)
+
+ def test_convention_hanning_kernel2d_is_the_outer_product_in_y_x_order(self, device, dtype):
+ kernel = get_hanning_kernel2d((5, 4), device=device, dtype=dtype)
+ assert kernel.shape == (5, 4)
+ along_y = get_hanning_kernel1d(5, device=device, dtype=dtype)
+ along_x = get_hanning_kernel1d(4, device=device, dtype=dtype)
+ self.assert_close(kernel, along_y[:, None] * along_x[None, :])