Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(filters): Convention blocks and pins for spatial_gradient, sobel, laplacian, canny, in_range and otsu_threshold (batch 11c) (#5427)

Dmytro Mishkin6e8d566b73df
diff --git a/changelog.d/5427.added.md b/changelog.d/5427.added.md
new file mode 100644
index 000000000..5ceedbf07
--- /dev/null
+++ b/changelog.d/5427.added.md
@@ -0,0 +1 @@
+Convention blocks for `spatial_gradient`, `spatial_gradient3d`, `sobel`, `laplacian`, `canny`, `in_range` and `otsu_threshold`: the `(dx, dy)` output layout and default normalisation of the derivative filters, the Laplacian kernel's sign and scale, the unnormalized Sobel magnitude that `canny`'s thresholds are compared with and its tie rule, `in_range`'s inclusive bounds and accepted bound shapes, and the per-plane Otsu threshold read from the upper edge of the split bin. The Filtering section of the Conventions page maps the derivative scales and `canny`'s thresholds to OpenCV and scikit-image.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index b4aca41f7..dd18e3b4b 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -669,6 +669,37 @@ 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 derivative filters apply those kernels at different scales, and :func:`~kornia.filters.canny` thresholds the raw
+one:
+
+- :func:`~kornia.filters.spatial_gradient` and :func:`~kornia.filters.sobel` use normalized first-order gradients
+ by default: an interior axis-aligned unit slope gives 1 in the corresponding ``spatial_gradient`` channel, and
+ ``sobel`` returns :math:`\sqrt{1 + \epsilon}`. ``normalized=False`` returns the raw Sobel response above.
+ :func:`~kornia.filters.spatial_gradient` always replicates the border, so
+ ``cv2.Sobel(x, cv2.CV_64F, 1, 0, borderType=cv2.BORDER_REPLICATE)`` and
+ ``scipy.ndimage.sobel(x, axis=-1, mode='nearest')`` equal channel 0 of ``spatial_gradient(x, normalized=False)``;
+ OpenCV's default ``BORDER_REFLECT_101`` differs on the outermost rows and columns.
+ ``skimage.filters.sobel(x, mode='nearest')`` equals ``sqrt(2) * sobel(x, eps=0)``.
+- For floating inputs, :func:`~kornia.filters.laplacian` is normalized by default too, but by the stencil's absolute
+ sum, 16 for size 3: ``laplacian(x, 3)`` estimates :math:`3 \nabla^2 / 16`, and ``normalized=False`` the
+ :math:`3 \nabla^2` above. See its Convention block for the integer-input defect.
+- :func:`~kornia.filters.canny` compares its thresholds with the **unnormalized** Sobel magnitude of the blurred
+ image, about eight times what :func:`~kornia.filters.sobel` returns by default, up to the ``eps`` inside the square
+ root. For a **single-channel grayscale** uint8 image ``img``, ``cv2.Canny(img, t1, t2, L2gradient=True)`` corresponds
+ to ``canny(x, t1 / 255, t2 / 255, kernel_size=1, eps=0)`` for edge-map comparison, with ``x`` the float32 or float64
+ tensor ``img / 255``: the thresholds scale with the image and ``kernel_size=1`` skips the Gaussian blur that
+ OpenCV does not apply. OpenCV's default L1 magnitude :math:`|g_x| + |g_y|` has no kornia counterpart.
+ :func:`~kornia.filters.canny` resolves ties along the gradient as OpenCV does, but floating-point rounding of
+ ``img / 255``, the gradient and threshold comparisons can still change a near-tie or near-threshold decision.
+ With the default ``eps=1e-6``, the square root raises the magnitude above its ``eps=0`` value, when retained by
+ the dtype's precision: it can promote a pixel even when the threshold is slightly above the raw magnitude,
+ without an exact tie. Color images need separate preprocessing: Kornia converts RGB to grayscale, while
+ OpenCV's color Canny selects the channel with the strongest gradient, so this correspondence does not apply
+ directly to a 3-channel image.
+- ``skimage.feature.canny`` thresholds the same unnormalized magnitude of a floating-point image and has the same
+ defaults, 0.1 and 0.2, so thresholds carry over; its Gaussian blur and its interpolating suppression differ from
+ :func:`~kornia.filters.canny`'s, so the edge maps do not match.
+
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
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index b8d07ebfd..4ca85499a 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -70,19 +70,34 @@ def canny(
.. image:: _static/img/canny.png
- The thresholds are compared with the magnitude :math:`\sqrt{g_x^2 + g_y^2 + \epsilon}` of the **unnormalised**
- Sobel gradient of the blurred grayscale image, ``sobel(blurred, normalized=False, eps=eps)``. That is eight times
- what :func:`~kornia.filters.sobel` returns with its default ``normalized=True``, up to the ``eps`` inside the square
- root, so on an image in :math:`[0, 1]` it is not bounded by 1: a unit step reaches 4 without the blur
- (``kernel_size=1``) and about 2.59 with the default one.
- In float16 the squared gradient overflows past 65504, which a step of 64 already reaches without the blur, so
- keep a float16 image in :math:`[0, 1]` rather than scaling it and the thresholds up.
-
- Non-maximum suppression compares each pixel with its two neighbours along the gradient direction, rounded to a
- multiple of 45 degrees. As in OpenCV's ``cv2.Canny``, along a horizontal (vertical) gradient a pixel must be
- strictly greater than its left (upper) neighbour and greater than or equal to its right (lower) one, so of two
- pixels of equal magnitude across a step edge the left (upper) one is kept. Along a diagonal it must be strictly
- greater than both. A pixel with zero gradient is never kept.
+ Convention:
+ - A 3-channel input is converted with :func:`~kornia.color.rgb_to_grayscale`, which reads channel 0 as
+ red. For a floating input both outputs are :math:`(B, 1, H, W)` in the input's dtype.
+ - The image is blurred with ``gaussian_blur2d(input, kernel_size, sigma)``; the Convention block on
+ :func:`~kornia.filters.gaussian_blur2d` gives the order of both pairs, and ``kernel_size=1`` skips the
+ blur. The magnitude is :math:`\sqrt{g_x^2 + g_y^2 + \epsilon}` of the **unnormalised** Sobel gradient
+ ``spatial_gradient(blurred, normalized=False)``: an axis-aligned ramp of signed slope ``s`` gives
+ :math:`\sqrt{(8 s)^2 + \epsilon}` at an interior pixel, about ``8 * abs(s)``. This is about eight times
+ what :func:`~kornia.filters.sobel` returns by default, up to the ``eps`` inside the square root. On an
+ image in :math:`[0, 1]` it is not bounded by 1: a unit step reaches 4 without the blur and about 2.59 with
+ the default one. In float16 the squared gradient overflows past 65504, which a step of 64 already reaches
+ without the blur, so keep a float16 image in :math:`[0, 1]` rather than scaling it and the thresholds up.
+ - The thresholds compare against that magnitude and are strict: a pixel is weak above ``low_threshold`` and
+ strong above ``high_threshold``. :ref:`Filtering <filtering-conventions>` maps them onto OpenCV and
+ scikit-image.
+ - Non-maximum suppression compares each pixel with its two neighbours along the gradient direction,
+ rounded to a multiple of 45 degrees. As in OpenCV's ``cv2.Canny``, along a horizontal (vertical) gradient
+ a pixel must be strictly greater than its left (upper) neighbour and greater than or equal to its right
+ (lower) one, so of two pixels of equal magnitude across a step edge the left (upper) one is kept. Along a
+ diagonal it must be strictly greater than both. A pixel with zero gradient is never kept. The returned
+ magnitude is taken after this step, so it is zero off the edge ridges; it is differentiable with respect
+ to the input, and the edge map is not.
+ - Hysteresis keeps a weak pixel connected to a strong one through any of its 8 neighbours, repeated until
+ nothing changes, and returns edges of 0 and 1.
+ - Known defect: an integer input is not converted to a floating dtype. With the default blur a 1-channel
+ signed integer image blurs to zeros and yields no edge; a uint8 image, a 3-channel integer image, or any
+ integer image where torch has no integer convolution raises
+ (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
Args:
input: input image torch.Tensor with shape :math:`(B,C,H,W)`, with :math:`C` equal to 1, or to 3 for an RGB
@@ -97,7 +112,7 @@ def canny(
eps: regularization number to avoid NaN during backprop.
Returns:
- - the canny edge magnitudes map, shape of :math:`(B,1,H,W)`.
+ - the gradient magnitude after non-maximum suppression, shape of :math:`(B,1,H,W)`.
- the canny edge detection filtered by thresholds and hysteresis, shape of :math:`(B,1,H,W)`.
.. note::
@@ -164,7 +179,9 @@ def canny(
negative_idx: torch.Tensor = (angle_45 + 4) % 8
negative_idx = negative_idx.long()
- # The two neighbours along the gradient direction, read with one gather per channel
+ # The two neighbours along the gradient direction, read with one gather per channel. Inductor on MPS miscompiles
+ # two separate gathers when the pixel is read from the padded magnitude rather than from the window: the second
+ # comparison recomputes the pixel's magnitude from gx alone (pytorch/pytorch#199642)
neighbour_both: torch.Tensor = torch.gather(window, 2, torch.stack([positive_idx, negative_idx], 2))
neighbour_positive: torch.Tensor = neighbour_both[:, :, 0]
neighbour_negative: torch.Tensor = neighbour_both[:, :, 1]
@@ -218,7 +235,8 @@ def canny(
class Canny(nn.Module):
r"""nn.Module that finds edges of the input image and filters them using the Canny algorithm.
- See :func:`~kornia.filters.canny` for the units of the thresholds and the non-maximum suppression.
+ Convention:
+ See the Convention block on :func:`~kornia.filters.canny`. The thresholds are validated at construction.
Args:
low_threshold: lower threshold for the hysteresis procedure, in the units of the unnormalised Sobel
@@ -231,7 +249,7 @@ class Canny(nn.Module):
eps: regularization number to avoid NaN during backprop.
Returns:
- - the canny edge magnitudes map, shape of :math:`(B,1,H,W)`.
+ - the gradient magnitude after non-maximum suppression, shape of :math:`(B,1,H,W)`.
- the canny edge detection filtered by thresholds and hysteresis, shape of :math:`(B,1,H,W)`.
Example:
@@ -302,7 +320,7 @@ class Canny(nn.Module):
Returns:
Tuple ``(magnitude, edges)``. ``magnitude`` contains the gradient
- magnitude response for each pixel, and ``edges`` contains the final
+ magnitude after non-maximum suppression, and ``edges`` contains the final
thresholded edge map. Both tensors follow the layout returned by
:func:`canny` and keep the same batch and spatial dimensions as the
input.
diff --git a/kornia/filters/in_range.py b/kornia/filters/in_range.py
index 43d1c25c3..c66723e63 100644
--- a/kornia/filters/in_range.py
+++ b/kornia/filters/in_range.py
@@ -98,9 +98,17 @@ def in_range(
\text{out}(I) = \bigwedge_{c=0}^{C-1}
\left( \text{lower}_c(I) \leq \text{input}_c(I) \leq \text{upper}_c(I) \right)
- where `C` is the number of channels. Both comparisons are inclusive. For integer inputs, fractional lower
- bounds are rounded up and fractional upper bounds down. Bounds outside the input dtype's range do not
- wrap or overflow; a range containing no representable input value produces an empty mask.
+ where `C` is the number of channels. Both comparisons are inclusive.
+
+ Convention:
+ - A NaN channel fails its pixel. The mask has the input's dtype, 1 for a pass. For floating input, bounds
+ are cast to the input dtype before comparison, so only an interval still reversed after that conversion
+ selects nothing.
+ - ``return_mask=False`` returns ``input * mask``: the channels of a failing pixel become 0, except a NaN or
+ infinite one, which becomes NaN.
+ - For integer inputs, fractional lower bounds round up and fractional upper bounds round down. Bounds outside
+ the input dtype's range do not wrap or overflow; a range containing no representable input value produces
+ an empty mask.
Args:
input: The input torch.Tensor to be filtered in the shape of :math:`(*, *, H, W)`.
@@ -209,8 +217,10 @@ def in_range(
class InRange(nn.Module):
r"""Create a module for applying lower and upper bounds to input tensors.
+ Convention:
+ See the Convention block on :func:`~kornia.filters.in_range`.
+
Args:
- input: The input torch.Tensor to be filtered.
lower: The lower bounds of the filter (inclusive).
upper: The upper bounds of the filter (inclusive).
return_mask: If is true, the filtered mask is returned, otherwise the filtered input image.
@@ -261,8 +271,9 @@ class InRange(nn.Module):
the height, and :math:`W` is the width.
Returns:
- If ``self.return_mask`` is ``True``, a mask indicating which
- entries lie within the inclusive range. Otherwise, a tensor with
- values outside the range removed according to :func:`in_range`.
+ If ``self.return_mask`` is ``True``, a :math:`(B, 1, H, W)` mask of
+ the pixels whose every channel lies within the inclusive range.
+ Otherwise, a tensor with values outside the range removed according
+ to :func:`in_range`.
"""
return in_range(input, self.lower, self.upper, self.return_mask)
diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.py
index b489ae713..735b22c68 100644
--- a/kornia/filters/laplacian.py
+++ b/kornia/filters/laplacian.py
@@ -63,23 +63,40 @@ def laplacian(
.. image:: _static/img/laplacian.png
- The operator smooths the given tensor with a laplacian kernel by convolving
- it to each channel. It supports batched operation.
+ The operator filters each channel of the given tensor with a Laplacian kernel.
+ It supports batched operation.
+
+ Convention:
+ - The kernel is ``get_laplacian_kernel2d(kernel_size)``, correlated with each channel as by
+ :func:`~kornia.filters.filter2d`; see the Convention blocks on
+ :func:`~kornia.filters.get_laplacian_kernel2d` for the stencil, its sign and ``kernel_size``, and on
+ :func:`~kornia.filters.filter2d` for the border modes.
+ - For floating inputs, ``normalized=True``, the default, divides the kernel by its absolute sum
+ :math:`2 (kH \cdot kW - 1)`, 16 for size 3. Unlike ``normalized`` in
+ :func:`~kornia.filters.spatial_gradient`, this does not give derivative units: size 3 returns
+ :math:`3 \nabla^2 / 16`. :ref:`Filtering <filtering-conventions>` compares both scales with scipy and
+ OpenCV.
+ - Known defect: an integer input casts the kernel to its dtype, as :func:`~kornia.filters.filter2d` does,
+ so the normalised kernel truncates to 0 and on the CPU the output is all zeros. For uint8, the negative
+ centre wraps before normalisation, making its absolute sum 256 for size 3, but every normalised tap still
+ truncates to 0 (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
Args:
input: the input image tensor with shape :math:`(B, C, H, W)`.
kernel_size: the size of the kernel. It should be odd and positive, and at least 3 along one axis.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
- ``'replicate'`` or ``'circular'``.
+ ``'replicate'`` or ``'circular'``, case-insensitive.
normalized: if True, L1 norm of the kernel is set to 1.
Note:
Ordinary eager CPU execution uses convolution for extreme input ranges.
- Captured graphs and function transforms retain their selected arithmetic.
+ Captured graphs and function transforms retain their selected arithmetic, so with ``normalized=False`` an
+ input near its dtype's maximum can overflow to NaN under ``torch.compile`` or ``torch.vmap`` where eager CPU
+ execution returns a finite response.
Return:
- the blurred image with shape :math:`(B, C, H, W)`.
+ the Laplacian response with shape :math:`(B, C, H, W)`.
Raises:
BaseError: if a size is even or not positive, if ``kernel_size`` is a sequence of other than 2 sizes, or if
@@ -140,14 +157,17 @@ def laplacian(
class Laplacian(nn.Module):
r"""Create an operator that returns a tensor using a Laplacian filter.
- The operator smooths the given tensor with a laplacian kernel by convolving
- it to each channel. It supports batched operation.
+ The operator filters each channel of the given tensor with a Laplacian kernel.
+ It supports batched operation.
+
+ Convention:
+ See the Convention block on :func:`~kornia.filters.laplacian`.
Args:
kernel_size: the size of the kernel. It should be odd and positive, and at least 3 along one axis.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
- ``'replicate'`` or ``'circular'``.
+ ``'replicate'`` or ``'circular'``, case-insensitive.
normalized: if True, L1 norm of the kernel is set to 1.
Raises:
diff --git a/kornia/filters/otsu_thresholding.py b/kornia/filters/otsu_thresholding.py
index 08408dae8..7ee089f2e 100644
--- a/kornia/filters/otsu_thresholding.py
+++ b/kornia/filters/otsu_thresholding.py
@@ -25,7 +25,12 @@ from kornia.core.check import KORNIA_CHECK
class OtsuThreshold(torch.nn.Module):
- """Otsu thresholding module for PyTorch tensors."""
+ """Otsu thresholding module for PyTorch tensors.
+
+ Convention:
+ See the Convention block on :func:`~kornia.filters.otsu_threshold`. ``forward`` has no ``return_mask`` and
+ always returns the thresholded tensor with the thresholds.
+ """
# Standard deviation, in bin widths, of the Gaussian kernel density estimate whose histogram selects the
# threshold of ``slow_and_differentiable=True``.
@@ -375,17 +380,31 @@ def otsu_threshold(
) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Apply automatic image thresholding using Otsu algorithm to the input tensor.
- Each image/channel plane uses its own histogram range. The threshold is the upper edge of the selected histogram
- bin. For an integer input it is the largest integer below that value, so ``x > threshold`` keeps every pixel on
- or above it. For floating input, rounding is corrected when necessary to keep the threshold at or above the
- largest background pixel and below the smallest foreground pixel, so ``x > threshold`` matches the histogram
- split. On MPS, a zero foreground boundary in float32 or bfloat16 uses the smallest normal negative
- value because comparisons flush subnormal values to zero. Empty bins do not introduce candidate splits. A
- constant plane uses its constant value as the threshold. Both paths support ``torch.export`` and full-graph
- ``torch.compile``.
+ Convention:
+ - One threshold is returned per plane over the last two axes: a :math:`(B, C, H, W)` input gives ``B * C``
+ thresholds, flattened, and a tensor of at most two dimensions is one plane.
+ - Each plane is histogrammed on its own range, ``nbins`` bins between its minimum and its maximum, not over a
+ fixed :math:`[0, 1]` or :math:`[0, 255]`. The threshold is the upper edge of the selected histogram bin,
+ in input units and in the input's dtype. For an integer input it is the largest integer below that value,
+ so ``x > threshold`` keeps every pixel on or above it. For floating input, rounding is corrected when
+ necessary to keep the threshold at or above the largest background pixel and below the smallest foreground
+ pixel, so ``x > threshold`` matches the histogram split. On MPS, a zero foreground boundary in float32 or
+ bfloat16 uses the smallest normal negative value because comparisons flush subnormal values to zero.
+ - Histogram and bin-edge arithmetic uses float64 only for float64 input, and float32 for every other input
+ dtype, including integers and half precision. Large or narrowly spaced integer values can therefore lose
+ distinctions and select a different split; when that precision is required, pass float64 input whose
+ values are representable there, on a device that supports float64 (not MPS).
+ - Empty bins do not introduce candidate splits, so the lowest split across a run of empty bins wins on
+ every device. A constant plane uses its constant value as the threshold.
+ - The foreground is ``x > threshold``, strictly. The first output is ``x * (x > threshold)``, not a
+ binary image, and its gradient is that mask.
+ - With ``slow_and_differentiable=True``, every pixel contributes to a Gaussian kernel density estimate and
+ the threshold has a straight-through gradient; see the note below for the estimate and surrogate.
+ The default path's threshold has no gradient. Both paths support ``torch.export`` and full-graph
+ ``torch.compile``.
Args:
- x (Tensor): Input tensor (image or batch of images).
+ x (Tensor): Input tensor (image or batch of images) of at most five dimensions.
nbins (int): Number of bins for histogram computation, default is 256.
slow_and_differentiable (bool): If True, build the histogram from a Gaussian kernel density estimate and give
the threshold a gradient with respect to ``x``; see the note below. Default is False.
@@ -395,20 +414,15 @@ def otsu_threshold(
Returns:
Tuple[torch.Tensor, torch.Tensor]: Thresholded tensor, or the boolean mask ``x > threshold`` when
- ``return_mask`` is True, and the computed threshold values. The thresholded tensor cannot tell a kept pixel
- of value 0 from a dropped one; use the mask for that.
+ ``return_mask`` is True, each with the shape of ``x``, and the computed threshold values. The thresholded
+ tensor cannot tell a kept pixel of value 0 from a dropped one; use the mask for that.
Raises:
- ValueError: If the input tensor has unsupported dimensionality or dtype.
-
- .. note::
- - The input tensor can be of various types, but float types are preferred for accuracy
- in histogram computation, especially on CPU. Integer types will be cast to float.
- - If `use_thresh` is True, the threshold must have been computed previously and set in the module.
- - If `threshold` is provided, it overrides the computed threshold.
+ ValueError: If the input tensor has more than five dimensions.
+ ~kornia.core.exceptions.BaseError: If the input dtype is not supported.
.. note::
- You may found more information about the Otsu algorithm here: https://en.wikipedia.org/wiki/Otsu's_method
+ You can find more information about the Otsu algorithm here: https://en.wikipedia.org/wiki/Otsu's_method
.. note::
With ``slow_and_differentiable=True``, each pixel is spread into a Gaussian with a standard deviation of 0.1
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 20c3d2aec..768e41549 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -38,16 +38,27 @@ def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, n
.. image:: _static/img/spatial_gradient.png
+ Convention:
+ - The derivatives are the kernels of :func:`~kornia.filters.get_spatial_gradient_kernel2d`, stacked on a
+ new axis 2 in that function's order and with its sign; see its Convention block.
+ - For ``order=1`` with the default ``normalized=True``, an axis-aligned linear ramp with slope ``s`` has
+ response ``s`` in the corresponding channel away from the replicated border. With
+ ``normalized=False``, the Sobel response is ``8 s``. :ref:`Filtering <filtering-conventions>` maps both
+ scales onto OpenCV, scipy and scikit-image.
+ - The border is always replicated, so for ``order=1`` with ``normalized=True``, a linear ramp's derivative
+ is half its slope on the first and last pixel along that axis. There is no ``border_type``, unlike
+ :func:`~kornia.filters.filter2d` and :func:`~kornia.filters.laplacian`, whose default is ``'reflect'``.
+
Args:
input: input image torch.Tensor with shape :math:`(B, C, H, W)`.
mode: derivatives modality, can be: `sobel` or `diff`, case-insensitive.
order: the order of the derivatives.
normalized: if ``True``, scale the kernels so that every output channel estimates the derivative
- itself, exact on linear surfaces for ``order=1`` and on quadratic surfaces for ``order=2``. If
- ``False``, return the raw kernel responses.
+ itself away from the replicated border: exact on linear surfaces for ``order=1`` and on quadratic
+ surfaces for ``order=2``. If ``False``, return the raw kernel responses.
Return:
- the derivatives of the input feature map. with shape :math:`(B, C, 2, H, W)` holding
+ the derivatives of the input feature map, with shape :math:`(B, C, 2, H, W)` holding
:math:`(dx, dy)` for ``order=1`` and :math:`(B, C, 3, H, W)` holding :math:`(dxx, dxy, dyy)`
for ``order=2``.
@@ -107,9 +118,15 @@ def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, n
def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1) -> torch.Tensor:
r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
+ Convention:
+ - The derivatives are the kernels of :func:`~kornia.filters.get_spatial_gradient_kernel3d`, stacked on a
+ new axis 2; see its Convention block for their order and units. There is no ``normalized`` argument: a
+ floating input gives derivative units.
+ - The border is always replicated, as in :func:`~kornia.filters.spatial_gradient`.
+
Args:
input: input features torch.Tensor with shape :math:`(B, C, D, H, W)`.
- mode: derivatives modality, can be: `sobel` or `diff`, case-insensitive.
+ mode: derivatives modality, case-insensitive; only ``'diff'`` is implemented.
order: the order of the derivatives.
Return:
@@ -169,6 +186,15 @@ def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> to
.. image:: _static/img/sobel.png
+ Convention:
+ - The output is :math:`\sqrt{g_x^2 + g_y^2 + \epsilon}` per channel, where :math:`(g_x, g_y)` is
+ ``spatial_gradient(input, 'sobel', normalized=normalized)``; see the Convention block on
+ :func:`~kornia.filters.spatial_gradient`. Away from the replicated border, an axis-aligned ramp of slope
+ ``s`` gives :math:`\sqrt{s^2 + \epsilon}`, about :math:`|s|`, with the default ``normalized=True``;
+ ``normalized=False`` gives about :math:`8 |s|`, the scale :func:`~kornia.filters.canny` thresholds.
+ - ``eps`` sits inside the square root, so a flat region returns :math:`\sqrt{\epsilon}`, ``1e-3`` by
+ default, not 0.
+
Args:
input: the input image with shape :math:`(B,C,H,W)`.
normalized: if True, L1 norm of the kernel is set to 1.
@@ -204,7 +230,10 @@ def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> to
class SpatialGradient(nn.Module):
- r"""Compute the first order image derivative in both x and y using a Sobel operator.
+ r"""Compute the first or second order image derivative in x and y using a Sobel or diff operator.
+
+ Convention:
+ See the Convention block on :func:`~kornia.filters.spatial_gradient`.
Args:
mode: derivatives modality, can be: `sobel` or `diff`, case-insensitive.
@@ -212,11 +241,11 @@ class SpatialGradient(nn.Module):
normalized: whether the output is normalized.
Return:
- the sobel edges of the input feature map.
+ the derivatives of the input feature map.
Shape:
- Input: :math:`(B, C, H, W)`
- - Output: :math:`(B, C, 2, H, W)`
+ - Output: :math:`(B, C, 2, H, W)` for ``order=1`` and :math:`(B, C, 3, H, W)` for ``order=2``
Examples:
>>> input = torch.rand(1, 3, 4, 4)
@@ -251,10 +280,11 @@ class SpatialGradient(nn.Module):
Returns:
Gradient tensor from :func:`spatial_gradient`. For first-order
- derivatives the shape is typically :math:`(B, C, 2, H, W)`, where
+ derivatives the shape is :math:`(B, C, 2, H, W)`, where
the derivative axis of size ``2`` stores the response along
- :math:`x` (width) and :math:`y` (height). Higher orders may expose
- additional derivative components according to the functional API.
+ :math:`x` (width) and :math:`y` (height). For second-order
+ derivatives it is :math:`(B, C, 3, H, W)`, holding
+ :math:`(dxx, dxy, dyy)`.
"""
return spatial_gradient(input, self.mode, self.order, self.normalized)
@@ -262,8 +292,11 @@ class SpatialGradient(nn.Module):
class SpatialGradient3d(nn.Module):
r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
+ Convention:
+ See the Convention block on :func:`~kornia.filters.spatial_gradient3d`.
+
Args:
- mode: derivatives modality, can be: `sobel` or `diff`, case-insensitive.
+ mode: derivatives modality, case-insensitive; only ``'diff'`` is implemented.
order: the order of the derivatives.
Return:
@@ -318,6 +351,9 @@ class SpatialGradient3d(nn.Module):
class Sobel(nn.Module):
r"""Compute the Sobel operator and returns the magnitude per channel.
+ Convention:
+ See the Convention block on :func:`~kornia.filters.sobel`.
+
Args:
normalized: if True, L1 norm of the kernel is set to 1.
eps: regularization number to avoid NaN during backprop.
diff --git a/tests/filters/test_canny.py b/tests/filters/test_canny.py
index 6ff8fcd01..4c456600e 100644
--- a/tests/filters/test_canny.py
+++ b/tests/filters/test_canny.py
@@ -21,10 +21,12 @@ from typing import Any
import pytest
import torch
+import torch.nn.functional as F
+from kornia.color import rgb_to_grayscale
from kornia.core._compat import torch_version, torch_version_ge
from kornia.core.exceptions import ImageError
-from kornia.filters import Canny, canny, sobel
+from kornia.filters import Canny, canny, gaussian_blur2d, sobel, spatial_gradient
from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding
@@ -570,3 +572,205 @@ class TestCanny(BaseTester):
def test_unsupported_channel_count_raises(self, channels, device, dtype):
with pytest.raises(ImageError, match="1 or 3 channels"):
canny(torch.zeros(1, channels, 12, 13, device=device, dtype=dtype))
+
+
+class TestConventionsCanny(BaseTester):
+ @staticmethod
+ def _require_padding(device, dtype):
+ # the Gaussian blur pads by reflection, the Sobel gradient by replication
+ if not (supports_reflect_padding(device, dtype) and supports_replicate_padding(device, dtype)):
+ pytest.skip("torch has no reflect or replicate padding kernel for this device and dtype")
+
+ @staticmethod
+ def _ramped_step(height, device, dtype):
+ # 0 | 0.6 * height | height across x = 6..8 of a 9x14 image; with kernel_size=1 (no blur) the raw Sobel |gx|
+ # is 2.4h, 4h and 1.6h at x = 6, 7, 8, so the ridge at x = 7 has no tie
+ img = torch.zeros(1, 1, 9, 14, device=device, dtype=dtype)
+ img[..., 7] = 0.6 * height
+ img[..., 8:] = height
+ return img
+
+ def test_convention_canny_magnitude_is_unnormalized_sobel_after_nms(self, device, dtype):
+ self._require_padding(device, dtype)
+ img = self._ramped_step(0.125, device, dtype)
+ magnitude, edges = canny(img, 0.4, 0.49, kernel_size=1, eps=0.0)
+ assert magnitude.dtype == edges.dtype == dtype
+ # the thresholds compare against the unnormalized Sobel magnitude 4h = 0.5, eight times sobel()'s default
+ self.assert_close(sobel(img, eps=0.0)[..., 7], torch.full((1, 1, 9), 0.0625, device=device, dtype=dtype))
+ expected = torch.zeros_like(img)
+ expected[..., 7] = 0.5 # returned after non-maximum suppression: zero off the ridge
+ self.assert_close(magnitude, expected)
+ self.assert_close(edges, expected * 2)
+ # relabel: the transposed step gives the transposed result
+ magnitude_t, edges_t = canny(img.transpose(-1, -2), 0.4, 0.49, kernel_size=1, eps=0.0)
+ self.assert_close(magnitude_t, magnitude.transpose(-1, -2))
+ self.assert_close(edges_t, edges.transpose(-1, -2))
+ # with the default 5x5, sigma=1 blur: the Sobel of gaussian_blur2d(img), unnormalized, eps inside the root
+ grad = spatial_gradient(gaussian_blur2d(img, (5, 5), (1.0, 1.0)), normalized=False)
+ reference = torch.sqrt(grad[:, :, 0] ** 2 + grad[:, :, 1] ** 2 + 1e-6)
+ magnitude, _ = canny(img)
+ kept = magnitude > 0.1 # the ridge (about 0.32), not the sqrt(eps) floor of the flat regions
+ assert kept.sum() == 9 # one ridge pixel per row
+ self.assert_close(magnitude[kept], reference[kept])
+
+ def test_convention_canny_thresholds_are_strict(self, device, dtype):
+ self._require_padding(device, dtype)
+ # the ridge magnitude is exactly 0.5 (eps=0); hysteresis=False keeps the weak (0.5) / strong (1) labels
+ img = self._ramped_step(0.125, device, dtype)
+ ridge = (0, 0, 4, 7)
+ _, edges = canny(img, 0.4, 0.5, kernel_size=1, eps=0.0, hysteresis=False)
+ assert edges[ridge].item() == 0.5 # equal to high_threshold: weak, not strong
+ _, edges = canny(img, 0.5, 0.5, kernel_size=1, eps=0.0, hysteresis=False) # low == high is accepted
+ assert edges.sum().item() == 0 # equal to low_threshold: dropped
+ _, edges = canny(img, 0.4, 0.49, kernel_size=1, eps=0.0, hysteresis=False)
+ assert edges[ridge].item() == 1.0
+
+ def test_convention_canny_converts_rgb_to_grayscale(self, device, dtype):
+ self._require_padding(device, dtype)
+ generator = torch.Generator().manual_seed(0)
+ rgb = torch.rand(2, 3, 11, 13, generator=generator).to(device=device, dtype=dtype)
+ magnitude, edges = canny(rgb)
+ assert magnitude.shape == edges.shape == (2, 1, 11, 13)
+ magnitude_grey, edges_grey = canny(rgb_to_grayscale(rgb))
+ self.assert_close(magnitude, magnitude_grey)
+ self.assert_close(edges, edges_grey)
+ # channel 0 is read as red: the same data in BGR order gives other edges
+ _, edges_bgr = canny(rgb.flip(1))
+ assert not torch.equal(edges_bgr, edges)
+
+ def test_convention_canny_opencv_correspondence_requires_grayscale(self, device, dtype):
+ self._require_padding(device, dtype)
+ # OpenCV 5.0.0 gives this ridge for both grayscale and channel-2-only color uint8 images:
+ # u8 = np.zeros((9, 14), np.uint8); u8[:, 7] = 153; u8[:, 8:] = 255
+ # cv2.Canny(u8, 200, 300, L2gradient=True)
+ # cv2.Canny(np.stack([np.zeros_like(u8), np.zeros_like(u8), u8], -1), 200, 300, L2gradient=True)
+ # The raw gradient neighborhood is [612, 1020, 408], so the ridge has no NMS tie.
+ gray = self._ramped_step(1.0, device, dtype)
+ expected = torch.zeros_like(gray)
+ expected[..., 7] = 1.0
+ _, edges = canny(gray, 200 / 255, 300 / 255, kernel_size=1, eps=0.0)
+ self.assert_close(edges, expected)
+ # Kornia converts RGB to grayscale: channel 2's blue coefficient reduces the ridge below the low threshold.
+ rgb = torch.cat([torch.zeros_like(gray), torch.zeros_like(gray), gray], dim=1)
+ _, edges_rgb = canny(rgb, 200 / 255, 300 / 255, kernel_size=1, eps=0.0)
+ self.assert_close(edges_rgb, torch.zeros_like(gray))
+
+ def test_convention_canny_eps_can_promote_a_near_threshold_ridge(self, device, dtype):
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("the near-threshold gap must be representable in the test dtype")
+ self._require_padding(device, dtype)
+ # The untied raw ridge magnitude is 0.5; the high threshold is slightly above it, not equal to it.
+ # Default eps raises the magnitude to about 0.500001, producing a strong edge instead of an isolated weak one.
+ img = self._ramped_step(0.125, device, dtype)
+ _, raw_edges = canny(img, 0.4, 0.5000005, kernel_size=1, eps=0.0)
+ self.assert_close(raw_edges, torch.zeros_like(img))
+ _, regularized_edges = canny(img, 0.4, 0.5000005, kernel_size=1)
+ expected = torch.zeros_like(img)
+ expected[..., 7] = 1.0
+ self.assert_close(regularized_edges, expected)
+
+ def test_convention_canny_hysteresis_is_8_connected(self, device, dtype):
+ self._require_padding(device, dtype)
+ # hysteresis keeps a weak pixel connected to a strong one through any of its 8 neighbours, iterated to
+ # convergence; the reference grows the strong set from canny's own weak / strong labels
+ generator = torch.Generator().manual_seed(2)
+ img = torch.rand(1, 1, 12, 17, generator=generator).to(device=device, dtype=dtype)
+ _, labels = canny(img, 0.3, 0.6, hysteresis=False)
+ _, edges = canny(img, 0.3, 0.6, hysteresis=True)
+ weak, strong = (labels == 0.5).float(), (labels == 1).float()
+ cross = torch.tensor([[[[0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0]]]], device=device)
+
+ def grow(dilate):
+ kept, steps = strong, 0
+ while True:
+ grown = torch.maximum(strong, weak * (dilate(kept) > 0).float())
+ if torch.equal(grown, kept):
+ return kept, steps
+ kept, steps = grown, steps + 1
+
+ kept_8, steps_8 = grow(lambda k: F.max_pool2d(k, 3, 1, 1))
+ kept_4, _ = grow(lambda k: F.conv2d(k, cross, padding=1))
+ assert steps_8 > 1 # the fixture needs more than one pass
+ assert not torch.equal(kept_8, kept_4) # and separates the two connectivities
+ self.assert_close(edges, kept_8.to(dtype))
+
+ def test_convention_canny_blur_pairs_are_rows_first(self, device, dtype):
+ self._require_padding(device, dtype)
+ # kernel_size and sigma reach gaussian_blur2d unchanged, as (rows, columns) and (sigma_y, sigma_x); the step
+ # varies along x only, so the column entries decide the ridge and the swapped pairs give another magnitude
+ img = self._ramped_step(0.125, device, dtype)
+ ridge = {}
+ for kernel_size, sigma in (((5, 3), (1.5, 0.7)), ((3, 5), (0.7, 1.5))):
+ grad = spatial_gradient(gaussian_blur2d(img, kernel_size, sigma), normalized=False)
+ reference = torch.sqrt(grad[:, :, 0] ** 2 + grad[:, :, 1] ** 2 + 1e-6)
+ magnitude, _ = canny(img, kernel_size=kernel_size, sigma=sigma)
+ kept = magnitude > 0.1 # the ridge, not the sqrt(eps) floor of the flat regions
+ assert kept[0, 0].nonzero()[:, 1].tolist() == [7] * 9
+ self.assert_close(magnitude[kept], reference[kept])
+ ridge[kernel_size] = magnitude[0, 0, 4, 7].item()
+ assert abs(ridge[(5, 3)] - ridge[(3, 5)]) > 0.1 # about 0.395 against 0.263
+
+ def test_convention_canny_nms_follows_the_diagonal_gradient(self, device, dtype):
+ self._require_padding(device, dtype)
+ # a three-level step across x + y (0 | 0.3 on x + y = 13 | 1) in a 12x17 image, no blur: the gradient points
+ # along (1, 1) and its raw Sobel components are 0.3, 1.6, 3, 2.4, 0.7 on the lines x + y = 11..15. Suppression
+ # compares each line with the lines two steps away along the gradient, so 13 (3 against 0.3, 0.7) and 14
+ # (2.4 against 1.6, 0) survive; comparing along the edge, or along x or y only, gives another set
+ ys, xs = torch.meshgrid(torch.arange(12, device=device), torch.arange(17, device=device), indexing="ij")
+ u = xs + ys
+ img = torch.where(u < 13, 0.0, torch.where(u == 13, 0.3, 1.0)).to(dtype)[None, None]
+ # relabel: mirrored in x, the step runs along x - y and the lines move with it
+ for image, mirrored in ((img, False), (img.flip(-1), True)):
+ _, edges = canny(image, 0.1, 0.2, kernel_size=1)
+ on = edges[0, 0].nonzero()
+ x = 16 - on[:, 1] if mirrored else on[:, 1]
+ assert set((on[:, 0] + x).tolist()) == {13, 14}
+
+ def test_convention_canny_tied_step_keeps_its_left_or_upper_pixel_5170(self, device, dtype):
+ """Of the two equal-magnitude pixels across a two-level step, the left (upper) one is the edge."""
+ self._require_padding(device, dtype)
+ # 0 | 1 between x = 6 and x = 7 of a 9x14 image, no blur: the raw Sobel magnitudes of x = 6 and x = 7 tie at 4
+ step = torch.zeros(1, 1, 9, 14, device=device, dtype=dtype)
+ step[..., 7:] = 1.0
+ expected = torch.zeros_like(step)
+ expected[..., 6] = 1.0
+ # the rule is positional: the dark-to-bright and the bright-to-dark step keep the same pixel
+ for img in (step, 1.0 - step):
+ _, edges = canny(img, kernel_size=1)
+ self.assert_close(edges, expected)
+ # relabel: transposed, the upper pixel of the tie is kept
+ _, edges_t = canny(img.transpose(-1, -2), kernel_size=1)
+ self.assert_close(edges_t, expected.transpose(-1, -2))
+
+ def test_convention_canny_thresholds_have_no_upper_bound_5171(self, device, dtype):
+ """The thresholds are in unnormalized Sobel units, which reach 4 on a [0, 1] image, and are not capped at 1."""
+ self._require_padding(device, dtype)
+ img = self._ramped_step(1.0, device, dtype) # the ridge at x = 7 has magnitude 4
+ ridge = torch.zeros_like(img)
+ ridge[..., 7] = 1.0
+ for low, high, expected in ((2.0, 3.0, ridge), (2.0, 4.5, 0.5 * ridge), (4.5, 5.0, 0.0 * ridge)):
+ _, edges = canny(img, low, high, kernel_size=1, hysteresis=False)
+ self.assert_close(edges, expected)
+ _, edges = Canny(low, high, kernel_size=1, hysteresis=False)(img)
+ self.assert_close(edges, expected)
+
+ def test_convention_canny_rejects_channel_counts_other_than_1_and_3_5171(self, device, dtype):
+ """Only C = 1 and C = 3 (read as RGB) are accepted; any other channel count raises a kornia ImageError."""
+ for channels in (2, 4):
+ with pytest.raises(ImageError):
+ canny(torch.rand(1, channels, 12, 13, device=device, dtype=dtype))
+ with pytest.raises(ImageError):
+ Canny()(torch.rand(1, channels, 12, 13, device=device, dtype=dtype))
+
+ def test_wart_canny_integer_input_finds_no_edge_5155(self, device, dtype):
+ """#5155: an integer image is not converted to a floating dtype, and the default blur truncates it to zeros."""
+ if device.type != "cpu":
+ pytest.skip("integer convolution raises on this device, so there is no truncated result to pin (#5155)")
+ self._require_padding(device, dtype)
+ # the ramped step 0 | 6 | 10: in a floating dtype its blurred ridge, about 26, gives one edge pixel per row
+ img = self._ramped_step(10.0, device, torch.float64)
+ _, edges = canny(img.to(dtype), 5.0, 10.0)
+ assert edges[0, 0].nonzero()[:, 1].tolist() == [7] * 9
+ for int_dtype in (torch.int16, torch.int32, torch.int64):
+ _, edges = canny(img.to(int_dtype), 5.0, 10.0)
+ assert edges.count_nonzero().item() == 0
diff --git a/tests/filters/test_in_range.py b/tests/filters/test_in_range.py
index de09891f2..6f92a5e1c 100644
--- a/tests/filters/test_in_range.py
+++ b/tests/filters/test_in_range.py
@@ -489,3 +489,82 @@ class TestInRange(BaseTester):
op = InRange(lower=lower, upper=upper, return_mask=True)
op_optimized = torch_optimizer(op, fullgraph=True)
self.assert_close(op(data), op_optimized(data))
+
+
+class TestConventionsInRange(BaseTester):
+ def test_convention_in_range_bounds_inclusive_and_all_channels_must_pass(self, device, dtype):
+ # built in the test dtype so that a value equal to a bound is equal after rounding
+ row = [0.2, 0.5, 0.8, 0.9]
+ img = torch.tensor([[row, row]] * 3, device=device, dtype=dtype)[None] # (1, 3, 2, 4), H != W
+ img[0, 2, 1, 1] = 0.95 # above channel 2's upper bound 0.9 at one pixel only
+ img[0, 0, 1, 0] = float("nan") # at a pixel that is otherwise in range
+ img[0, 1, 0, 3] = float("inf") # at a pixel that fails anyway (0.9 > 0.8)
+ lower, upper = (0.2, 0.2, 0.2), (0.8, 0.8, 0.9)
+ mask = in_range(img, lower, upper, return_mask=True)
+ # both bounds inclusive (0.2 and 0.8 pass), a pixel passes only if every channel does, NaN fails;
+ # the mask is (B, 1, H, W) in the input dtype with 1 (not 255) for a pass
+ expected = torch.tensor([[[[1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 0.0]]]], device=device, dtype=dtype)
+ assert mask.dtype == dtype
+ self.assert_close(mask, expected)
+ # return_mask=False is input * mask: a failing pixel's channels become 0, a NaN stays NaN and an inf becomes NaN
+ out = in_range(img, lower, upper)
+ assert out[0, 0, 1, 0].isnan()
+ self.assert_close(out[0, 1:, 1, 0], torch.zeros(2, device=device, dtype=dtype))
+ assert out[0, 1, 0, 3].isnan()
+ self.assert_close(out[0, [0, 2], 0, 3], torch.zeros(2, device=device, dtype=dtype))
+ self.assert_close(out.nan_to_num(), (img * expected).nan_to_num())
+ # relabel: transposing the image transposes the mask
+ self.assert_close(in_range(img.transpose(-1, -2), lower, upper, return_mask=True), expected.transpose(-1, -2))
+ # lower > upper is not rejected; it selects nothing
+ assert in_range(img, upper, lower, return_mask=True).sum().item() == 0
+
+ def test_convention_in_range_casts_floating_bounds_before_checking_order(self, device, dtype):
+ """A floating interval is reversed only if it remains so after conversion to the input dtype."""
+ if dtype == torch.float64:
+ pytest.skip("A Python float cannot express a value strictly between adjacent float64 values at one.")
+
+ # The wider lower bound is above upper, but the gap is less than half an input ULP, so both become 1.
+ lower, upper = 1.0 + torch.finfo(dtype).eps / 4, 1.0
+ image = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)
+ expected = torch.ones_like(image)
+ self.assert_close(in_range(image, (lower,), (upper,), return_mask=True), expected)
+ self.assert_close(
+ in_range(
+ image,
+ torch.tensor([lower], dtype=torch.float64),
+ torch.tensor([upper], dtype=torch.float64),
+ return_mask=True,
+ ),
+ expected,
+ )
+
+ def test_convention_in_range_rounds_fractional_bounds_on_integer_input_5423(self, device, dtype):
+ """#5423: fractional lower bounds round up and fractional upper bounds round down for integer inputs."""
+ # a floating image keeps lower <= input <= upper: the value 100 lies below the lower bound 100.7
+ values = torch.tensor([100, 101, 200, 201], device=device, dtype=torch.uint8).view(1, 1, 1, 4)
+ as_float = in_range(values.to(dtype), (100.7,), (200.2,), return_mask=True)
+ assert as_float.flatten().tolist() == [0, 1, 1, 0]
+ # uint8 with tuple bounds has the same comparisons: lower=100.7 rounds to 101 and upper=200.2 to 200
+ as_uint8 = in_range(values, (100.7,), (200.2,), return_mask=True)
+ assert as_uint8.dtype == torch.uint8
+ assert as_uint8.flatten().tolist() == [0, 1, 1, 0]
+ # int16 Tensor bounds follow the same rule: upper=-3.5 rounds down to -4, rejecting -3
+ negative = torch.tensor([-4, -3, -2], device=device, dtype=torch.int16).view(1, 1, 1, 3)
+ lower, upper = torch.tensor([-10.0], device=device), torch.tensor([-3.5], device=device)
+ assert in_range(negative, lower, upper, return_mask=True).flatten().tolist() == [1, 0, 0]
+
+ def test_convention_in_range_checks_each_tensor_bound_shape_5176(self, device, dtype):
+ """Each Tensor bound is checked on its own, and a 1-D bound is read per channel, never per column."""
+ generator = torch.Generator().manual_seed(0)
+ img = torch.rand(2, 3, 4, 5, generator=generator).to(device=device, dtype=dtype) # C = 3, W = 5
+ per_sample = torch.zeros(2, 3, 1, 1, device=device, dtype=dtype)
+ per_column = torch.tensor([1.0, 1.0, 1.0, 1.0, 0.0], device=device, dtype=dtype)
+ # a (W,) bound is rejected whichever bound it is, even beside a valid (B, C, 1, 1) one
+ with pytest.raises(ValueError):
+ in_range(img, per_sample, per_column, return_mask=True)
+ with pytest.raises(ValueError):
+ in_range(img, per_column - 1, per_sample + 1, return_mask=True)
+ # a (C,) bound applies to its channel: channel 2's upper bound 0.5 decides the mask
+ per_channel = torch.tensor([1.0, 1.0, 0.5], device=device, dtype=dtype)
+ mask = in_range(img, per_sample, per_channel, return_mask=True)
+ self.assert_close(mask, (img[:, 2:] <= 0.5).to(dtype))
diff --git a/tests/filters/test_laplacian.py b/tests/filters/test_laplacian.py
index 0d3a97fc9..98ae9b50f 100644
--- a/tests/filters/test_laplacian.py
+++ b/tests/filters/test_laplacian.py
@@ -24,7 +24,13 @@ from kornia.core.exceptions import BaseError
from kornia.filters import Laplacian, filter2d, get_laplacian_kernel1d, get_laplacian_kernel2d, laplacian
from kornia.filters.kernels import normalize_kernel2d
-from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, assert_close, dynamo_is_available
+from testing.base import (
+ DYNAMO_UNAVAILABLE_REASON,
+ BaseTester,
+ assert_close,
+ dynamo_is_available,
+ supports_reflect_padding,
+)
laplacian_module = importlib.import_module("kornia.filters.laplacian")
@@ -275,3 +281,86 @@ class TestLaplacian(BaseTester):
op_optimized = torch_optimizer(op)
self.assert_close(op(data), op_optimized(data))
+
+
+class TestConventionsLaplacian(BaseTester):
+ @staticmethod
+ def _require_reflect_padding(device, dtype):
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("torch has no reflect padding kernel for this device and dtype")
+
+ def test_convention_laplacian_kernel_sign_and_normalization(self, device, dtype):
+ self._require_reflect_padding(device, dtype)
+ # delta off centre in a 7x10 image; kernel_size is (kH, kW) = (3, 5), all ones with centre 1 - kH * kW
+ delta = torch.zeros(1, 1, 7, 10, device=device, dtype=dtype)
+ delta[0, 0, 2, 6] = 1.0
+ raw = laplacian(delta, (3, 5), normalized=False)
+ expected = torch.zeros_like(delta)
+ expected[0, 0, 1:4, 4:9] = 1.0
+ expected[0, 0, 2, 6] = -14.0 # negative at a bright peak
+ self.assert_close(raw, expected)
+ # the default normalized=True divides by the kernel's absolute sum, 2 * (kH * kW - 1) = 28
+ self.assert_close(laplacian(delta, (3, 5)), expected / 28)
+ # relabel: transposing the image and the kernel size transposes the output
+ self.assert_close(laplacian(delta.transpose(-1, -2), (5, 3), normalized=False), raw.transpose(-1, -2))
+ # normalized is not derivative units: x^2/2 + y^2/2 has a Laplacian of 2, the k=3 output is 6 / 16
+ ys, xs = torch.meshgrid(
+ torch.arange(7, device=device, dtype=dtype), torch.arange(10, device=device, dtype=dtype), indexing="ij"
+ )
+ bowl = ((xs - 4) ** 2 / 2 + (ys - 2) ** 2 / 2)[None, None]
+ self.assert_close(
+ laplacian(bowl, 3, normalized=False)[0, 0, 3, 5], torch.tensor(6.0, device=device, dtype=dtype)
+ )
+ self.assert_close(laplacian(bowl, 3)[0, 0, 3, 5], torch.tensor(0.375, device=device, dtype=dtype))
+
+ def test_convention_laplacian_default_border_is_reflect(self, device, dtype):
+ self._require_reflect_padding(device, dtype)
+ # an x-ramp's Laplacian is 0 inside; at x = 0 torch's reflect gives 0.375, replicate 0.1875
+ ramp = (torch.arange(10, device=device, dtype=dtype) + 1).expand(1, 1, 7, 10)
+ out = laplacian(ramp, 3)
+ self.assert_close(out, laplacian(ramp, 3, border_type="reflect"))
+ self.assert_close(out[0, 0, 3, [0, 5]], torch.tensor([0.375, 0.0], device=device, dtype=dtype))
+
+ def test_convention_laplacian_rejects_kernel_size_one_5175(self, device, dtype):
+ """kernel_size needs 3 or more taps along one axis: 1 and (1, 1) raise, (1, 3) is accepted."""
+ self._require_reflect_padding(device, dtype)
+ data = torch.rand(1, 1, 5, 6, device=device, dtype=dtype)
+ for kernel_size in (1, (1, 1)):
+ with pytest.raises(BaseError):
+ laplacian(data, kernel_size)
+ with pytest.raises(BaseError):
+ Laplacian(kernel_size)
+ # a 1 x 3 kernel is the 1-D stencil [1, -2, 1] along x, divided by its absolute sum 4
+ ramp = (torch.arange(6, device=device, dtype=dtype) ** 2).expand(1, 1, 5, 6)
+ self.assert_close(laplacian(ramp, (1, 3))[0, 0, 2, 1:-1], torch.full((4,), 0.5, device=device, dtype=dtype))
+
+ def test_wart_laplacian_integer_input_returns_zeros_5155(self, device, dtype):
+ """#5155: the kernel takes the integer input's dtype, so the normalised taps truncate to 0."""
+ if device.type != "cpu":
+ pytest.skip("integer convolution raises on this device, so there is no truncated result to pin (#5155)")
+ self._require_reflect_padding(device, dtype)
+ img = torch.full((1, 1, 5, 7), 100, device=device, dtype=torch.uint8)
+ img[0, 0, 2, 3] = 180
+ # in a float dtype: (8 * 100 - 8 * 180) / 16 = -40 at the bright pixel, (180 - 100) / 16 = 5 beside it
+ reference = laplacian(img.to(dtype), 3)[0, 0, [2, 1], [3, 3]]
+ self.assert_close(reference, torch.tensor([-40.0, 5.0], device=device, dtype=dtype))
+ # every tap of the normalised kernel is below 1 in magnitude (1/16 and -8/16 in int16; 1/256 and 248/256 in
+ # uint8, whose centre wraps) and truncates to 0, so the wrap does not decide the result
+ for int_dtype in (torch.uint8, torch.int16):
+ assert laplacian(img.to(int_dtype), 3).count_nonzero().item() == 0
+ # unnormalised, the taps survive but the sum is uint8 arithmetic: -640 at the bright pixel reads -640 mod 256
+ assert laplacian(img, 3, normalized=False)[0, 0, 2, 3].item() == 128
+
+ def test_convention_laplacian_border_type_is_case_insensitive_5156(self, device, dtype):
+ """border_type is case-insensitive: 'REFLECT' and 'Reflect' pad as 'reflect' does, and so for every mode."""
+ self._require_reflect_padding(device, dtype)
+ generator = torch.Generator().manual_seed(0)
+ data = torch.rand(1, 1, 7, 10, generator=generator).to(device=device, dtype=dtype)
+ outputs = {}
+ for border_type in ("reflect", "circular", "constant"):
+ outputs[border_type] = laplacian(data, 3, border_type=border_type)
+ for spelling in (border_type.upper(), border_type.capitalize()):
+ self.assert_close(laplacian(data, 3, border_type=spelling), outputs[border_type])
+ # the modes differ on the border, so a spelling that fell back to another mode would be seen
+ assert not torch.allclose(outputs["reflect"], outputs["circular"])
+ assert not torch.allclose(outputs["reflect"], outputs["constant"])
diff --git a/tests/filters/test_otsu_thresholding.py b/tests/filters/test_otsu_thresholding.py
index 3c07f868a..22e8f2100 100644
--- a/tests/filters/test_otsu_thresholding.py
+++ b/tests/filters/test_otsu_thresholding.py
@@ -766,8 +766,8 @@ class TestOtsuThresholdDifferentiable(BaseTester):
# bin: 0 <= slow - fast <= one bin, plus the rounding of both thresholds to the dtype (the two paths also
# compute the same edge with different float arithmetic, which differs in the last bits). Not a property of
# every image: two near-tied splits far apart can swap under any change of histogram estimator. The default
- # path runs on the CPU, where it takes the lowest of splits that give the same partition; on MPS its
- # cumulative sums can make a later one win (0.4766 instead of 0.4000 on the bimodal image, #5421).
+ # path takes the lowest of the splits that give the same partition on every device (#5421); it runs on the
+ # CPU here as the reference.
generator = torch.Generator().manual_seed(0)
noise = torch.rand(1000, generator=generator, dtype=torch.float64)
ramp_a = torch.linspace(0, 1, 60, dtype=torch.float64).square().view(1, 1, 6, 10)
@@ -858,3 +858,129 @@ class TestOtsuThresholdDifferentiable(BaseTester):
(actual_grad,) = torch.autograd.grad(actual.sum(), x)
assert actual_grad.isfinite().all()
self.assert_close(actual_grad, expected_grad)
+
+
+class TestConventionsOtsuThreshold(BaseTester):
+ def test_convention_otsu_threshold_per_plane_in_input_units_foreground_strictly_above(self, device, dtype):
+ # two well-separated clusters per plane, in input units (not [0, 1]); B = 2, C = 3, H != W
+ values = torch.tensor([20.0, 30.0, 40.0, 160.0, 170.0, 180.0])
+ plane = torch.stack([values.roll(i) for i in range(4)]).view(1, 1, 4, 6)
+ img = torch.cat([plane, plane.flip(-1) + 5, plane * 0.5], 1)
+ img = torch.cat([img, img + 7]).to(device=device, dtype=dtype).requires_grad_(True)
+ out, thresholds = otsu_threshold(img)
+ # one threshold per (b, c) plane, returned flat, in the input dtype
+ assert thresholds.shape == (6,)
+ assert thresholds.dtype == out.dtype == dtype
+ ordered = img.detach().view(6, -1).sort(dim=1).values # 12 low and 12 high pixels per plane
+ low_max, high_min = ordered[:, 11], ordered[:, 12]
+ # between the clusters (a threshold equal to the low cluster's top still drops it), at the lowest tied split
+ assert (thresholds >= low_max).all()
+ assert (thresholds < low_max + (high_min - low_max) / 4).all()
+ # the first output is x * (x > threshold), and its gradient is that mask
+ mask = img.detach() > thresholds.view(2, 3, 1, 1)
+ self.assert_close(out, img.detach() * mask)
+ (grad,) = torch.autograd.grad(out.sum(), img)
+ self.assert_close(grad, mask.to(dtype))
+ # relabel: transposing the image leaves the thresholds and transposes the output
+ out_t, thresholds_t = otsu_threshold(img.detach().transpose(-1, -2))
+ self.assert_close(thresholds_t, thresholds)
+ self.assert_close(out_t, out.detach().transpose(-1, -2))
+ # strictly above: on 0..255 the pixel equal to the threshold is dropped, the next value is kept
+ u8 = _bimodal_uint8_image(device)
+ out8, t8 = otsu_threshold(u8)
+ assert t8.dtype == torch.uint8
+ level = int(t8.item())
+ assert out8.flatten()[level].item() == 0
+ assert out8.flatten()[level + 1].item() == level + 1
+
+ @pytest.mark.parametrize("int_dtype", [torch.int8, torch.int16, torch.int32, torch.int64])
+ def test_convention_otsu_integer_threshold_is_the_largest_integer_below_the_edge(self, device, int_dtype):
+ # the threshold takes the input's dtype as the largest integer below the bin edge, so x > threshold keeps
+ # every pixel on or above the edge: the edges -59.69 and 40.31 give -60 (not -59, toward zero) and 40
+ img = torch.tensor([[-90, -80, -70], [-60, -50, -40], [-30, -20, -10]], device=device, dtype=int_dtype)
+ for data, expected in ((img, -60), (img + 100, 40)):
+ _, threshold = otsu_threshold(data)
+ assert threshold.dtype == int_dtype
+ assert threshold.item() == expected
+ _, edge = otsu_threshold(data.cpu().float())
+ assert expected < edge.item() < expected + 1
+ # an edge on an integer: two bins split 0..10 at 5, and the pixel of value 5, in the upper bin, is kept
+ out, threshold = otsu_threshold(torch.tensor([[0, 0, 5, 10, 10, 10]], device=device, dtype=int_dtype), nbins=2)
+ assert threshold.item() == 4
+ assert out.flatten().tolist() == [0, 0, 5, 10, 10, 10]
+
+ def test_convention_otsu_threshold_is_the_upper_edge_of_the_split_bin_5172(self, device, dtype):
+ """The threshold is the upper edge of the histogram bin where the split falls, in input units."""
+ # nbins=2 splits [0, 1] at its single inner edge 0.5, so the three pixels above it are kept
+ x = torch.tensor([[0.0, 0.1, 0.2, 0.55, 0.9, 1.0]], device=device, dtype=dtype)
+ out, threshold = otsu_threshold(x, nbins=2)
+ assert threshold.item() == 0.5
+ self.assert_close(out, x * (x > 0.5))
+ assert out.count_nonzero().item() == 3
+ # uint8: skimage.filters.threshold_otsu and cv2.THRESH_OTSU give 125 on this image
+ _, t8 = otsu_threshold(_bimodal_uint8_image(device))
+ assert t8.item() == 125
+
+ def test_convention_otsu_threshold_is_independent_of_batch_mates_5172(self, device, dtype):
+ """Each image and channel is histogrammed on its own [min, max], whatever else is in the call."""
+ a = (torch.linspace(0, 1, 60) ** 2).view(1, 1, 6, 10).to(device=device, dtype=dtype)
+ b = torch.linspace(0.6, 4.3, 60).view(1, 1, 6, 10).to(device=device, dtype=dtype)
+ alone = torch.cat([otsu_threshold(a)[1], otsu_threshold(b)[1]])
+ _, batched = otsu_threshold(torch.cat([a, b]))
+ _, channels = otsu_threshold(torch.cat([a, b], 1))
+ assert batched.tolist() == alone.tolist()
+ assert channels.tolist() == alone.tolist()
+
+ def test_convention_otsu_constant_plane_threshold_is_its_value_5172(self, device, dtype):
+ """A constant plane has no split: its threshold is its own value, so none of its pixels is foreground."""
+ for value in (0.4, -0.4):
+ img = torch.full((1, 1, 4, 5), value, device=device, dtype=dtype)
+ out, threshold = otsu_threshold(img)
+ assert threshold.item() == img[0, 0, 0, 0].item()
+ assert out.count_nonzero().item() == 0
+
+ def test_convention_otsu_return_mask_is_x_above_threshold_5173(self, device, dtype):
+ """return_mask=True returns the boolean x > threshold of each plane, so foreground values <= 0 count."""
+ x = torch.tensor([[[[-1.0, -1.0, 0.0, 0.0]]], [[[-2.0, -2.0, -1.0, -1.0]]]], device=device, dtype=dtype)
+ mask, threshold = otsu_threshold(x, return_mask=True)
+ assert mask.dtype == torch.bool
+ assert mask.shape == x.shape
+ # plane 1's foreground -1 lies below plane 0's threshold: each plane is compared with its own
+ assert mask.flatten().tolist() == [False, False, True, True] * 2
+ assert torch.equal(mask, x > threshold.view(2, 1, 1, 1))
+
+ def test_convention_otsu_equivalent_splits_pick_the_same_edge_on_mps_5421(self, device, dtype):
+ """#5421: empty bins do not add candidate splits, so MPS and CPU choose the same edge and mask."""
+ if device.type != "mps":
+ pytest.skip("#5421 compares the threshold computed on MPS with the one computed on the CPU")
+ # These x^3 samples left empty-bin gaps where rounding once selected a later split on MPS.
+ images = [torch.linspace(0, 1, 40).pow(3).view(1, 1, 4, 10), torch.linspace(0, 1, 48).pow(3).view(1, 1, 6, 8)]
+ for img in images:
+ img = img.to(dtype)
+ mask_cpu, threshold_cpu = otsu_threshold(img, return_mask=True)
+ mask_mps, threshold_mps = otsu_threshold(img.to(device), return_mask=True)
+ assert torch.equal(mask_mps.cpu(), mask_cpu)
+ self.assert_close(threshold_mps.cpu(), threshold_cpu, rtol=0, atol=0)
+
+ def test_convention_otsu_slow_path_threshold_has_a_gradient_and_counts_pixels_5174(self, device, dtype):
+ """#5174: the slow threshold has a surrogate gradient and counts pixels between the former KDE samples."""
+ generator = torch.Generator().manual_seed(0)
+ noise = torch.rand(1000, generator=generator)
+ x = torch.cat([0.3 + 0.1 * noise[:500], 0.6 + 0.1 * noise[500:]]).view(1, 1, 20, 50)
+ x = x.to(device=device, dtype=dtype).requires_grad_(True)
+ _, threshold = otsu_threshold(x, slow_and_differentiable=True)
+ assert threshold.requires_grad
+ (grad,) = torch.autograd.grad(threshold.sum(), x)
+ assert grad.isfinite().all()
+ assert grad.count_nonzero().item() > 0
+ # The former fixed-bandwidth KDE missed the 80 pixels at 0.3 or 0.7, producing the same threshold.
+ # Every pixel now contributes its bin mass, so both paths separate these images within one bin.
+ fast, slow = [], []
+ for mid in (0.3, 0.7):
+ img = torch.tensor([0.0] * 10 + [mid] * 80 + [1.0] * 10, device=device, dtype=dtype).view(1, 1, 1, -1)
+ fast.append(otsu_threshold(img, nbins=16)[1])
+ slow.append(otsu_threshold(img, nbins=16, slow_and_differentiable=True)[1])
+ assert fast[0] != fast[1]
+ assert slow[0] != slow[1]
+ for fast_threshold, slow_threshold in zip(fast, slow):
+ self.assert_close(fast_threshold, slow_threshold, rtol=0, atol=1 / 16)
diff --git a/tests/filters/test_sobel.py b/tests/filters/test_sobel.py
index 4b89f6fcb..b79a65f8a 100644
--- a/tests/filters/test_sobel.py
+++ b/tests/filters/test_sobel.py
@@ -633,3 +633,153 @@ class TestSobel(BaseTester):
op_optimized = torch_optimizer(op)
self.assert_close(op(data), op_optimized(data))
+
+
+class TestConventionsSpatialGradient(BaseTester):
+ @staticmethod
+ def _require_replicate_padding(device, dtype, three_d=False):
+ if not supports_replicate_padding(device, dtype) or (
+ three_d and not supports_replicate_padding_3d(device, dtype)
+ ):
+ pytest.skip("torch has no replicate padding kernel for this device and dtype")
+
+ @staticmethod
+ def _grid(h, w, device, dtype):
+ return torch.meshgrid(
+ torch.arange(h, device=device, dtype=dtype), torch.arange(w, device=device, dtype=dtype), indexing="ij"
+ )
+
+ def test_convention_spatial_gradient_normalized_ramp(self, device, dtype):
+ self._require_replicate_padding(device, dtype)
+ # H != W; an x-ramp of slope 3 and a y-ramp of slope 2, read at an interior pixel off the diagonal
+ ys, xs = self._grid(6, 9, device, dtype)
+ x_ramp = (3 * xs + 1)[None, None]
+ y_ramp = (2 * ys + 1)[None, None]
+ raw_scale = {"sobel": 8.0, "diff": 2.0}
+ for mode in ("sobel", "diff"):
+ # the default (normalized=True) is in derivative units; channel 0 = d/dx along W, 1 = d/dy along H (y down)
+ gx = spatial_gradient(x_ramp, mode)
+ gy = spatial_gradient(y_ramp, mode)
+ assert gx.shape == (1, 1, 2, 6, 9)
+ self.assert_close(gx[0, 0, :, 2, 5], torch.tensor([3.0, 0.0], device=device, dtype=dtype))
+ self.assert_close(gy[0, 0, :, 2, 5], torch.tensor([0.0, 2.0], device=device, dtype=dtype))
+ # normalized=False returns the raw kernel response: 8x for Sobel (as cv2.Sobel), 2x for diff
+ raw = spatial_gradient(x_ramp, mode, normalized=False)[0, 0, :, 2, 5]
+ self.assert_close(raw, torch.tensor([3.0 * raw_scale[mode], 0.0], device=device, dtype=dtype))
+ # relabel: transposing the image swaps the two channels and transposes each
+ gxt = spatial_gradient(x_ramp.transpose(-1, -2), mode)
+ self.assert_close(gxt[:, :, [1, 0]], gx.transpose(-1, -2))
+
+ def test_convention_spatial_gradient_second_order_channels(self, device, dtype):
+ self._require_replicate_padding(device, dtype)
+ # quadratics centred off the probe pixel (3, 4) of a 7x10 image; channels are (dxx, dxy, dyy)
+ ys, xs = self._grid(7, 10, device, dtype)
+ x, y = xs - 4, ys - 4
+ surfaces = torch.stack([x * x / 2, x * y, y * y / 2, x * x / 2 + 3 * x * y - y * y])[:, None]
+ exact = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 3.0, -2.0]])
+ raw_scale = {"sobel": torch.tensor([64.0, 64.0, 64.0]), "diff": torch.tensor([1.0, 4.0, 1.0])}
+ for mode in ("sobel", "diff"):
+ out = spatial_gradient(surfaces, mode, order=2)
+ self.assert_close(out[:, 0, :, 3, 4], exact.to(device, dtype))
+ raw = spatial_gradient(surfaces, mode, order=2, normalized=False)[:, 0, :, 3, 4]
+ self.assert_close(raw, (exact * raw_scale[mode]).to(device, dtype))
+ # relabel: transposing swaps dxx and dyy, dxy stays
+ out_t = spatial_gradient(surfaces.transpose(-1, -2), mode, order=2)
+ self.assert_close(out_t[:, :, [2, 1, 0]], out.transpose(-1, -2))
+
+ def test_convention_spatial_gradient_border_is_replicate(self, device, dtype):
+ self._require_replicate_padding(device, dtype, three_d=True)
+ # the border is replicated (not the reflect default of filter2d / laplacian), so a ramp's derivative at the
+ # first and last column is half its slope; reflect would give 0 there
+ ys, xs = self._grid(6, 9, device, dtype)
+ x_ramp = (3 * xs + 1)[None, None]
+ y_ramp = (2 * ys + 1)[None, None]
+ for mode in ("sobel", "diff"):
+ gx = spatial_gradient(x_ramp, mode)[0, 0, 0, 2]
+ self.assert_close(gx[[0, 4, 8]], torch.tensor([1.5, 3.0, 1.5], device=device, dtype=dtype))
+ gy = spatial_gradient(y_ramp, mode)[0, 0, 1, :, 4]
+ self.assert_close(gy[[0, 3, 5]], torch.tensor([1.0, 2.0, 1.0], device=device, dtype=dtype))
+ # The order-2 response has a different replicated-border convention: a linear ramp is zero only in its
+ # interior. This keeps the order-1 half-slope convention from being overgeneralized.
+ self.assert_close(
+ spatial_gradient(x_ramp, "diff", order=2)[0, 0, 0, 2],
+ torch.tensor([3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -3.0], device=device, dtype=dtype),
+ )
+ self.assert_close(
+ spatial_gradient(x_ramp, "sobel", order=2)[0, 0, 0, 2],
+ torch.tensor([1.5, 0.75, 0.0, 0.0, 0.0, 0.0, 0.0, -0.75, -1.5], device=device, dtype=dtype),
+ )
+ x_ramp3d = (3 * torch.arange(7, device=device, dtype=dtype) + 1).expand(1, 1, 5, 6, 7)
+ g3 = spatial_gradient3d(x_ramp3d)[0, 0, 0, 2, 3]
+ self.assert_close(g3[[0, 3, 6]], torch.tensor([1.5, 3.0, 1.5], device=device, dtype=dtype))
+ z_ramp3d = (5 * torch.arange(5, device=device, dtype=dtype) + 1).view(1, 1, 5, 1, 1).expand(1, 1, 5, 6, 7)
+ gz = spatial_gradient3d(z_ramp3d)[0, 0, 2, :, 3, 4]
+ self.assert_close(gz[[0, 2, 4]], torch.tensor([2.5, 5.0, 2.5], device=device, dtype=dtype))
+
+ def test_convention_spatial_gradient3d_channel_order(self, device, dtype):
+ self._require_replicate_padding(device, dtype, three_d=True)
+ # D != H != W (5, 6, 7); first order (dx, dy, dz) along (W, H, D), always in derivative units
+ zs, ys, xs = torch.meshgrid(
+ torch.arange(5, device=device, dtype=dtype),
+ torch.arange(6, device=device, dtype=dtype),
+ torch.arange(7, device=device, dtype=dtype),
+ indexing="ij",
+ )
+ ramps = torch.stack([3 * xs + 1, 2 * ys + 1, 5 * zs + 1])[:, None]
+ first = spatial_gradient3d(ramps)
+ assert first.shape == (3, 1, 3, 5, 6, 7)
+ expected = torch.tensor([[3.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 5.0]], device=device, dtype=dtype)
+ self.assert_close(first[:, 0, :, 2, 3, 4], expected)
+ # relabel: swapping D and W swaps dx and dz
+ first_t = spatial_gradient3d(ramps.transpose(-1, -3))
+ self.assert_close(first_t[:, :, [2, 1, 0]], first.transpose(-1, -3))
+ # second order: pure terms first, (dxx, dyy, dzz, dxy, dyz, dxz), unlike the 2-D (dxx, dxy, dyy)
+ x, y, z = xs - 4, ys - 2, zs - 1
+ quadratics = torch.stack([x * x / 2, y * y / 2, z * z / 2, x * y, y * z, x * z])[:, None]
+ second = spatial_gradient3d(quadratics, order=2)[:, 0, :, 2, 3, 4]
+ self.assert_close(second, torch.eye(6, device=device, dtype=dtype))
+
+ def test_convention_spatial_gradient3d_sobel_mode_raises(self, device, dtype):
+ # 'diff' is the default and the only implemented 3-D mode
+ volume = torch.rand(1, 1, 5, 6, 7, device=device, dtype=dtype)
+ with pytest.raises(NotImplementedError):
+ spatial_gradient3d(volume, mode="sobel")
+ with pytest.raises(NotImplementedError):
+ SpatialGradient3d(mode="sobel")
+
+ def test_convention_sobel_magnitude_of_normalized_gradient_eps_inside_root(self, device, dtype):
+ self._require_replicate_padding(device, dtype)
+ # sobel = sqrt(gx^2 + gy^2 + eps) of the normalized gradient: slope (3, 2) -> sqrt(13), not 8 * sqrt(13)
+ ys, xs = self._grid(6, 9, device, dtype)
+ plane = (3 * xs + 2 * ys + 1)[None, None]
+ interior = (..., slice(1, -1), slice(1, -1))
+ self.assert_close(sobel(plane)[interior], torch.full((1, 1, 4, 7), 13.0**0.5, device=device, dtype=dtype))
+ self.assert_close(sobel(-plane)[interior], torch.full((1, 1, 4, 7), 13.0**0.5, device=device, dtype=dtype))
+ self.assert_close(
+ sobel(plane, normalized=False)[interior],
+ torch.full((1, 1, 4, 7), 8 * 13.0**0.5, device=device, dtype=dtype),
+ )
+ self.assert_close(
+ sobel(-plane, normalized=False)[interior],
+ torch.full((1, 1, 4, 7), 8 * 13.0**0.5, device=device, dtype=dtype),
+ )
+ # eps sits inside the root: a flat image returns sqrt(eps), not 0
+ flat = torch.full((1, 1, 6, 9), 0.3, device=device, dtype=dtype)
+ self.assert_close(sobel(flat), torch.full_like(flat, 1e-3))
+ self.assert_close(sobel(flat, eps=0.0), torch.zeros_like(flat))
+
+ def test_convention_spatial_gradient_mode_is_case_insensitive_5156(self, device, dtype):
+ """mode is case-insensitive: 'Sobel' and 'DIFF' give the results of 'sobel' and 'diff'."""
+ self._require_replicate_padding(device, dtype, three_d=True)
+ generator = torch.Generator().manual_seed(0)
+ img = torch.rand(1, 1, 6, 9, generator=generator).to(device=device, dtype=dtype)
+ for order in (1, 2):
+ sobel_out = spatial_gradient(img, "sobel", order)
+ diff_out = spatial_gradient(img, "diff", order)
+ assert not torch.allclose(sobel_out, diff_out) # the spelling decides which operator runs
+ self.assert_close(spatial_gradient(img, "Sobel", order), sobel_out)
+ self.assert_close(spatial_gradient(img, "DIFF", order), diff_out)
+ volume = torch.rand(1, 1, 5, 6, 7, generator=generator).to(device=device, dtype=dtype)
+ for order in (1, 2):
+ self.assert_close(spatial_gradient3d(volume, "Diff", order), spatial_gradient3d(volume, "diff", order))
+ self.assert_close(SpatialGradient3d("Diff")(volume), spatial_gradient3d(volume))