π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(filters): Convention blocks and pins for the blurring operators (batch 11b) (#5433)
Dmytro Mishkinaf10a025d5f3
diff --git a/changelog.d/5433.added.md b/changelog.d/5433.added.mdnew file mode 100644index 000000000..5a16fb417--- /dev/null+++ b/changelog.d/5433.added.md@@ -0,0 +1 @@+Convention blocks for the blurring operators of `kornia.filters` (`gaussian_blur2d`, `box_blur`, `median_blur`, `bilateral_blur`, `joint_bilateral_blur`, `guided_blur`, `motion_blur`, `motion_blur3d`, `unsharp_mask`, `blur_pool2d`, `max_blur_pool2d`, `edge_aware_blur_pool2d` and their module classes): `kernel_size` and `sigma` given rows first, per-sample tensor sigmas, the bilateral and guided filters' parameter units and argument order, the motion-blur angle and streak weighting, the blur pools' sampling grid and padding. The Filtering section of the Conventions page relates them to OpenCV, scipy, scikit-image and the antialiased-cnns `BlurPool`. `edge_aware_blur_pool2d`, `motion_blur3d`, `EdgeAwareBlurPool2D`, `MotionBlur3D` and `StableDiffusionDissolving` are added to the API reference.diff --git a/docs/source/filters.blurring.rst b/docs/source/filters.blurring.rstindex fa6916df9..362884cc9 100644--- a/docs/source/filters.blurring.rst+++ b/docs/source/filters.blurring.rst@@ -9,12 +9,14 @@ Functions.. autofunction:: bilateral_blur.. autofunction:: blur_pool2d.. autofunction:: box_blur+.. autofunction:: edge_aware_blur_pool2d.. autofunction:: gaussian_blur2d.. autofunction:: guided_blur.. autofunction:: joint_bilateral_blur.. autofunction:: max_blur_pool2d.. autofunction:: median_blur.. autofunction:: motion_blur+.. autofunction:: motion_blur3d.. autofunction:: unsharp_maskModules@@ -23,10 +25,17 @@ Modules.. autoclass:: BilateralBlur.. autoclass:: BlurPool2D.. autoclass:: BoxBlur+.. autoclass:: EdgeAwareBlurPool2D.. autoclass:: MaxBlurPool2D.. autoclass:: MedianBlur.. autoclass:: GaussianBlur2d.. autoclass:: GuidedBlur.. autoclass:: JointBilateralBlur.. autoclass:: MotionBlur+.. autoclass:: MotionBlur3D.. autoclass:: UnsharpMask++Dissolving+----------++.. autoclass:: StableDiffusionDissolvingdiff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex c54ff13b1..b4aca41f7 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -586,7 +586,7 @@ is a ``[row, col]`` index and ``border_type`` takes torch's pad names. Below, ``- ``circular``- ``wrap``- ``wrap``- - rejected (``BORDER_WRAP``)+ - no equivalent: ``BORDER_WRAP`` raises, except on uint8, where the result is not a wrapThe equivalences cover empty ``geodesic`` windows too: scipy, scikit-image and kornia all return ``-inf`` fromsuch a window in a dilation and ``+inf`` in an erosion, whatever the data range.@@ -669,6 +669,36 @@ The kernel builders against their references: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`.+The blurs give sizes and standard deviations rows first, as torch orders ``(H, W)``: ``kernel_size`` is+``(kh, kw)`` and ``sigma`` is :math:`(\sigma_y, \sigma_x)` in :func:`~kornia.filters.gaussian_blur2d`,+:func:`~kornia.filters.box_blur`, :func:`~kornia.filters.median_blur` and the filters built on them. OpenCV passes+both pairs x first, so swap them when porting; scipy uses kornia's order. For odd ``kh`` and ``kw``, with the border+mapped by the table above (OpenCV accepts ``BORDER_WRAP`` in these calls only for some dtypes and sizes):++- ``gaussian_blur2d(x, (kh, kw), (sy, sx))`` equals ``cv2.GaussianBlur(x, (kw, kh), sigmaX=sx, sigmaY=sy)`` and+ ``scipy.ndimage.gaussian_filter(x, sigma=(sy, sx), radius=(kh // 2, kw // 2))``.+- ``box_blur(x, (kh, kw))`` equals ``cv2.blur(x, (kw, kh))`` and ``scipy.ndimage.uniform_filter(x, size=(kh, kw))``.++The edge-preserving filters, the sharpening and the blur pools against their references:++- :func:`~kornia.filters.bilateral_blur` with ``'l1'`` uses the colour distance of ``cv2.bilateralFilter``, but+ weighs the whole ``kernel_size`` rectangle where OpenCV weighs only the disc of radius ``d // 2``, so the two differ+ even for ``kernel_size=(d, d)``.+- ``guided_blur(guide, src, 2 * r + 1, eps)`` equals ``cv2.ximgproc.guidedFilter(guide, src, r, eps)`` away from the+ border: ``eps`` is the same quantity, but OpenCV pads with ``BORDER_REFLECT``, which has no kornia mode.+ :func:`~kornia.filters.joint_bilateral_blur` takes its guide second, where+ ``cv2.ximgproc.jointBilateralFilter(joint, src, ...)`` takes it first.+- ``unsharp_mask(x, (k, k), (r, r))`` with ``k = 2 * int(4 * r + 0.5) + 1``, the window scikit-image truncates its+ Gaussian to, equals ``skimage.filters.unsharp_mask(x, radius=r, amount=1, preserve_range=True)`` away from the+ border. scikit-image pads with scipy's ``reflect``, which has no kornia mode, and with its default+ ``preserve_range=False`` it clips the result, which :func:`~kornia.filters.unsharp_mask` never does.+- ``blur_pool2d(x, k, s)`` equals the antialiased-cnns ``BlurPool(channels, pad_type='zero', filt_size=k, stride=s)``,+ which defines ``filt_size`` up to 7. The reference's default ``pad_type='reflect'`` keeps a constant map constant+ where :func:`~kornia.filters.blur_pool2d` zero-pads and darkens its border.+- ``blur_pool2d(x, 5, 2)`` blurs with the 5 x 5 binomial kernel of :func:`~kornia.geometry.transform.pyrdown` but+ samples differently: it zero-pads and keeps every second pixel from index 0, :math:`\lceil H / 2 \rceil` rows,+ where ``pyrdown`` reflects the border and interpolates between pixels, :math:`\lfloor H / 2 \rfloor` rows.+.. _two-view-conventions:Two-view geometrydiff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.pyindex d401dc684..6b0e39ecd 100644--- a/kornia/filters/bilateral.py+++ b/kornia/filters/bilateral.py@@ -124,6 +124,23 @@ def bilateral_blur(for each pixel in a neighborhood is determined not only by its distanceto the center pixel, but also the difference in intensity or color.+ Convention:+ - A neighbour weighs :math:`g \, \exp(-d^2 / (2 \sigma_{color}^2))`. :math:`g` is the Gaussian of+ :func:`~kornia.filters.gaussian_blur2d` with ``sigma = sigma_space``, :math:`(\sigma_y, \sigma_x)`, over+ the whole ``kernel_size`` rectangle, and :math:`d` is the neighbour's colour distance from the centre+ pixel: the sum of the absolute channel differences for ``'l1'``, their Euclidean norm for ``'l2'``.+ :ref:`Filtering <filtering-conventions>` compares this with OpenCV.+ - ``sigma_color`` is in the units of the input values: an image scaled by ``s > 0``, filtered with+ ``sigma_color * s``, gives the result scaled by ``s``.+ - The border modes are :func:`~kornia.filters.filter2d`'s, but only in lower case; see its Convention block.+ - Known defects:++ - an integer input is differenced in its own dtype, so uint8 differences wrap and the filter blends+ across edges it should keep (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+ - a tensor ``sigma_space`` keeps its own dtype, unlike ``sigma_color``, so a wider one promotes the output:+ a float32 image with a float64 ``sigma_space`` comes back float64+ (`#5521 <https://github.com/kornia/kornia/issues/5521>`_).+Arguments:input: the input torch.Tensor with shape :math:`(B,C,H,W)`.kernel_size: the size of the kernel. Each entry must be a positive odd integer.@@ -137,9 +154,7 @@ def bilateral_blur(The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``. Default: ``'reflect'``.color_distance_type: the type of distance to calculate intensity/color- difference. Only ``'l1'`` or ``'l2'`` is allowed. Use ``'l1'`` to- match OpenCV implementation. Use ``'l2'`` to match Matlab implementation.- Default: ``'l1'``.+ difference. Only ``'l1'`` or ``'l2'`` is allowed. Default: ``'l1'``.Returns:the blurred torch.Tensor with shape :math:`(B, C, H, W)`.@@ -176,9 +191,18 @@ def joint_bilateral_blur(is that the color Gaussian kernel is computed based on another image calleda guidance image. See :func:`bilateral_blur()` for more information.+ Convention:+ - See the Convention block on :func:`~kornia.filters.bilateral_blur`; the colour distances are taken in+ ``guidance``, and ``input`` is what gets averaged.+ - ``input`` comes first and ``guidance`` second, the opposite of :func:`~kornia.filters.guided_blur`.+ - ``guidance`` may have its own channel count; its batch size and :math:`(H, W)` must equal ``input``'s.+ - Known defects: those of :func:`~kornia.filters.bilateral_blur`, for an integer ``guidance``+ (`#5155 <https://github.com/kornia/kornia/issues/5155>`_) and for a tensor ``sigma_space`` of a wider dtype,+ which ``guidance`` of a wider dtype shares (`#5521 <https://github.com/kornia/kornia/issues/5521>`_).+Arguments:input: the input torch.Tensor with shape :math:`(B,C,H,W)`.- guidance: the guidance torch.Tensor with shape :math:`(B,C,H,W)`.+ guidance: the guidance torch.Tensor with shape :math:`(B,C_g,H,W)`.kernel_size: the size of the kernel. Each entry must be a positive odd integer.sigma_color: the standard deviation for intensity/color Gaussian kernel.Smaller values preserve more edges. It must be positive. A float is shared by the batch; a@@ -190,8 +214,7 @@ def joint_bilateral_blur(The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``. Default: ``'reflect'``.color_distance_type: the type of distance to calculate intensity/color- difference. Only ``'l1'`` or ``'l2'`` is allowed. Use ``'l1'`` to- match OpenCV implementation.+ difference. Only ``'l1'`` or ``'l2'`` is allowed. Default: ``'l1'``.Returns:the blurred torch.Tensor with shape :math:`(B, C, H, W)`.@@ -248,6 +271,9 @@ class BilateralBlur(_BilateralBlur):for each pixel in a neighborhood is determined not only by its distanceto the center pixel, but also the difference in intensity or color.+ Convention:+ See the Convention block on :func:`~kornia.filters.bilateral_blur`.+Arguments:kernel_size: the size of the kernel. Each entry must be a positive odd integer.sigma_color: the standard deviation for intensity/color Gaussian kernel.@@ -260,9 +286,7 @@ class BilateralBlur(_BilateralBlur):The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``. Default: ``'reflect'``.color_distance_type: the type of distance to calculate intensity/color- difference. Only ``'l1'`` or ``'l2'`` is allowed. Use ``'l1'`` to- match OpenCV implementation. Use ``'l2'`` to match Matlab implementation.- Default: ``'l1'``.+ difference. Only ``'l1'`` or ``'l2'`` is allowed. Default: ``'l1'``.Returns:the blurred input torch.Tensor.@@ -303,10 +327,11 @@ class BilateralBlur(_BilateralBlur):Returns:Tensor with shape :math:`(B, C, H, W)` containing the- edge-preserving smoothed image. The output keeps the same layout,- dtype, and device as ``input`` while reducing small local- variations according to the configured kernel size and sigma- values.+ edge-preserving smoothed image. The output keeps the layout and+ device of ``input``, and the dtype of a floating ``input`` unless a+ tensor ``sigma_space`` of a wider dtype promotes it, while reducing+ small local variations according to the configured kernel size and+ sigma values."""return bilateral_blur(input, self.kernel_size, self.sigma_color, self.sigma_space, self.border_type, self.color_distance_type@@ -320,6 +345,9 @@ class JointBilateralBlur(_BilateralBlur):is that the color Gaussian kernel is computed based on another image calleda guidance image. See :class:`BilateralBlur` for more information.+ Convention:+ See the Convention block on :func:`~kornia.filters.joint_bilateral_blur`.+Arguments:kernel_size: the size of the kernel. Each entry must be a positive odd integer.sigma_color: the standard deviation for intensity/color Gaussian kernel.@@ -332,14 +360,13 @@ class JointBilateralBlur(_BilateralBlur):The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``. Default: ``'reflect'``.color_distance_type: the type of distance to calculate intensity/color- difference. Only ``'l1'`` or ``'l2'`` is allowed. Use ``'l1'`` to- match OpenCV implementation.+ difference. Only ``'l1'`` or ``'l2'`` is allowed. Default: ``'l1'``.Returns:the blurred input torch.Tensor.Shape:- - Input: :math:`(B, C, H, W)`, :math:`(B, C, H, W)`+ - Input: :math:`(B, C, H, W)`, :math:`(B, C_g, H, W)`- Output: :math:`(B, C, H, W)`Raises:@@ -373,7 +400,7 @@ class JointBilateralBlur(_BilateralBlur)::math:`B` is the batch size, :math:`C` is the number of inputchannels, :math:`H` is the height, and :math:`W` is the width.guidance: Tensor used to compute range weights. Its batch and- spatial dimensions must be compatible with ``input``; its+ spatial dimensions must equal those of ``input``; itschannel count may differ when the guidance signal uses adifferent representation.diff --git a/kornia/filters/blur.py b/kornia/filters/blur.pyindex cc8ac29b1..dcfcd82eb 100644--- a/kornia/filters/blur.py+++ b/kornia/filters/blur.py@@ -124,18 +124,22 @@ def box_blur(1 & 1 & 1 & \cdots & 1 & 1 \\\end{bmatrix}+ Convention:+ - ``kernel_size`` is ``(kH, kW)``. An even extent is anchored at ``(k - 1) // 2`` and the output keeps the+ input's size; see the Convention block on :func:`~kornia.filters.filter2d` for the anchor and the border+ modes.+ - Known defect: an integer input gets a kernel in its own dtype, whose ``1 / k`` taps truncate to 0, so on+ the CPU a uint8 image comes back as zeros (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+Args:input: the image to blur with shape :math:`(B,C,H,W)`.kernel_size: the blurring kernel size.border_type: the padding mode to be applied before convolving.The expected modes are: ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.+ Default: ``'reflect'``.separable: use two one-dimensional passes (the default), reducing work- for larger kernels. Floating inputs use average pooling outside autocast- where it is faster (on CPUs with oneDNN, only for large inputs or small- compiled windows); complex inputs and autocast use convolution. The dense implementation- may differ by floating-point roundoff. Ordinary eager CPU execution- falls back to convolution for extreme input ranges; captured graphs- and function transforms retain native pooling arithmetic.+ for larger kernels. The two implementations agree to floating-point roundoff while the sum of a window's+ absolute values stays below the dtype's largest finite value; beyond it the result can be ``inf`` or NaN.Returns:the blurred torch.Tensor with shape :math:`(B,C,H,W)`.@@ -184,18 +188,17 @@ class BoxBlur(nn.Module):1 & 1 & 1 & \cdots & 1 & 1 \\\end{bmatrix}+ Convention:+ See the Convention block on :func:`~kornia.filters.box_blur`.+Args:kernel_size: the blurring kernel size.border_type: the padding mode to be applied before convolving.The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``. Default: ``'reflect'``.separable: use two one-dimensional passes (the default), reducing work- for larger kernels. Floating inputs use average pooling outside autocast- where it is faster (on CPUs with oneDNN, only for large inputs or small- compiled windows); complex inputs and autocast use convolution. The dense implementation- may differ by floating-point roundoff. Ordinary eager CPU execution- falls back to convolution for extreme input ranges; captured graphs- and function transforms retain native pooling arithmetic.+ for larger kernels. The two implementations agree to floating-point roundoff while the sum of a window's+ absolute values stays below the dtype's largest finite value; beyond it the result can be ``inf`` or NaN.Returns:the blurred input torch.Tensor.diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.pyindex 5ab93a6c2..18bdd520d 100644--- a/kornia/filters/blur_pool.py+++ b/kornia/filters/blur_pool.py@@ -43,8 +43,11 @@ class BlurPool2D(nn.Module):See :cite:`zhang2019shiftinvar` for more details.+ Convention:+ See the Convention block on :func:`~kornia.filters.blur_pool2d`.+Args:- kernel_size: the kernel size for max pooling.+ kernel_size: the size of the square binomial blur kernel.stride: stride for pooling.Shape:@@ -98,13 +101,16 @@ class BlurPool2D(nn.Module):class MaxBlurPool2D(nn.Module):r"""Compute pools and blurs and downsample a given feature map.- Equivalent to ```nn.Sequential(nn.MaxPool2d(...), BlurPool2D(...))```+ Equivalent to ``nn.Sequential(nn.MaxPool2d(max_pool_size, stride=1), BlurPool2D(kernel_size, stride))``.See :cite:`zhang2019shiftinvar` for more details.+ Convention:+ See the Convention block on :func:`~kornia.filters.max_blur_pool2d`.+Args:- kernel_size: the kernel size for max pooling.- stride: stride for pooling.+ kernel_size: the size of the square binomial blur kernel.+ stride: stride of the blur step.max_pool_size: the kernel size for max pooling.ceil_mode: deprecated, has no effect. The max pool runs at stride 1, where floor and ceilrounding give the same size, and the strided blur has no rounding mode. Passing it emits a@@ -177,13 +183,16 @@ class MaxBlurPool2D(nn.Module):class EdgeAwareBlurPool2D(nn.Module):- """Apply an edge-aware anti-aliasing filter during downsampling.+ """Apply an edge-aware anti-aliasing blur that keeps the input size.- This module performs blur pooling while preserving edges by using an+ This module blurs while preserving edges by using anedge-intensity threshold.+ Convention:+ See the Convention block on :func:`~kornia.filters.edge_aware_blur_pool2d`.+Args:- kernel_size: The size of the Gaussian blur kernel.+ kernel_size: The size of the square binomial blur kernel.edge_threshold: The intensity ratio between pixels 4 apart above which a pixel counts as an edge and keepsits value. It must be greater than 1. Default: 1.25.edge_dilation_kernel_size: The kernel size for dilating the edge map. It must be an odd positive integer.@@ -213,15 +222,12 @@ class EdgeAwareBlurPool2D(nn.Module)::math:`B` is the batch size, :math:`C` is the number ofchannels, :math:`H` is the input height, and :math:`W` is theinput width.- epsilon: Small positive value used to keep edge-aware divisions- numerically stable when local normalization terms are close to- zero.+ epsilon: Small positive value added to the input before the+ logarithm of the edge test.Returns:- Edge-aware downsampled tensor with shape- :math:`(B, C, H_{out}, W_{out})`. The output preserves channel- order while reducing the spatial dimensions according to the- configured pooling parameters.+ Edge-aware blurred tensor with the shape of ``input``,+ :math:`(B, C, H, W)`."""return edge_aware_blur_pool2d(input, self.kernel_size, self.edge_threshold, self.edge_dilation_kernel_size, epsilon@@ -237,9 +243,18 @@ def blur_pool2d(input: torch.Tensor, kernel_size: tuple[int, int] | int, stride:See :cite:`zhang2019shiftinvar` for more details.+ Convention:+ - The blur is the normalised binomial (Pascal) kernel, which must be square. The blurred map is sampled+ every ``stride`` pixels from index 0.+ - The border is zero-padded, ``(k - 1) // 2`` pixels before and ``k // 2`` after, and there is no+ ``border_type``, so a constant map comes out darker where the kernel reaches past the border. An even+ ``kernel_size`` is thereby anchored at ``(k - 1) // 2``, as in :func:`~kornia.filters.filter2d`.+ :ref:`Filtering <filtering-conventions>` compares the padding with antialiased-cnns, and the sampling with+ :func:`~kornia.geometry.transform.pyrdown`.+Args:input: torch.Tensor to apply operation to.- kernel_size: the kernel size for max pooling.+ kernel_size: the size of the square binomial blur kernel.stride: stride for pooling.Shape:@@ -283,10 +298,15 @@ def max_blur_pool2d(See :class:`~kornia.filters.MaxBlurPool2D` for details.+ Convention:+ - The result equals ``blur_pool2d(F.max_pool2d(input, max_pool_size, stride=1), kernel_size, stride)``: the+ max pool runs at stride 1 without padding and ``stride`` belongs to the blur. See the Convention block on+ :func:`~kornia.filters.blur_pool2d` for the kernel and the border.+Args:input: torch.Tensor to apply operation to.- kernel_size: the kernel size for max pooling.- stride: stride for pooling.+ kernel_size: the size of the square binomial blur kernel.+ stride: stride of the blur step.max_pool_size: the kernel size for max pooling.ceil_mode: deprecated, has no effect. The max pool runs at stride 1, where floor and ceilrounding give the same size, and the strided blur has no rounding mode. Passing it emits a@@ -381,9 +401,23 @@ def edge_aware_blur_pool2d() -> torch.Tensor:r"""Blur the input torch.Tensor while maintaining its edges.+ Convention:+ - Nothing is downsampled: the output has the input's shape.+ - A pixel is on an edge when, along ``x`` or ``y``, the channel mean of ``log2(input + epsilon)`` differs+ by more than ``log2(edge_threshold)`` between the pixels two before and two after it, so scaling the image+ does not move the edges while the intensities stay well above ``epsilon``. Pixels on the edge map,+ dilated by ``edge_dilation_kernel_size``, keep their input value; every other pixel takes the value+ blurred with :func:`~kornia.filters.blur_pool2d`'s kernel at stride 1, with the border reflected as+ ``border_type='reflect'`` reflects it in :func:`~kornia.filters.filter2d`, so a constant image keeps its+ value to roundoff.+ - The input is taken to be positive. Where ``input + epsilon`` is negative its logarithm is NaN, which never+ exceeds the threshold, so a test that reads such a value never finds an edge, and those regions are blurred+ except where the dilation of an adjacent edge reaches them. Values in ``(-epsilon, 0]`` keep a finite+ logarithm and can form edges, and ``input = -epsilon`` gives ``-inf``, an edge against any value above it.+Args:input: the input image to blur with shape :math:`(B, C, H, W)`.- kernel_size: the kernel size for max pooling.+ kernel_size: the size of the square binomial blur kernel.edge_threshold: intensity ratio between pixels 4 apart above which a pixel counts as an edge and keeps itsvalue. It must be greater than 1.edge_dilation_kernel_size: the kernel size for dilating the edges. It must be an odd positive integer.diff --git a/kornia/filters/dissolving.py b/kornia/filters/dissolving.pyindex f169b7640..215fa8c67 100644--- a/kornia/filters/dissolving.py+++ b/kornia/filters/dissolving.py@@ -221,6 +221,9 @@ class StableDiffusionDissolving(ImageModule):- .. figure:: https://raw.githubusercontent.com/kornia/data/main/dslv-sd-1.5.png- SD XL example image pending β see `#4601 <https://github.com/kornia/kornia/issues/4601>`_.+ Convention:+ See the Convention block on :class:`~kornia.augmentation.RandomDissolving`.+Args:version: the version of the stable diffusion model. Options: "1.4", "1.5", "xl".**kwargs: additional arguments for `.from_pretrained`.diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.pyindex c20c0e168..62ee261f6 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -96,6 +96,15 @@ def gaussian_blur2d(The operator smooths the given torch.Tensor with a gaussian kernel by convolvingit to each channel. It supports batched operation.+ Convention:+ - ``kernel_size`` is ``(kH, kW)`` and ``sigma`` is :math:`(\sigma_y, \sigma_x)`: both give the rows (y)+ first, so ``sigma[0]`` blurs along ``H`` and ``sigma[1]`` along ``W``.+ :ref:`Filtering <filtering-conventions>` maps both pairs onto OpenCV and scipy.+ - The border modes are :func:`~kornia.filters.filter2d`'s; see its Convention block.+ - Known defect: an integer input casts ``sigma`` and the kernel to its dtype, so on the CPU a uint8 image+ comes back as zeros, and a ``sigma`` below 1 truncates to 0 and is rejected as not positive+ (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+Arguments:input: the input torch.Tensor with shape :math:`(B,C,H,W)`.kernel_size: the size of the kernel. Can be an integer or tuple of two integers (height, width).@@ -111,10 +120,11 @@ def gaussian_blur2d(the blurred torch.Tensor with shape :math:`(B, C, H, W)`.Raises:- RuntimeError: if input is not a 4D torch.Tensor.- RuntimeError: if sigma values are not positive.- BaseError: if the ``sigma`` batch is neither 1 nor the input batch.- RuntimeError: if kernel_size is not a positive odd integer.+ ~kornia.core.exceptions.TypeCheckError: if input is not a torch.Tensor.+ ~kornia.core.exceptions.ShapeError: if input is not 4D.+ ~kornia.core.exceptions.BaseError: if sigma values are not positive.+ ~kornia.core.exceptions.BaseError: if the ``sigma`` batch is neither 1 nor the input batch.+ ~kornia.core.exceptions.BaseError: if kernel_size is not a positive odd integer... note::See a working example `here <https://www.kornia.org/tutorials/nbs/gaussian_blur.html>`__.@@ -197,6 +207,9 @@ class GaussianBlur2d(nn.Module):The operator smooths the given torch.Tensor with a gaussian kernel by convolvingit to each channel. It supports batched operation.+ Convention:+ See the Convention block on :func:`~kornia.filters.gaussian_blur2d`.+Arguments:kernel_size: the size of the kernel.sigma: the standard deviation of the kernel.diff --git a/kornia/filters/guided.py b/kornia/filters/guided.pyindex 7b141214e..968dd0a3d 100644--- a/kornia/filters/guided.py+++ b/kornia/filters/guided.py@@ -185,9 +185,19 @@ def guided_blur(The operator is an edge-preserving image smoothing filter. See :cite:`he2010guided`and :cite:`he2015fast` for details. Guidance and input can have different number of channels.+ Convention:+ - ``guidance`` comes first and ``input`` second, the opposite of+ :func:`~kornia.filters.joint_bilateral_blur`.+ - ``kernel_size`` is the whole ``(kH, kW)`` window, ``2 * r + 1`` for the radius ``r`` of+ :cite:`he2010guided`. The window means are :func:`~kornia.filters.box_blur`'s, so the border modes and+ the anchor of an even size follow its Convention block.+ - ``eps`` is added to the local variance of ``guidance``, so it is in squared guidance units: guidance and+ input scaled by ``s``, filtered with ``eps * s**2``, give the result scaled by ``s``.+ :ref:`Filtering <filtering-conventions>` maps the arguments onto OpenCV's ``guidedFilter``.+Arguments:- guidance: the guidance torch.Tensor with shape :math:`(B,C,H,W)`.- input: the input torch.Tensor with shape :math:`(B,C,H,W)`.+ guidance: the guidance torch.Tensor with shape :math:`(B,C_g,H,W)`.+ input: the input torch.Tensor with shape :math:`(B,C_i,H,W)`.kernel_size: the size of the kernel.eps: regularization parameter. Smaller values preserve more edges.border_type: the padding mode to be applied before convolving.@@ -205,7 +215,7 @@ def guided_blur(large windows. Default: FalseReturns:- the blurred torch.Tensor with same shape as `input` :math:`(B, C, H, W)`.+ the blurred torch.Tensor with same shape as `input` :math:`(B, C_i, H, W)`.Raises:TypeCheckError: if ``subsample`` is not an integer (NumPy integers are accepted).@@ -260,6 +270,9 @@ class GuidedBlur(nn.Module):The operator is an edge-preserving image smoothing filter. See :cite:`he2010guided`and :cite:`he2015fast` for details. Guidance and input can have different number of channels.+ Convention:+ See the Convention block on :func:`~kornia.filters.guided_blur`.+Arguments:kernel_size: the size of the kernel.eps: regularization parameter. Smaller values preserve more edges.@@ -285,8 +298,8 @@ class GuidedBlur(nn.Module):BaseError: if ``subsample`` is not positive, or is a ``bool``. Both are raised by the constructor.Shape:- - Input: :math:`(B, C, H, W)`, :math:`(B, C, H, W)`- - Output: :math:`(B, C, H, W)`+ - Input: :math:`(B, C_g, H, W)`, :math:`(B, C_i, H, W)`+ - Output: :math:`(B, C_i, H, W)`Examples:>>> guidance = torch.rand(2, 3, 5, 5)@@ -340,8 +353,8 @@ class GuidedBlur(nn.Module):the width.input: Tensor to filter with shape :math:`(B, C_i, H, W)`, where:math:`C_i` is the number of channels in the signal being- smoothed. Its batch and spatial dimensions must be compatible- with ``guidance``.+ smoothed. Its batch and spatial dimensions must equal those+ of ``guidance``.Returns:Tensor with shape :math:`(B, C_i, H, W)` containing thediff --git a/kornia/filters/median.py b/kornia/filters/median.pyindex 2c26c338a..c0165b734 100644--- a/kornia/filters/median.py+++ b/kornia/filters/median.py@@ -100,6 +100,13 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int, border_.. image:: _static/img/median_blur.png+ Convention:+ - ``kernel_size`` is ``(kH, kW)``, rows first, and both entries are odd, so every window has one middle+ value.+ - A window of more than one pixel that holds a NaN or an infinity returns NaN, even where the median of its+ values is finite; a 1x1 window returns its pixel, infinity included.+ - The border modes are :func:`~kornia.filters.filter2d`'s; see its Convention block.+Args:input: the input image with shape :math:`(B,C,H,W)`.kernel_size: the blurring kernel size. Each entry must be a positive odd integer.@@ -181,6 +188,9 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int, border_class MedianBlur(nn.Module):r"""Blur an image using the median filter.+ Convention:+ See the Convention block on :func:`~kornia.filters.median_blur`.+Args:kernel_size: the blurring kernel size.border_type: the padding mode to be applied before filtering.diff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex 05ec9de3a..57a33becd 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -54,8 +54,11 @@ def _scalar_params_as_tensors(class MotionBlur(nn.Module):r"""Blur 2D images (4D torch.Tensor) using the motion filter.+ Convention:+ See the Convention block on :func:`~kornia.filters.motion_blur`.+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),@@ -123,8 +126,11 @@ class MotionBlur(nn.Module):class MotionBlur3D(nn.Module):r"""Blur 3D volumes (5D torch.Tensor) using the motion filter.+ Convention:+ See the Convention block on :func:`~kornia.filters.motion_blur3d`.+Args:- kernel_size: motion kernel width and height. It should be odd and positive.+ kernel_size: motion kernel width, height and depth, an odd integer of at least 3.angle: Components of one Rodrigues axis-angle vector ``(rx, ry, rz)`` in degrees, not Euler angles; see:func:`~kornia.filters.get_motion_kernel3d`. A scalar sets all three components to the same value;a three-element sequence sets each component, and a tensor must have shape :math:`(B, 3)`.@@ -223,9 +229,14 @@ def motion_blur(.. image:: _static/img/motion_blur.png+ Convention:+ - The kernel is :func:`~kornia.filters.get_motion_kernel2d`'s, correlated with the image by+ :func:`~kornia.filters.filter2d`; their Convention blocks cover ``angle``, ``direction`` (including the+ side on which the streak of a bright point is heaviest), ``mode``, the tensor shapes and the border modes.+Args:input: the input torch.Tensor with shape :math:`(B, C, H, W)`.- 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 (Union[torch.Tensor, float]): angle of the motion blur in degrees (anti-clockwise rotation).If torch.Tensor, it must be :math:`(B,)`.direction : forward/backward direction of the motion blur.@@ -271,9 +282,16 @@ def motion_blur3d() -> torch.Tensor:r"""Perform motion blur on 3D volumes (5D torch.Tensor).+ Convention:+ - The kernel is :func:`~kornia.filters.get_motion_kernel3d`'s, correlated with the volume by+ :func:`~kornia.filters.filter3d`; their Convention blocks cover ``angle``, ``direction``, ``mode`` and the+ border modes. With ``direction=1`` and a zero ``angle`` the streak of a bright voxel is heaviest toward+ increasing ``W``; a positive roll alone turns it toward increasing ``H``, and a positive pitch alone toward+ decreasing ``D``.+Args:input: the input torch.Tensor with shape :math:`(B, C, D, H, W)`.- kernel_size: motion kernel width, height and depth. It should be odd and positive.+ kernel_size: motion kernel width, height and depth, an odd integer of at least 3.angle: ``(yaw, pitch, roll)``, one Rodrigues axis-angle vector ``(rx, ry, rz)`` in degrees, not Eulerangles; see :func:`~kornia.filters.get_motion_kernel3d`. If torch.Tensor, it must be :math:`(B, 3)`.direction: forward/backward direction of the motion blur.diff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.pyindex af2799dd0..36be49caf 100644--- a/kornia/filters/unsharp.py+++ b/kornia/filters/unsharp.py@@ -33,16 +33,23 @@ def unsharp_mask(.. image:: _static/img/unsharp_mask.png+ Convention:+ - The blur in the formula above is :func:`~kornia.filters.gaussian_blur2d` with the same ``kernel_size``,+ ``sigma`` and ``border_type``, and the detail it removes is added back with a fixed gain of 1. See the+ Convention block on :func:`~kornia.filters.gaussian_blur2d` for the argument order.+ - The output is not clamped: next to an edge it overshoots on both sides, so a step from 0 to 1 comes back+ below 0 and above 1. :ref:`Filtering <filtering-conventions>` maps the call onto scikit-image.+Args:input: the input torch.Tensor with shape :math:`(B,C,H,W)`.kernel_size: the size of the kernel.sigma: the standard deviation of the kernel.border_type: the padding mode to be applied before convolving.The expected modes are: ``'constant'``, ``'reflect'``,- ``'replicate'`` or ``'circular'``.+ ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.Returns:- the blurred torch.Tensor with shape :math:`(B,C,H,W)`.+ the sharpened torch.Tensor with shape :math:`(B,C,H,W)`.Examples:>>> input = torch.rand(2, 4, 5, 5)@@ -58,12 +65,15 @@ def unsharp_mask(class UnsharpMask(nn.Module):r"""Create an operator that sharpens image with: out = 2 * image - gaussian_blur2d(image).+ Convention:+ See the Convention block on :func:`~kornia.filters.unsharp_mask`.+Args:kernel_size: the size of the kernel.sigma: the standard deviation of the kernel.border_type: the padding mode to be applied before convolving.The expected modes are: ``'constant'``, ``'reflect'``,- ``'replicate'`` or ``'circular'``.+ ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.Returns:the sharpened torch.Tensor with shape :math:`(B,C,H,W)`.@@ -111,7 +121,7 @@ class UnsharpMask(nn.Module):Returns:Tensor with shape :math:`(B, C, H, W)` containing the sharpened- image. The amount and spatial scale of sharpening are controlled by- the configured Gaussian kernel size, sigma, and border handling.+ image. The spatial scale of sharpening is set by the configured+ Gaussian kernel size and sigma; the amount is fixed."""return unsharp_mask(input, self.kernel_size, self.sigma, self.border_type)diff --git a/tests/filters/test_bilateral.py b/tests/filters/test_bilateral.pyindex 2e02a0a6f..8b0f8f3e6 100644--- a/tests/filters/test_bilateral.py+++ b/tests/filters/test_bilateral.py@@ -15,12 +15,21 @@# limitations under the License.#+import math+import pytestimport torch-from kornia.filters import BilateralBlur, JointBilateralBlur, bilateral_blur, joint_bilateral_blur+from kornia.core.exceptions import BaseError+from kornia.filters import (+ BilateralBlur,+ JointBilateralBlur,+ bilateral_blur,+ gaussian_blur2d,+ joint_bilateral_blur,+)-from testing.base import BaseTester+from testing.base import BaseTester, supports_reflect_padding, supports_replicate_paddingclass TestBilateralBlur(BaseTester):@@ -486,3 +495,148 @@ class TestJointBilateralBlur(BaseTester):out = joint_bilateral_blur(img, guide, kernel_size, sigma_color, sigma_distance)self.assert_close(out, expected)+++class TestConventionsBilateralBlur(BaseTester):+ """Pins for the colour and space parameters of :func:`bilateral_blur` and :func:`joint_bilateral_blur`."""++ @staticmethod+ def _skip_without_reflect_padding(device, dtype):+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")++ def test_convention_bilateral_blur_sigma_color_is_in_input_units(self, device, dtype):+ # sigma_color is compared with differences of input values, not with a normalised range: scaling the image by+ # s needs sigma_color * s for the same (scaled) result. A power of two keeps the rescaling exact in every dtype.+ self._skip_without_reflect_padding(device, dtype)+ torch.manual_seed(0)+ image = torch.rand(2, 3, 9, 13).to(device=device, dtype=dtype)+ for distance in ("l1", "l2"):+ reference = bilateral_blur(image, 3, 0.1, (1.0, 1.5), color_distance_type=distance)+ rescaled = bilateral_blur(16 * image, 3, 16 * 0.1, (1.0, 1.5), color_distance_type=distance)+ self.assert_close(rescaled, 16 * reference)+ # control: the unscaled sigma_color on the rescaled image is a different filter+ unscaled = bilateral_blur(16 * image, 3, 0.1, (1.0, 1.5), color_distance_type=distance)+ assert (unscaled - 16 * reference).abs().max() > 0.1++ @pytest.mark.parametrize("border_type", ["reflect", "replicate", "constant", "circular"])+ def test_convention_bilateral_blur_sigma_space_is_gaussian_blur2d_sigma(self, border_type, device, dtype):+ # sigma_space is gaussian_blur2d's (sigma_y, sigma_x) with the same kernel_size, and border_type pads as it+ # does: once sigma_color dwarfs every intensity difference the colour weights are 1 and the bilateral filter+ # is gaussian_blur2d.+ if border_type == "reflect":+ self._skip_without_reflect_padding(device, dtype)+ if border_type == "replicate" and not supports_replicate_padding(device, dtype):+ pytest.skip(f"this torch build has no replicate padding kernel for {dtype} on {device.type}")+ image = torch.zeros(1, 1, 23, 31, device=device, dtype=dtype)+ image[0, 0, 9, 17] = 1.0+ out = bilateral_blur(image, (15, 21), 1e6, (1.0, 3.0), border_type)+ self.assert_close(out, gaussian_blur2d(image, (15, 21), (1.0, 3.0), border_type))+ # control: the swapped sigma is a different blur of this delta+ assert (out - gaussian_blur2d(image, (15, 21), (3.0, 1.0), border_type)).abs().max() > 0.02++ # A delta one pixel from the top and right edges: the window reaches the padding.+ corner = torch.zeros(1, 1, 9, 12, device=device, dtype=dtype)+ corner[0, 0, 1, 10] = 1.0+ out = bilateral_blur(corner, (5, 7), 1e6, (1.0, 2.0), border_type)+ self.assert_close(out, gaussian_blur2d(corner, (5, 7), (1.0, 2.0), border_type))++ @pytest.mark.parametrize("distance", ["l1", "l2"])+ def test_convention_bilateral_blur_color_weight(self, distance, device, dtype):+ # A neighbour's weight is its spatial Gaussian weight times exp(-d^2 / (2 sigma_color^2)), normalised over the+ # window, with d = sum_c |dI_c| for 'l1' (OpenCV's colour distance) and d^2 = sum_c dI_c^2 for 'l2'.+ # One 1 x 3 window on a two-channel 1 x 3 image: the centre pixel is recomputed here from that formula.+ self._skip_without_reflect_padding(device, dtype)+ rows = [[0.2, 0.2, 0.9], [0.8, 0.8, 0.1]] # the right neighbour differs by (0.7, -0.7), the left by nothing+ image = torch.tensor(rows, device=device, dtype=dtype).view(1, 2, 1, 3)+ sigma_color, sigma_x = 0.8, 1.2++ def centre(dist):+ weights = []+ for col in range(3):+ diff = [row[col] - row[1] for row in rows]+ d2 = sum(abs(v) for v in diff) ** 2 if dist == "l1" else sum(v * v for v in diff)+ weights.append(math.exp(-((col - 1) ** 2) / (2 * sigma_x**2)) * math.exp(-d2 / (2 * sigma_color**2)))+ return [sum(w * v for w, v in zip(weights, row)) / sum(weights) for row in rows]++ # the fixture tells the two distances apart well beyond the half-precision tolerances+ assert max(abs(a - b) for a, b in zip(centre("l1"), centre("l2"))) > 0.05+ out = bilateral_blur(image, (1, 3), sigma_color, (1.0, sigma_x), color_distance_type=distance)+ self.assert_close(out[0, :, 0, 1], torch.tensor(centre(distance), device=device, dtype=dtype))++ def test_convention_joint_bilateral_blur_filters_its_first_argument(self, device, dtype):+ # joint_bilateral_blur(input, guidance, ...) filters input with colour weights taken from guidance -- the+ # guidance second, unlike guided_blur(guidance, input, ...) -- and the guidance may have its own channel+ # count. A flat guidance makes every colour weight 1, so the output is gaussian_blur2d of the input, with a+ # one-channel guidance and with one that has the input's three channels.+ self._skip_without_reflect_padding(device, dtype)+ torch.manual_seed(0)+ image = torch.rand(2, 3, 9, 13).to(device=device, dtype=dtype)+ expected = gaussian_blur2d(image, (3, 5), (1.0, 2.0))+ for guidance_channels in (1, 3):+ flat = torch.full((2, guidance_channels, 9, 13), 0.5, device=device, dtype=dtype)+ for out in (+ joint_bilateral_blur(image, flat, (3, 5), 0.1, (1.0, 2.0)),+ JointBilateralBlur((3, 5), 0.1, (1.0, 2.0))(image, flat),+ ):+ assert out.shape == image.shape+ self.assert_close(out, expected)++ def test_wart_bilateral_blur_integer_image_wraps_its_differences_5155(self, device):+ """bilateral_blur subtracts uint8 values in uint8, so 10 - 250 wraps and blends edges it should keep (#5155)."""+ if device.type not in ("cpu", "mps"):+ pytest.skip("#5155 is pinned on the CPU and MPS only")+ # Columns alternate 10 and 250. A colour sigma of 50 keeps them apart, but the wrapped difference+ # 10 - 250 = 16 (mod 256) makes the 10s look close to the 250s, which come back near 162.+ # Snippet used to generate expected:+ # s = torch.tensor([10, 250], dtype=torch.uint8).repeat(8, 5)[None, None]+ # print(bilateral_blur(s, 3, 50.0, (1.0, 1.0))[0, 0, 3, :4]) # [10.0, 162.3, 10.0, 162.3]+ stripes = torch.tensor([10, 250], device=device, dtype=torch.uint8).repeat(8, 5)[None, None]+ out = bilateral_blur(stripes, 3, 50.0, (1.0, 1.0))+ assert out[0, 0, :, 1::2].max() < 200+ # the same filter on the same values in floating point keeps the stripes+ self.assert_close(bilateral_blur(stripes.float(), 3, 50.0, (1.0, 1.0)), stripes.float(), rtol=0.0, atol=0.01)++ def test_wart_bilateral_blur_wider_sigma_space_promotes_the_output_5521(self, device, dtype):+ """A tensor sigma_space or guidance of a wider dtype promotes the output; sigma_color does not (#5521)."""+ # sigma_space builds the spatial kernel in its own dtype, and the product with the colour kernel promotes.+ # A fix that casts sigma_space to the input's dtype, as gaussian_blur2d casts sigma, fails this pin.+ if device.type == "mps":+ pytest.skip("MPS has no float64")+ if dtype == torch.float64:+ pytest.skip("nothing is wider than a float64 input")+ self._skip_without_reflect_padding(device, dtype)+ image = torch.rand(1, 1, 7, 9, device=device).to(dtype)+ wide_space = torch.full((1, 2), 1.5, device=device, dtype=torch.float64)+ assert bilateral_blur(image, 3, 0.1, wide_space).dtype == torch.float64+ assert joint_bilateral_blur(image, image, 3, 0.1, wide_space).dtype == torch.float64+ assert joint_bilateral_blur(image, image.double(), 3, 0.1, (1.5, 1.5)).dtype == torch.float64+ # control: a wider sigma_color is cast to the input's dtype+ wide_color = torch.tensor([0.1], device=device, dtype=torch.float64)+ assert bilateral_blur(image, 3, wide_color, (1.5, 1.5)).dtype == dtype++ @pytest.mark.parametrize("kernel_size", [4, (3, 4)])+ def test_convention_bilateral_blur_even_kernel_size_is_rejected_up_front_5163(self, kernel_size, device, dtype):+ """The bilateral filters reject an even kernel_size with a kornia error, the modules at construction (#5163)."""+ image = torch.rand(1, 1, 8, 9, device=device, dtype=dtype)+ with pytest.raises(BaseError):+ bilateral_blur(image, kernel_size, 0.1, (1.0, 1.0))+ with pytest.raises(BaseError):+ joint_bilateral_blur(image, image, kernel_size, 0.1, (1.0, 1.0))+ for module in (BilateralBlur, JointBilateralBlur):+ with pytest.raises(BaseError):+ module(kernel_size, 0.1, (1.0, 1.0))++ def test_convention_bilateral_blur_sigma_color_must_be_positive_5169(self, device, dtype):+ """The bilateral filters reject a sigma_color that is not positive, a float or any entry of a tensor (#5169)."""+ image = torch.rand(2, 3, 9, 13, device=device, dtype=dtype)+ for sigma_color in (+ torch.zeros(2, device=device, dtype=dtype),+ torch.tensor([0.1, -0.1], device=device, dtype=dtype),+ 0.0,+ -0.1,+ ):+ with pytest.raises(BaseError):+ bilateral_blur(image, 3, sigma_color, (1.0, 1.0))+ with pytest.raises(BaseError):+ joint_bilateral_blur(image, image, 3, sigma_color, (1.0, 1.0))diff --git a/tests/filters/test_blur.py b/tests/filters/test_blur.pyindex 42788efb0..6488b4609 100644--- a/tests/filters/test_blur.py+++ b/tests/filters/test_blur.py@@ -20,10 +20,10 @@ import importlibimport pytestimport torch-from kornia.filters import BoxBlur, box_blur, filter2d, filter2d_separable+from kornia.filters import BoxBlur, box_blur, filter2d, filter2d_separable, gaussian_blur2d, median_blurfrom kornia.filters.kernels import get_box_kernel1d, get_box_kernel2d-from testing.base import BaseTester+from testing.base import BaseTester, supports_reflect_paddingblur_module = importlib.import_module("kornia.filters.blur")@@ -347,3 +347,62 @@ class TestBoxBlur(BaseTester):box_blur(data, kernel_size, border_type, separable=separable),functional_optimized(data, kernel_size, border_type, separable=separable),)+++class TestConventionsBoxBlur(BaseTester):+ """Pins for the window of :func:`box_blur` and the ``kernel_size`` order the blurs share."""++ @pytest.mark.parametrize(+ "blur",+ [+ pytest.param(box_blur, id="box_blur"),+ pytest.param(lambda image, size: gaussian_blur2d(image, size, (1.5, 1.5)), id="gaussian_blur2d"),+ pytest.param(median_blur, id="median_blur"),+ ],+ )+ def test_convention_blur_kernel_size_is_height_then_width(self, blur, device, dtype):+ # kernel_size = (kH, kW): a (1, 5) window slides along a row and leaves a full-width horizontal bar as it is,+ # while a (5, 1) window spans five rows and spreads the bar (the median erases it). cv2.blur and+ # cv2.GaussianBlur take ksize = (width, height) instead.+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ bar = torch.zeros(1, 1, 7, 10, device=device, dtype=dtype)+ bar[0, 0, 2, :] = 1.0+ self.assert_close(blur(bar, (1, 5)), bar)+ assert (blur(bar, (5, 1)) - bar).abs().max() > 0.5++ # Relabelling check: transpose the image, and the two sizes swap roles.+ column = bar.transpose(-1, -2).contiguous()+ self.assert_close(blur(column, (5, 1)), column)+ assert (blur(column, (1, 5)) - column).abs().max() > 0.5++ @pytest.mark.parametrize("separable", [True, False])+ def test_convention_box_blur_even_kernel_is_centred_at_k_minus_1_over_2(self, separable, device, dtype):+ # An even extent k averages [i - (k - 1) // 2, i + k // 2] with weight 1 / (kH * kW) and keeps the image size:+ # the window's centre is (k - 1) // 2, as in filter2d and torch's F.conv2d(padding="same"). cv2.blur's default+ # anchor and scipy's uniform_filter(origin=0) centre an even window at k // 2 instead.+ # Snippet used to generate expected:+ # x = torch.zeros(1, 1, 9, 13); x[0, 0, 3, 8] = 1+ # nz = box_blur(x, (2, 4))[0, 0].nonzero(); print(nz[:, 0].unique(), nz[:, 1].unique())+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ image = torch.zeros(1, 1, 9, 13, device=device, dtype=dtype)+ image[0, 0, 3, 8] = 1.0+ # the (2, 4) / (4, 2) pair is the relabelling check+ for kernel_size, rows, cols in (((2, 4), [2, 3], [6, 7, 8, 9]), ((4, 2), [1, 2, 3, 4], [7, 8])):+ out = box_blur(image, kernel_size, separable=separable)+ assert out.shape == image.shape+ lit = out[0, 0].nonzero()+ assert lit[:, 0].unique().tolist() == rows+ assert lit[:, 1].unique().tolist() == cols+ self.assert_close(out[out != 0], torch.full((8,), 1 / 8, device=device, dtype=dtype))++ def test_wart_box_blur_integer_image_blurs_to_zero_5155(self, device):+ """box_blur builds its kernel in an integer input's dtype, so a uint8 image blurs to zero (#5155)."""+ if device.type != "cpu":+ pytest.skip("#5155 is pinned on the CPU; MPS raises for an integer convolution instead")+ image = torch.full((1, 1, 5, 7), 100, device=device, dtype=torch.uint8)+ for separable in (True, False):+ assert box_blur(image, (3, 3), separable=separable).eq(0).all()+ # the same blur of the same values in floating point keeps the constant image+ self.assert_close(box_blur(image.float(), (3, 3)), image.float())diff --git a/tests/filters/test_blur_pool.py b/tests/filters/test_blur_pool.pyindex 029c70ae9..6d80de5e4 100644--- a/tests/filters/test_blur_pool.py+++ b/tests/filters/test_blur_pool.py@@ -21,6 +21,7 @@ import warningsimport numpy as npimport pytestimport torch+import torch.nn.functional as Ffrom kornia.core.exceptions import BaseErrorfrom kornia.filters import (@@ -386,3 +387,164 @@ class TestEdgeAwareBlurPool(BaseTester):expected = _zero_padded_reference(padded, kernel_size, 1)[..., pad:-pad, pad:-pad]actual = edge_aware_blur_pool2d(data.to(device=device, dtype=dtype), kernel_size, edge_threshold=1e6)self.assert_close(actual, expected.to(device=device, dtype=dtype))+++class TestConventionsBlurPool(BaseTester):+ """Pins for the sampling, padding and anchor of the blur pools, and for their filed defects."""++ def test_convention_blur_pool2d_odd_kernel_samples_every_stride_th_pixel_from_0(self, device, dtype):+ # For an odd kernel, blur_pool2d zero-pads (k - 1) // 2 per side, blurs, and keeps rows and columns 0, s, 2s,+ # ... of the stride-1 blur: the output is ceil(H / s) x ceil(W / s). pyrdown instead resamples between pixels+ # to floor(H / 2) x floor(W / 2).+ torch.manual_seed(0)+ image = torch.rand(1, 2, 7, 10).to(device=device, dtype=dtype)+ for kernel_size in (3, 5):+ dense = blur_pool2d(image, kernel_size, stride=1)+ assert dense.shape == image.shape+ for stride in (2, 3):+ out = blur_pool2d(image, kernel_size, stride=stride)+ assert out.shape[-2:] == (math.ceil(7 / stride), math.ceil(10 / stride))+ self.assert_close(out, dense[..., ::stride, ::stride])+ self.assert_close(BlurPool2D(kernel_size, stride=stride)(image), out)++ def test_convention_blur_pool2d_zero_pads_the_border(self, device, dtype):+ # blur_pool2d pads with zeros, so a constant map darkens along its border: each padded side drops the outer+ # quarter of the binomial [1, 2, 1] / 4 weights. antialiased-cnns' BlurPool reflect-pads by default and+ # matches kornia with pad_type='zero'.+ # Snippet used to generate expected:+ # out = blur_pool2d(torch.ones(1, 1, 7, 10), 3); print(out[0, 0, 0], out[0, 0, :, 0])+ ones = torch.ones(1, 1, 7, 10, device=device, dtype=dtype)+ out = blur_pool2d(ones, 3)+ self.assert_close(out[0, 0, 0], torch.tensor([0.5625, 0.75, 0.75, 0.75, 0.75], device=device, dtype=dtype))+ self.assert_close(out[0, 0, :, 0], torch.tensor([0.5625, 0.75, 0.75, 0.5625], device=device, dtype=dtype))+ self.assert_close(out[0, 0, 1:-1, 1:], torch.ones(2, 4, device=device, dtype=dtype))++ def test_convention_blur_pool2d_even_kernel_is_anchored_at_k_minus_1_over_2(self, device, dtype):+ # An even kernel's window covers [i - (k - 1) // 2, i + k // 2] -- the filters convention (filter2d, box_blur)+ # and antialiased-cnns' anchor -- so a delta off the centre lights the rows and columns below.+ # Snippet used to generate expected:+ # x = torch.zeros(1, 1, 7, 9); x[0, 0, 3, 4] = 1+ # nz = blur_pool2d(x, k, stride=1)[0, 0].nonzero(); print(nz[:, 0].unique(), nz[:, 1].unique())+ image = torch.zeros(1, 1, 7, 9, device=device, dtype=dtype)+ image[0, 0, 3, 4] = 1.0+ for kernel_size, rows, cols in (+ (2, [2, 3], [3, 4]),+ (3, [2, 3, 4], [3, 4, 5]),+ (4, [1, 2, 3, 4], [2, 3, 4, 5]),+ ):+ lit = blur_pool2d(image, kernel_size, stride=1)[0, 0].nonzero()+ assert lit[:, 0].unique().tolist() == rows+ assert lit[:, 1].unique().tolist() == cols++ def test_convention_max_blur_pool2d_is_a_stride_one_max_pool_then_blur_pool2d(self, device, dtype):+ # max_blur_pool2d(x, k, stride, max_pool_size) = blur_pool2d(F.max_pool2d(x, max_pool_size, stride=1), k,+ # stride): the max pool never strides, so the output is ceil((H - max_pool_size + 1) / stride), not H / stride.+ torch.manual_seed(0)+ image = torch.rand(1, 2, 7, 10).to(device=device, dtype=dtype)+ for kernel_size, max_pool_size, size in ((3, 2, (3, 5)), (3, 3, (3, 4)), (5, 2, (3, 5)), (4, 2, (3, 5))):+ out = max_blur_pool2d(image, kernel_size, stride=2, max_pool_size=max_pool_size)+ assert out.shape[-2:] == size+ self.assert_close(out, blur_pool2d(F.max_pool2d(image, max_pool_size, stride=1), kernel_size, stride=2))+ self.assert_close(MaxBlurPool2D(kernel_size, 2, max_pool_size)(image), out)++ def test_convention_edge_aware_blur_pool2d_edge_is_an_intensity_ratio(self, device, dtype):+ # A pixel keeps its value where the channel mean of log2(I(x + 2) / I(x - 2)), along x or y, exceeds+ # log2(edge_threshold) in magnitude (dilated by edge_dilation_kernel_size), and is blurred elsewhere: the+ # threshold is a ratio of intensities 4 px apart, so the decision is scale-invariant for intensities well+ # above epsilon. The comparison is strict. Positive intensities are assumed: where input + epsilon is negative+ # the log is NaN, which never counts as an edge.+ # The default edge_threshold is 1.25, and the output keeps the input size. On a vertical step between+ # columns 5 and 6 the blur would move those two columns by a quarter of the step.+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")++ def moved(step, out):+ return (out[..., 5:7] - step[..., 5:7]).abs().max()++ for low, high, kept in ((1.0, 1.2, False), (1.0, 1.3, True), (10.0, 12.0, False), (10.0, 13.0, True)):+ step = torch.full((1, 1, 9, 12), low, device=device, dtype=dtype)+ step[..., 6:] = high+ out = edge_aware_blur_pool2d(step, 3)+ assert out.shape == step.shape+ if kept:+ self.assert_close(out[..., 5:7], step[..., 5:7])+ else:+ assert moved(step, out) > (high - low) / 8+ # a ratio of 1.3 in one channel of two averages below the threshold+ step = torch.ones(1, 2, 9, 12, device=device, dtype=dtype)+ step[:, 0, :, 6:] = 1.3+ assert moved(step, edge_aware_blur_pool2d(step, 3)) > 0.3 / 8+ # a negative step with the same ratio is blurred, and no NaN reaches the output+ step = torch.full((1, 1, 9, 12), -1.0, device=device, dtype=dtype)+ step[..., 6:] = -1.3+ out = edge_aware_blur_pool2d(step, 3)+ assert moved(step, out) > 0.3 / 8+ assert not out.isnan().any()+ # the log is taken of input + epsilon, so a negative step above -epsilon is an edge: with epsilon=1 a+ # -0.5 -> -0.125 step compares 0.5 with 0.875, a log2 ratio of 0.81 > log2(1.25)+ step = torch.full((1, 1, 9, 12), -0.5, device=device, dtype=dtype)+ step[..., 6:] = -0.125+ self.assert_close(edge_aware_blur_pool2d(step, 3, epsilon=1.0)[..., 5:7], step[..., 5:7])+ # strict: with epsilon=0 a 1 -> 2 step has a log2 ratio of exactly 1 = log2(2), which is not an edge at+ # edge_threshold=2 and is one just below it+ step = torch.ones(1, 1, 9, 12, device=device, dtype=dtype)+ step[..., 6:] = 2.0+ assert moved(step, edge_aware_blur_pool2d(step, 3, edge_threshold=2.0, epsilon=0.0)) > 1 / 8+ self.assert_close(edge_aware_blur_pool2d(step, 3, edge_threshold=1.99, epsilon=0.0)[..., 5:7], step[..., 5:7])++ def test_convention_edge_aware_blur_pool2d_compares_pixels_two_apart_and_dilates_the_edges(self, device, dtype):+ # The edge test at x compares x - 2 with x + 2 (and y - 2 with y + 2), and edge_dilation_kernel_size widens+ # the kept band. Period-2 stripes, 1.0 | 1.15, scaled by 1.5 from column 8 on: pixels two apart match away+ # from the step, so only columns 6..9 see the 1.5 ratio, and the stripes make every blurred column differ+ # from the input. Transposing the image moves the band to rows 6..9.+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ step = (1.0 + 0.15 * (torch.arange(16) % 2)).expand(1, 1, 9, 16).to(device=device, dtype=dtype).contiguous()+ step[..., 8:] *= 1.5+ for dilation, kept in ((1, [6, 7, 8, 9]), (3, [5, 6, 7, 8, 9, 10])):+ out = edge_aware_blur_pool2d(step, 3, edge_dilation_kernel_size=dilation)+ assert [c for c in range(16) if torch.equal(out[..., c], step[..., c])] == kept+ transposed = step.transpose(-1, -2).contiguous()+ out = edge_aware_blur_pool2d(transposed, 3, edge_dilation_kernel_size=1)+ assert [r for r in range(16) if torch.equal(out[..., r, :], transposed[..., r, :])] == [6, 7, 8, 9]++ def test_convention_blur_pool2d_even_kernel_keeps_ceil_h_over_stride_5166(self, device, dtype):+ """An even kernel pads (k - 1) // 2 before and k // 2 after, so the blur pools keep ceil(H / stride) (#5166)."""+ torch.manual_seed(0)+ image = torch.rand(1, 2, 7, 10).to(device=device, dtype=dtype)+ for kernel_size in (2, 4):+ dense = blur_pool2d(image, kernel_size, stride=1)+ assert dense.shape == image.shape+ assert BlurPool2D(kernel_size, stride=1)(image).shape == image.shape+ assert max_blur_pool2d(image, kernel_size, stride=1, max_pool_size=1).shape == image.shape+ for stride in (2, 3):+ out = blur_pool2d(image, kernel_size, stride=stride)+ assert out.shape[-2:] == (math.ceil(7 / stride), math.ceil(10 / stride))+ self.assert_close(out, dense[..., ::stride, ::stride])++ @pytest.mark.parametrize("kernel_size", [2, 4])+ def test_convention_edge_aware_blur_pool2d_even_kernel_size_keeps_the_input_shape_5163(+ self, kernel_size, device, dtype+ ):+ """edge_aware_blur_pool2d blurs with an even kernel_size as blur_pool2d does and keeps the shape (#5163)."""+ # With edge_threshold=1e6 no pixel is an edge, so the output is the stride-1 blur_pool2d of the input+ # reflect-padded by 2, cropped back: an even kernel is anchored at (k - 1) // 2 there too.+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ torch.manual_seed(0)+ image = torch.rand(1, 1, 8, 9).to(device=device, dtype=dtype) + 0.1+ out = edge_aware_blur_pool2d(image, kernel_size, edge_threshold=1e6)+ assert out.shape == image.shape+ self.assert_close(EdgeAwareBlurPool2D(kernel_size, edge_threshold=1e6)(image), out)+ padded = F.pad(image.cpu().double(), (2, 2, 2, 2), mode="reflect")+ expected = blur_pool2d(padded, kernel_size, stride=1)[..., 2:-2, 2:-2]+ self.assert_close(out, expected.to(device=device, dtype=dtype))++ def test_convention_edge_aware_blur_pool2d_keeps_a_constant_image_at_any_kernel_size_5228(self, device, dtype):+ """edge_aware_blur_pool2d reflects the border as far as its kernel reaches: a constant image stays (#5228)."""+ # A 7-tap binomial reaches 3 px past the border and a 15-tap one 7 px, past the 2 px the edge test reads.+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ ones = torch.ones(1, 1, 15, 18, device=device, dtype=dtype)+ for kernel_size in (3, 5, 7, 9, 15):+ self.assert_close(edge_aware_blur_pool2d(ones, kernel_size), ones)diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.pyindex e60581143..7d8c0757e 100644--- a/tests/filters/test_gaussian.py+++ b/tests/filters/test_gaussian.py@@ -28,6 +28,7 @@ from kornia.core._compat import torch_version_ge, torch_version_ltfrom kornia.core.exceptions import BaseErrorfrom kornia.filters import (GaussianBlur2d,+ filter2d,gaussian,gaussian_blur2d,get_gaussian_discrete_kernel1d,@@ -38,7 +39,7 @@ from kornia.filters import ()from kornia.filters.kernels import gaussian_discrete, gaussian_discrete_erf-from testing.base import BaseTester, assert_close+from testing.base import BaseTester, assert_close, supports_reflect_padding, supports_replicate_padding@pytest.mark.parametrize(@@ -690,3 +691,107 @@ class TestGaussianBlur2d(BaseTester):sample = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)output = gaussian_blur2d(sample, (3, 3), (1.5, 1.5))assert output.device.type == sample.device.type+++class TestConventionsGaussianBlur(BaseTester):+ """Pins for the axis order, the tensor sigma and the integer-input behaviour of :func:`gaussian_blur2d`."""++ @staticmethod+ def _spread(response):+ # Row and column variance of one (H, W) response, as a distribution over its pixels, in float64 on the CPU.+ weights = response.detach().cpu().double()+ weights = weights / weights.sum()+ rows = torch.arange(weights.shape[0], dtype=torch.float64)+ cols = torch.arange(weights.shape[1], dtype=torch.float64)+ row_mass, col_mass = weights.sum(1), weights.sum(0)+ row_mean, col_mean = (row_mass * rows).sum(), (col_mass * cols).sum()+ return float((row_mass * (rows - row_mean) ** 2).sum()), float((col_mass * (cols - col_mean) ** 2).sum())++ @pytest.mark.parametrize(+ "separable, shape",+ [+ pytest.param(True, (1, 1, 23, 31), id="separable"),+ pytest.param(False, (1, 1, 23, 31), id="dense"),+ # large enough for the CPU weighted-slice path of float32 / float64 images+ pytest.param(True, (1, 2, 257, 301), id="sliced"),+ ],+ )+ def test_convention_gaussian_blur2d_sigma_order_is_y_x(self, separable, shape, device, dtype):+ # sigma = (sigma_y, sigma_x), in the order of kernel_size = (kH, kW): sigma[0] spreads a delta along the rows+ # and sigma[1] along the columns. OpenCV's GaussianBlur takes (sigmaX, sigmaY) instead.+ # Snippet used to generate expected (21 taps truncate sigma = 3 to a variance of 8.947):+ # x = torch.zeros(1, 1, 23, 31, dtype=torch.float64); x[0, 0, 9, 17] = 1+ # out = gaussian_blur2d(x, (15, 21), (1.0, 3.0)) # row variance 1.000, column variance 8.947+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ image = torch.zeros(shape, device=device, dtype=dtype)+ image[..., 9, 17] = 1.0+ out = gaussian_blur2d(image, (15, 21), (1.0, 3.0), separable=separable)+ var_y, var_x = self._spread(out[0, 0])+ assert abs(var_y - 1.0) < 0.01+ assert abs(var_x - 8.947) < 0.02++ # Relabelling check: transpose the image and swap both pairs, and the output is the transpose.+ transposed = gaussian_blur2d(image.transpose(-1, -2).contiguous(), (21, 15), (3.0, 1.0), separable=separable)+ self.assert_close(transposed.transpose(-1, -2), out)++ def test_convention_gaussian_blur2d_tensor_sigma_is_one_row_per_sample(self, device, dtype):+ # A tensor sigma is (B, 2): row b is (sigma_y, sigma_x) of sample b, and a (1, 2) row is shared by the batch.+ # Snippet used to generate expected (15 taps truncate sigma = 3 to 8.214, 21 taps to 8.947):+ # x = torch.zeros(2, 1, 23, 31, dtype=torch.float64); x[:, 0, 9, 17] = 1+ # gaussian_blur2d(x, (15, 21), torch.tensor([[1.0, 3.0], [3.0, 1.0]], dtype=torch.float64))+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ image = torch.zeros(2, 1, 23, 31, device=device, dtype=dtype)+ image[:, 0, 9, 17] = 1.0+ sigma = torch.tensor([[1.0, 3.0], [3.0, 1.0]], device=device, dtype=dtype)+ out = gaussian_blur2d(image, (15, 21), sigma)+ for sample, (expected_y, expected_x) in ((0, (1.0, 8.947)), (1, (8.214, 1.0))):+ var_y, var_x = self._spread(out[sample, 0])+ assert abs(var_y - expected_y) < 0.02+ assert abs(var_x - expected_x) < 0.02++ shared = gaussian_blur2d(image, (15, 21), sigma[:1])+ self.assert_close(shared[0], out[0])+ self.assert_close(shared[1], out[0])++ @pytest.mark.parametrize("border_type", ["reflect", "replicate", "constant", "circular"])+ def test_convention_gaussian_blur2d_border_type_is_filter2d_s_on_every_path(self, border_type, device, dtype):+ # border_type pads as filter2d does, on every implementation: the separable pass, the dense kernel and, for a+ # large float32 / float64 CPU image, the weighted-slice path. The delta-free random image reaches the border.+ if border_type == "reflect" and not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ if border_type == "replicate" and not supports_replicate_padding(device, dtype):+ pytest.skip(f"this torch build has no replicate padding kernel for {dtype} on {device.type}")+ kernel = get_gaussian_kernel2d((5, 7), (1.0, 2.0), dtype=torch.float64).to(dtype)+ torch.manual_seed(0)+ for shape in ((1, 2, 23, 31), (1, 2, 257, 301)):+ image = torch.rand(shape).to(device=device, dtype=dtype)+ expected = filter2d(image, kernel, border_type)+ for separable in (True, False):+ self.assert_close(gaussian_blur2d(image, (5, 7), (1.0, 2.0), border_type, separable), expected)++ def test_wart_gaussian_blur2d_integer_image_blurs_to_zero_5155(self, device):+ """gaussian_blur2d casts sigma and the kernel to an integer dtype: a uint8 image blurs to zero (#5155)."""+ if device.type != "cpu":+ pytest.skip("#5155 is pinned on the CPU; MPS raises for an integer convolution instead")+ image = torch.full((1, 1, 5, 7), 100, device=device, dtype=torch.uint8)+ for separable in (True, False):+ assert gaussian_blur2d(image, (3, 3), (1.0, 1.0), separable=separable).eq(0).all()+ # a sigma below 1 truncates to 0 in uint8 and is then rejected as not positive+ with pytest.raises(BaseError):+ gaussian_blur2d(image, (3, 3), (0.5, 0.5))+ # the same blur of the same values in floating point keeps the constant image+ self.assert_close(gaussian_blur2d(image.float(), (3, 3), (1.0, 1.0)), image.float())++ def test_convention_gaussian_blur2d_sigma_batch_is_one_or_the_input_batch_5169(self, device, dtype):+ """gaussian_blur2d rejects a tensor sigma whose batch is neither 1 nor B, on both paths (#5169)."""+ torch.manual_seed(0)+ image = torch.rand(4, 3, 9, 13).to(device=device, dtype=dtype)+ two_rows = torch.tensor([[0.8, 0.8], [3.0, 3.0]], device=device, dtype=dtype)+ for separable in (True, False):+ # a batch of 2 is rejected for B = 4 although it divides it, and a batch of 3 for B = 2+ with pytest.raises(BaseError, match="batch"):+ gaussian_blur2d(image, 5, two_rows, separable=separable)+ with pytest.raises(BaseError, match="batch"):+ gaussian_blur2d(image[:2], 3, torch.ones(3, 2, device=device, dtype=dtype), separable=separable)diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.pyindex 2cfd4cb3b..19d7cb34b 100644--- a/tests/filters/test_guided.py+++ b/tests/filters/test_guided.py@@ -701,3 +701,55 @@ class TestGuidedBlur(BaseTester):op_optimized = torch_optimizer(op)self.assert_close(op(guide, data), op_optimized(guide, data))+++class TestConventionsGuidedBlur(BaseTester):+ """Pins for the argument order, the window and the ``eps`` units of :func:`guided_blur`."""++ @staticmethod+ def _skip_without_reflect_padding(device, dtype):+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")++ @pytest.mark.parametrize("guidance_channels", [1, 3])+ def test_convention_guided_blur_eps_is_in_squared_guidance_units(self, guidance_channels, device, dtype):+ # eps regularises the local variance of the guidance, so it is in squared guidance units: scaling guidance and+ # input by s needs eps * s**2 for the same (scaled) result. OpenCV's ximgproc.guidedFilter eps is the same+ # quantity. A power of two keeps the rescaling exact in every dtype.+ self._skip_without_reflect_padding(device, dtype)+ torch.manual_seed(0)+ guidance = torch.rand(2, guidance_channels, 9, 13).to(device=device, dtype=dtype)+ image = torch.rand(2, 2, 9, 13).to(device=device, dtype=dtype)+ reference = guided_blur(guidance, image, 5, 0.01)+ self.assert_close(guided_blur(16 * guidance, 16 * image, 5, 0.01 * 16**2), 16 * reference)+ # control: eps scaled like the intensities, not like their square, is a different filter+ assert (guided_blur(16 * guidance, 16 * image, 5, 0.01 * 16) - 16 * reference).abs().max() > 0.1++ def test_convention_guided_blur_guidance_first_and_kernel_size_is_the_full_window(self, device, dtype):+ # guided_blur(guidance, input, kernel_size, eps) takes the guidance first, unlike joint_bilateral_blur(input,+ # guidance, ...), and kernel_size = (kH, kW) is the whole box window, 2r + 1 for the radius r of He et al. and+ # of OpenCV's ximgproc.guidedFilter. With a flat guidance the local linear model has slope 0 and the filter is+ # the mean of the local means: box_blur of box_blur of the input, which keeps its own channel count.+ self._skip_without_reflect_padding(device, dtype)+ torch.manual_seed(0)+ image = torch.rand(2, 2, 9, 13).to(device=device, dtype=dtype)+ flat = torch.full((2, 1, 9, 13), 0.5, device=device, dtype=dtype)+ out = guided_blur(flat, image, (3, 5), 0.01)+ assert out.shape == image.shape+ self.assert_close(out, box_blur(box_blur(image, (3, 5)), (3, 5)))+ self.assert_close(GuidedBlur((3, 5), 0.01)(flat, image), out)+ # controls: the window read as (kW, kH), or kernel_size read as radii (7 x 11 windows), is another filter+ assert (out - box_blur(box_blur(image, (5, 3)), (5, 3))).abs().max() > 0.05+ assert (out - box_blur(box_blur(image, (7, 11)), (7, 11))).abs().max() > 0.05++ @pytest.mark.parametrize("guidance_channels", [1, 3])+ def test_convention_guided_blur_subsample_takes_any_size_5167(self, guidance_channels, device, dtype):+ """guided_blur(subsample=s) filters an image whose H and W are not multiples of s, at the input size (#5167)."""+ self._skip_without_reflect_padding(device, dtype)+ torch.manual_seed(0)+ guidance = torch.rand(1, guidance_channels, 9, 13).to(device=device, dtype=dtype)+ image = torch.rand(1, 2, 9, 13).to(device=device, dtype=dtype)+ out = guided_blur(guidance, image, 5, 0.01, subsample=2)+ assert out.shape == image.shape+ assert out.isfinite().all()+ self.assert_close(GuidedBlur(5, 0.01, subsample=2)(guidance, image), out)diff --git a/tests/filters/test_median.py b/tests/filters/test_median.pyindex 559b1cb27..3f45d7361 100644--- a/tests/filters/test_median.py+++ b/tests/filters/test_median.py@@ -25,7 +25,7 @@ from kornia.core.exceptions import BaseErrorfrom kornia.filters import MedianBlur, median_blurfrom kornia.filters.kernels import get_binary_kernel2d-from testing.base import BaseTester+from testing.base import BaseTester, supports_reflect_paddingmedian_module = importlib.import_module("kornia.filters.median")@@ -355,3 +355,51 @@ class TestMedianBlur(BaseTester):expected = op(data)self.assert_close(actual.isnan(), expected.isnan())self.assert_close(actual.nan_to_num(), expected.nan_to_num())+++class TestConventionsMedianBlur(BaseTester):+ """Pins for the border of :func:`median_blur`."""++ # Without a gradient a square 3x3 or 5x5 window on the CPU runs the selection network; with one, the+ # convolution + median path. Both pad as border_type says.+ @pytest.mark.parametrize("requires_grad", [False, True], ids=["selection_network", "conv_median"])+ def test_convention_median_blur_default_border_keeps_a_constant_image_4670(self, requires_grad, device, dtype):+ """median_blur reflects the border by default, so a constant image keeps its corners (#4670)."""+ # border_type='constant' takes a border median over zeros as well: a 3x3 corner window holds 4 image pixels+ # and 5 zeros, so its median is 0; a 5x5 window zeroes a triangle of 3 pixels at each corner.+ # Snippet used to generate expected:+ # image = torch.full((1, 1, 11, 13), 0.8)+ # for k in (3, 5): print((median_blur(image, k, "constant") != image).sum()) # 4, 12+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ image = torch.full((1, 1, 11, 13), 0.8, device=device, dtype=dtype).requires_grad_(requires_grad)+ for kernel_size, changed in ((3, 4), (5, 12)):+ self.assert_close(median_blur(image, kernel_size).detach(), image.detach())+ zero_padded = median_blur(image, kernel_size, border_type="constant").detach()+ assert zero_padded[0, 0, 0, 0] == 0 and zero_padded[0, 0, -1, -1] == 0+ assert int((zero_padded != image.detach()).sum()) == changed+ # the default is 'reflect', not just a mode that keeps a constant+ torch.manual_seed(0)+ noisy = torch.rand(1, 1, 11, 13).to(device=device, dtype=dtype).requires_grad_(requires_grad)+ for kernel_size in (3, 5):+ default = median_blur(noisy, kernel_size).detach()+ self.assert_close(default, median_blur(noisy, kernel_size, border_type="reflect").detach())+ assert not torch.equal(default, median_blur(noisy, kernel_size, border_type="replicate").detach())++ @pytest.mark.parametrize("requires_grad", [False, True], ids=["selection_network", "conv_median"])+ @pytest.mark.parametrize("invalid", [float("nan"), float("inf")])+ def test_convention_median_blur_non_finite_window_is_nan(self, invalid, requires_grad, device, dtype):+ # Any window of more than one pixel that reaches the non-finite pixel is NaN, even when its other values are+ # all 0.5; a 1x1 window returns the pixel itself.+ image = torch.full((1, 1, 9, 11), 0.5, device=device, dtype=dtype)+ image[0, 0, 4, 5] = invalid+ image.requires_grad_(requires_grad)+ for kernel_size in (3, 5, 7, (1, 3), (3, 1)):+ ky, kx = (kernel_size, kernel_size) if isinstance(kernel_size, int) else kernel_size+ expected = torch.zeros(1, 1, 9, 11, dtype=torch.bool, device=device)+ expected[..., 4 - ky // 2 : 5 + ky // 2, 5 - kx // 2 : 6 + kx // 2] = True+ assert torch.equal(median_blur(image, kernel_size, "replicate").detach().isnan(), expected)+ for kernel_size in (1, (1, 1)):+ out = median_blur(image, kernel_size).detach()+ assert torch.equal(out.isnan(), image.detach().isnan())+ self.assert_close(out.nan_to_num(), image.detach().nan_to_num())diff --git a/tests/filters/test_motion.py b/tests/filters/test_motion.pyindex 0f63bd066..d780089cb 100644--- a/tests/filters/test_motion.py+++ b/tests/filters/test_motion.py@@ -37,6 +37,7 @@ from kornia.filters import (from testing.base import (BaseTester,supports_arange,+ supports_bilinear_2d_grid_sample,supports_bilinear_3d_grid_sample,supports_nearest_2d_grid_sample,supports_nearest_3d_grid_sample,@@ -581,3 +582,166 @@ class TestMotionBlur3D(BaseTester):self.assert_close(MotionBlur3D(*params)(volume), from_function)# the shared default is "replicate"self.assert_close(from_function, motion_blur3d(volume, *params, border_type="replicate"))+++class TestConventionsMotionBlur(BaseTester):+ """Pins for the angle and direction of the motion blurs, and for their filed defects."""++ @staticmethod+ def _heaviest_offset(response, centre):+ # Offset of the heaviest pixel (or voxel) of a delta's response from the delta, in (..., row, column) order.+ flat = int(response.detach().cpu().float().argmax())+ index = []+ for size in reversed(response.shape):+ index.append(flat % size)+ flat //= size+ return tuple(i - c for i, c in zip(reversed(index), centre))++ @staticmethod+ def _skip_without_default_border(device, dtype, volumetric):+ # The default border pads with reflect (2-D) or replicate (3-D), which some torch builds lack for half dtypes.+ if volumetric and not supports_replicate_padding_3d(device, dtype):+ pytest.skip(f"this torch build has no 3D replicate padding kernel for {dtype} on {device.type}")+ if not volumetric and not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")++ def test_convention_motion_blur_angle_is_counterclockwise_as_displayed(self, device, dtype):+ # angle is in degrees and turns the streak counter-clockwise as the image is displayed (row 0 on top), as+ # rotate() does: with direction=1 a point's streak is heaviest 2 px right of it at angle 0 and 2 px above+ # it (row - 2) at angle 90.+ self._skip_without_default_border(device, dtype, False)+ image = torch.zeros(1, 1, 9, 12, device=device, dtype=dtype)+ image[0, 0, 3, 7] = 1.0+ at_0 = motion_blur(image, 5, 0.0, 1.0)+ at_90 = motion_blur(image, 5, 90.0, 1.0)+ assert self._heaviest_offset(at_0[0, 0], (3, 7)) == (0, 2)+ assert at_0[0, 0].nonzero()[:, 0].unique().tolist() == [3]+ assert self._heaviest_offset(at_90[0, 0], (3, 7)) == (-2, 0)+ assert at_90[0, 0].nonzero()[:, 1].unique().tolist() == [7]++ # Relabelling check: a transpose mirrors the image and reverses the sense of rotation, so the transposed+ # response at angle 0 is the transposed image's response at angle -90, not at +90.+ transposed = image.transpose(-1, -2).contiguous()+ self.assert_close(motion_blur(transposed, 5, -90.0, 1.0), at_0.transpose(-1, -2))+ assert (motion_blur(transposed, 5, 90.0, 1.0) - at_0.transpose(-1, -2)).abs().max() > 0.3++ def test_convention_motion_blur_direction_weights_the_streak_linearly(self, device, dtype):+ # direction, clamped to [-1, 1], tilts the weights linearly along the streak: at angle 0 a point's streak+ # carries 0.1, 0.2, 0.3, 0.4 from 1 px left to 2 px right of it for +1 (heaviest ahead, at +x), the mirror+ # image for -1, and 0.2 on each of 5 pixels for 0.+ # Snippet used to generate expected:+ # x = torch.zeros(1, 1, 9, 12); x[0, 0, 3, 7] = 1; print(motion_blur(x, 5, 0.0, d)[0, 0, 3, 5:10])+ self._skip_without_default_border(device, dtype, False)+ image = torch.zeros(1, 1, 9, 12, device=device, dtype=dtype)+ image[0, 0, 3, 7] = 1.0+ forward, backward, even = [0.0, 0.1, 0.2, 0.3, 0.4], [0.4, 0.3, 0.2, 0.1, 0.0], [0.2] * 5+ for direction, expected in ((1.0, forward), (-1.0, backward), (0.0, even), (5.0, forward), (-3.0, backward)):+ out = motion_blur(image, 5, 0.0, direction)+ assert out[0, 0].nonzero()[:, 0].unique().tolist() == [3]+ self.assert_close(out[0, 0, 3, 5:10], torch.tensor(expected, device=device, dtype=dtype))++ def test_convention_motion_blur3d_positive_roll_turns_x_toward_y(self, device, dtype):+ # angle = (yaw, pitch, roll) is one axis-angle vector (rx, ry, rz) in degrees, and the streak starts along +x.+ # Each case sets one component, a turn about that axis. A positive roll turns +x toward +y: clockwise as+ # displayed, the opposite sense to motion_blur's angle. A positive pitch turns it toward -z, and yaw, a turn+ # about the streak's own axis, leaves it along +x.+ # Snippet used to generate expected (k = 3, direction = 1; the heaviest voxel's (depth, row, column) offset):+ # v = torch.zeros(1, 1, 7, 9, 11); v[0, 0, 3, 5, 4] = 1; out = motion_blur3d(v, 3, angle, 1.0)+ self._skip_without_default_border(device, dtype, True)+ volume = torch.zeros(1, 1, 7, 9, 11, device=device, dtype=dtype)+ volume[0, 0, 3, 5, 4] = 1.0+ for angle, offset in (+ ((0.0, 0.0, 0.0), (0, 0, 1)),+ ((0.0, 0.0, 90.0), (0, 1, 0)),+ ((0.0, 0.0, -90.0), (0, -1, 0)),+ ((0.0, 90.0, 0.0), (-1, 0, 0)),+ ((90.0, 0.0, 0.0), (0, 0, 1)),+ ):+ assert self._heaviest_offset(motion_blur3d(volume, 3, angle, 1.0)[0, 0], (3, 5, 4)) == offset++ def test_convention_motion_blur3d_module_float_angle_is_used_for_all_three_axes(self, device, dtype):+ # MotionBlur3D takes a float angle as the vector (angle, angle, angle): yaw, pitch and roll alike. At 50+ # degrees every vector that leaves one or two of its components at 0 is a different kernel.+ self._skip_without_default_border(device, dtype, True)+ torch.manual_seed(0)+ volume = torch.rand(1, 1, 7, 8, 9).to(device=device, dtype=dtype)+ out = MotionBlur3D(3, 50.0, 0.5)(volume)+ self.assert_close(out, motion_blur3d(volume, 3, (50.0, 50.0, 50.0), 0.5))+ for yaw, pitch, roll in ((1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1), (0, 1, 1)):+ partial = motion_blur3d(volume, 3, (50.0 * yaw, 50.0 * pitch, 50.0 * roll), 0.5)+ assert (out - partial).abs().max() > 0.3++ def test_convention_motion_blur_tensor_angle_and_direction_are_per_sample(self, device, dtype):+ # A tensor angle and direction are (B,): entry b drives sample b. A scalar direction is not broadcast+ # against a (B,) angle.+ self._skip_without_default_border(device, dtype, False)+ if not supports_bilinear_2d_grid_sample(device, dtype):+ pytest.skip(f"this torch build has no 2D grid_sample kernel for {dtype} on {device.type}")+ torch.manual_seed(0)+ image = torch.rand(2, 1, 9, 12).to(device=device, dtype=dtype)+ angle = torch.tensor([0.0, 90.0], device=device, dtype=dtype)+ direction = torch.tensor([0.5, -0.5], device=device, dtype=dtype)+ out = motion_blur(image, 5, angle, direction)+ self.assert_close(out[:1], motion_blur(image[:1], 5, 0.0, 0.5))+ self.assert_close(out[1:], motion_blur(image[1:], 5, 90.0, -0.5))+ with pytest.raises(BaseError, match="same length"):+ motion_blur(image, 5, angle, 0.5)++ @pytest.mark.parametrize("volumetric", [False, True], ids=["MotionBlur", "MotionBlur3D"])+ def test_convention_motion_blur_modules_honour_mode_5164(self, volumetric, device, dtype):+ """MotionBlur and MotionBlur3D rotate the kernel with their mode argument, as the functions do (#5164)."""+ self._skip_without_default_border(device, dtype, volumetric)+ torch.manual_seed(0)+ if volumetric:+ image = torch.rand(1, 1, 5, 6, 7).to(device=device, dtype=dtype)+ out = MotionBlur3D(3, (10.0, 20.0, 30.0), 0.5, mode="bilinear")(image)+ nearest = motion_blur3d(image, 3, (10.0, 20.0, 30.0), 0.5, mode="nearest")+ bilinear = motion_blur3d(image, 3, (10.0, 20.0, 30.0), 0.5, mode="bilinear")+ else:+ image = torch.rand(1, 1, 9, 12).to(device=device, dtype=dtype)+ out = MotionBlur(5, 30.0, 0.3, mode="bilinear")(image)+ nearest = motion_blur(image, 5, 30.0, 0.3, mode="nearest")+ bilinear = motion_blur(image, 5, 30.0, 0.3, mode="bilinear")+ self.assert_close(out, bilinear)+ assert (out - nearest).abs().max() > 0.03++ def test_convention_motion_blur3d_module_takes_a_tensor_or_int_angle_5164(self, device, dtype):+ """MotionBlur3D takes a (B, 3) tensor angle as motion_blur3d does, and an int as a float (#5164)."""+ self._skip_without_default_border(device, dtype, True)+ torch.manual_seed(0)+ volume = torch.rand(1, 1, 5, 6, 7).to(device=device, dtype=dtype)+ # the tensor angle and direction share a device and a dtype, as get_motion_kernel3d requires+ angle, direction = torch.tensor([[10.0, 20.0, 30.0]]), torch.tensor([0.5])+ self.assert_close(MotionBlur3D(3, angle, direction)(volume), motion_blur3d(volume, 3, angle, direction))+ self.assert_close(MotionBlur3D(3, 35, 0.5)(volume), motion_blur3d(volume, 3, (35.0, 35.0, 35.0), 0.5))++ def test_convention_motion_blur_default_border_keeps_a_constant_image_5168(self, device, dtype):+ """The 2-D motion blurs default to border_type='reflect' and the 3-D ones to 'replicate' (#5168)."""+ # Both defaults keep a constant image constant at its edges, where 'constant' darkens it.+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ if not supports_replicate_padding_3d(device, dtype):+ pytest.skip(f"this torch build has no 3D replicate padding kernel for {dtype} on {device.type}")+ image = torch.ones(1, 1, 5, 7, device=device, dtype=dtype)+ self.assert_close(motion_blur(image, 5, 0.0, 0.0), image)+ self.assert_close(MotionBlur(5, 0.0, 0.0)(image), image)+ assert motion_blur(image, 5, 0.0, 0.0, "constant")[0, 0, 2, 0] < 0.9+ volume = torch.ones(1, 1, 5, 6, 7, device=device, dtype=dtype)+ self.assert_close(motion_blur3d(volume, 3, (0.0, 0.0, 0.0), 0.0), volume)+ self.assert_close(MotionBlur3D(3, (0.0, 0.0, 0.0), 0.0)(volume), volume)+ assert motion_blur3d(volume, 3, (0.0, 0.0, 0.0), 0.0, "constant")[0, 0, 2, 3, 0] < 0.9+ # the defaults are those two modes, not just modes that keep a constant+ torch.manual_seed(0)+ image, volume = torch.rand_like(image), torch.rand_like(volume)+ self.assert_close(motion_blur(image, 5, 30.0, 0.5), motion_blur(image, 5, 30.0, 0.5, "reflect"))+ self.assert_close(+ motion_blur3d(volume, 3, (10.0, 20.0, 30.0), 0.5),+ motion_blur3d(volume, 3, (10.0, 20.0, 30.0), 0.5, "replicate"),+ )++ def test_convention_motion_blur_kernel_size_must_be_an_int_5169(self, device, dtype):+ """motion_blur and motion_blur3d reject a tuple kernel_size with a kornia error that names it (#5169)."""+ with pytest.raises(BaseError, match="kernel_size"):+ motion_blur(torch.rand(1, 1, 9, 12, device=device, dtype=dtype), (5, 5), 30.0, 0.5)+ with pytest.raises(BaseError, match="kernel_size"):+ motion_blur3d(torch.rand(1, 1, 5, 9, 12, device=device, dtype=dtype), (3, 3, 3), (30.0, 0.0, 0.0), 0.5)diff --git a/tests/filters/test_unsharp_mask.py b/tests/filters/test_unsharp_mask.pyindex c57db8278..b6bc80720 100644--- a/tests/filters/test_unsharp_mask.py+++ b/tests/filters/test_unsharp_mask.py@@ -18,9 +18,9 @@import pytestimport torch-from kornia.filters import UnsharpMask, unsharp_mask+from kornia.filters import UnsharpMask, gaussian_blur2d, unsharp_mask-from testing.base import BaseTester+from testing.base import BaseTester, supports_reflect_paddingclass Testunsharp(BaseTester):@@ -87,3 +87,33 @@ class Testunsharp(BaseTester):op_optimized = torch_optimizer(op)self.assert_close(op(data), op_optimized(data))+++class TestConventionsUnsharpMask(BaseTester):+ """Pins for the formula and the range of :func:`unsharp_mask`."""++ @pytest.mark.parametrize("border_type", ["reflect", "constant"])+ def test_convention_unsharp_mask_is_twice_the_image_minus_its_gaussian_blur(self, border_type, device, dtype):+ # out = 2 * x - gaussian_blur2d(x, kernel_size, sigma, border_type) = x + 1 * (x - blur): the gain is fixed at 1+ # (scikit-image's amount=1) and kernel_size, sigma and border_type are gaussian_blur2d's.+ if border_type == "reflect" and not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ torch.manual_seed(0)+ image = torch.rand(2, 3, 9, 13).to(device=device, dtype=dtype)+ expected = 2 * image - gaussian_blur2d(image, (3, 5), (1.0, 2.0), border_type)+ self.assert_close(unsharp_mask(image, (3, 5), (1.0, 2.0), border_type), expected)+ self.assert_close(UnsharpMask((3, 5), (1.0, 2.0), border_type)(image), expected)++ def test_convention_unsharp_mask_output_is_not_clamped(self, device, dtype):+ # The output is not clipped to the input range: a 0 | 1 step overshoots on both sides of the edge+ # (scikit-image clips by default, preserve_range=False).+ # Snippet used to generate expected:+ # step = torch.zeros(1, 1, 7, 10); step[..., 5:] = 1; print(unsharp_mask(step, (5, 5), (1.5, 1.5))[0, 0, 3])+ if not supports_reflect_padding(device, dtype):+ pytest.skip(f"this torch build has no reflect padding kernel for {dtype} on {device.type}")+ step = torch.zeros(1, 1, 7, 10, device=device, dtype=dtype)+ step[..., 5:] = 1.0+ out = unsharp_mask(step, (5, 5), (1.5, 1.5))+ expected = [0.0, 0.0, 0.0, -0.120078, -0.353959, 1.353959, 1.120078, 1.0, 1.0, 1.0]+ self.assert_close(out[0, 0, 3], torch.tensor(expected, device=device, dtype=dtype))+ assert out.min() < -0.3 and out.max() > 1.3