Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(morphology): Convention blocks and pins for the seven morphology functions (batch 7) (#4743)

Dmytro Mishkin57cd68e6fe1c
diff --git a/changelog.d/4743.added.md b/changelog.d/4743.added.md
new file mode 100644
index 000000000..0cfb2ab18
--- /dev/null
+++ b/changelog.d/4743.added.md
@@ -0,0 +1,6 @@
+Document the conventions of `kornia.morphology` β€” the kernel reflection in `dilation` and its absence in
+`erosion`, the membership-mask `kernel` and additive `structuring_element`, the `[row, col]` `origin` and its
+even-size default, and the five `border_type` values with their scipy / scikit-image names (and OpenCV's for
+`geodesic` and `reflect`) β€” as Convention blocks on the seven public functions and a new section on the Conventions &
+Pitfalls page, with executable tests for the kornia-side claims and for the `max_val` sentinel, non-float
+operand and convolution-engine dtype warts.
diff --git a/changelog.d/4743.fixed.md b/changelog.d/4743.fixed.md
new file mode 100644
index 000000000..ac152f972
--- /dev/null
+++ b/changelog.d/4743.fixed.md
@@ -0,0 +1,3 @@
+Corrected the `kornia.morphology` docstrings: `origin` defaults to `[k_h // 2, k_w // 2]` rather than
+"the center ... (rounding towards zero)", the `Returns` section of `bottom_hat` names the bottom hat rather than
+the top hat, and the kernel shape is `(k_h, k_w)` over the image's `(H, W)` axes rather than `(k_x, k_y)`.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 0dfc26b51..ff8b118fa 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -465,6 +465,55 @@ Serializing an augmentation
forward replaces the pending state. Unchanged inherited implementations
keep the compact metadata state. See :doc:`/augmentation.base` for details.
+Morphology
+----------
+
+- :func:`kornia.morphology.dilation` **reflects** the structuring element (the Minkowski convention, as in
+ ``scipy.ndimage``); :func:`kornia.morphology.erosion` does not. For an asymmetric kernel scikit-image returns
+ kornia's dilation by the *flipped* kernel, and OpenCV's ``anchor=(a_x, a_y)`` returns that dilation at
+ ``origin=[k_h - 1 - a_y, k_w - 1 - a_x]``, which at its default anchor is the default origin for an odd size and
+ one cell earlier for an even one.
+- ``origin`` is the ``[row, col]`` index of the structuring-element cell placed on the output pixel, not an offset
+ from the centre, and OpenCV's ``anchor`` is the same index in ``(x, y)`` order for erosion (for dilation see the
+ flip above). The default is ``[k_h // 2, k_w // 2]`` for even sizes too.
+- ``border_type``'s ``reflect`` does not mean what the same word means in scipy and scikit-image (``constant``
+ does): torch's ``reflect`` is their ``mirror``, while their own ``reflect`` -- also their default -- repeats the
+ edge sample and has no kornia spelling. See :func:`kornia.morphology.dilation` for the full convention block.
+
+.. list-table::
+ :header-rows: 1
+
+ * - Behaviour
+ - kornia
+ - ``scipy.ndimage``
+ - scikit-image
+ - OpenCV
+ * - ``dilation`` reflects the kernel
+ - yes
+ - yes
+ - no
+ - no
+ * - ``dilation`` by ``ones(2, 2)`` of a hot pixel at ``(2, 3)``
+ - rows 1-2, cols 2-3
+ - rows 1-2, cols 2-3
+ - rows 1-2, cols 2-3
+ - rows 2-3, cols 3-4
+ * - origin/anchor semantics
+ - ``[row, col]`` index
+ - offset from ``k // 2``
+ - not exposed
+ - ``(x, y)`` index
+ * - default border
+ - ``geodesic`` (ignore outside)
+ - ``reflect`` (scipy's own rule, **not** torch's ``reflect``)
+ - ``reflect`` (same rule as scipy's)
+ - ignore outside
+ * - name of torch's ``reflect``
+ - ``reflect``
+ - ``mirror``
+ - ``mirror``
+ - ``BORDER_REFLECT_101``
+
Pitfall checklist
-----------------
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index 40e049ca9..d801e43c4 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -157,20 +157,106 @@ def dilation(
The kernel must have 2 dimensions.
+ Convention:
+ See :doc:`Conventions & Pitfalls </get-started/conventions>` for the table that compares the
+ reflection, centring and border rules of ``kornia.morphology`` with scipy, scikit-image and OpenCV.
+
+ - ``kernel`` is a flat **membership mask** of shape :math:`(k_h, k_w)`, laid over the image's
+ :math:`(H, W)` axes. Every non-zero entry is a member of the neighborhood and its magnitude is
+ ignored, so negative and fractional entries are members too; use ``structuring_element`` for
+ weights. Entries of ``structuring_element`` under a zero ``kernel`` cell do not reach the output.
+ - ``dilation`` **reflects** the structuring element. It is the Minkowski dilation
+ :math:`\delta_B f(x) = \max_{b \in B} f(x - b)`, the convention of ``scipy.ndimage.grey_dilation``.
+ scikit-image does not reflect, so for an asymmetric kernel it returns kornia's dilation by the
+ flipped kernel. OpenCV does not reflect either, so ``anchor=(a_x, a_y)`` returns kornia's dilation
+ by the flipped kernel at ``origin=[k_h - 1 - a_y, k_w - 1 - a_x]``; its default anchor gives
+ ``origin=[(k_h - 1) // 2, (k_w - 1) // 2]``, the default origin for an odd-sized kernel and one cell
+ earlier for an even-sized one.
+ :func:`erosion` does not reflect; scipy and OpenCV agree with it for odd and even sizes alike,
+ while scikit-image centres an even-sized footprint one cell earlier, so
+ ``skimage.morphology.erosion`` matches kornia's ``erosion`` at that same ``origin``.
+ - ``origin`` is the ``[row, col]`` index of the structuring-element cell placed on the output pixel,
+ defaulting to ``[k_h // 2, k_w // 2]`` for odd and for even sizes alike. scipy spells the same
+ choice as an offset from ``k // 2``, and OpenCV's ``anchor`` is an index in ``(x, y)`` order.
+ - ``border_type="geodesic"`` (the default) ignores the pixels outside the image, which is
+ scikit-image's ``mode="ignore"`` and OpenCV's default border. scikit-image's own default is
+ ``mode="reflect"``, so a comparison against it has to pass ``mode="ignore"`` explicitly. scipy has
+ no such mode: ``mode="constant"`` with ``cval=-np.inf`` for ``grey_dilation`` and ``cval=np.inf``
+ for ``grey_erosion`` reproduces it. Each of the three matches this border rule on every window
+ that holds an in-image kernel cell, and only while :math:`|x|` stays well below ``max_val``
+ (see the first warning).
+ - The other border modes carry torch's names, which do not match scipy's and scikit-image's:
+ ``reflect`` is their ``mirror``, ``replicate`` their ``nearest`` and ``circular`` their ``wrap``,
+ while their ``reflect`` is a rule this function has no name for. ``geodesic`` is not ``replicate``:
+ the two can differ once the structuring element can reach outside the image, including when its origin
+ cell is a member and the gaps are elsewhere (``kernel=[[1, 0, 1, 0, 1]]``). They coincide for a
+ rectangle of ones with a flat structuring element and :math:`|x|` well below ``max_val``, where
+ every pixel the replicate pad duplicates is already in the window; a non-flat
+ ``structuring_element`` adds a different value to the duplicate, and ``engine="convolution"`` rounds
+ the two pads differently.
+ - :func:`opening` and :func:`closing` reuse ``kernel`` in both halves, so under
+ ``border_type="geodesic"`` or ``"circular"``, with a flat structuring element and any engine but
+ ``"convolution"``, they are morphological openings and closings *up to the* ``max_val``
+ *sentinel*: under ``geodesic`` a window that reaches outside the image can leave ``x - max_val``
+ (``x + max_val`` in an erosion) in the output, and the later stage that adds (subtracts) ``max_val``
+ back returns ``x`` quantised to that sentinel's spacing. While :math:`|x|` stays well below
+ ``max_val``, anti-extensivity, extensivity and idempotence can then miss by a fraction of that
+ spacing (``circular`` pads real pixels and, for a kernel with a non-zero cell, misses nothing); once
+ :math:`|x|` approaches ``max_val`` the sentinel clips the data instead and they miss by the clip (see
+ the first warning below). :func:`opening` lists what the other borders, a non-flat
+ ``structuring_element`` and ``engine="convolution"`` break.
+ :func:`top_hat` and :func:`bottom_hat` are their one-line definitions (``tensor - opening`` and
+ ``closing - tensor``), and :func:`gradient` is the one-line ``dilation - erosion``. The kernel,
+ origin and border conventions above apply to all seven.
+
+ .. warning::
+ ``max_val`` is a finite stand-in for infinity, not an infinity. It is carried into the masked-out
+ neighborhood cells, so such a cell contributes ``x - max_val`` in :func:`dilation` and
+ ``x + max_val`` in :func:`erosion`, and under the default ``border_type="geodesic"`` it is also
+ padded into the border -- ``-max_val`` in :func:`dilation`, ``+max_val`` in :func:`erosion`. It
+ therefore reaches the output whenever a geodesic window is empty or the range of ``x`` plus
+ ``structuring_element`` approaches it, and the geodesic pad bounds the accuracy of
+ ``engine="convolution"``. The same sentinel is used in all seven functions. Keep it well above that
+ range and finite in the operands' dtypes (at most 65504 for ``float16``); a larger value raises or
+ rounds depending on the backend and the torch release.
+ Tracked in `#4734 <https://github.com/kornia/kornia/issues/4734>`_.
+
+ .. warning::
+ Only floating-point images are supported. On one, a ``bool`` or integer ``kernel`` takes the image's
+ dtype and is only a membership mask: it returns exactly what the same kernel in the image's dtype
+ returns, and with a floating ``structuring_element`` the kernel is only the ``kernel == 0`` mask.
+ A non-float image is not rejected yet; depending on the ``border_type``, the engine, the backend and
+ the torch release it raises, wraps the ``max_val`` sentinel, returns a wrong result or returns another
+ dtype. Tracked in `#4735 <https://github.com/kornia/kornia/issues/4735>`_.
+
+ The ``unfold`` and ``shift`` engines return the promoted dtype of ``tensor`` and ``kernel`` (or of
+ ``tensor`` and ``structuring_element``), while ``engine="convolution"`` casts the kernel and the
+ sentinel to the image's dtype and returns that dtype: a ``float16`` image with a ``float32`` kernel
+ comes back ``float32`` from ``unfold`` and ``shift`` but ``float16`` from ``convolution``
+ (`#4762 <https://github.com/kornia/kornia/issues/4762>`_).
+
Args:
tensor: Image with shape :math:`(B, C, H, W)`.
kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
- the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
- For full structural elements use torch.ones_like(structural_element).
- structuring_element: Structuring element used for the grayscale dilation. It may be a non-flat
- structuring element.
- origin: Origin of the structuring element. Default: ``None`` and uses the center of
- the structuring element as origin (rounding towards zero).
- border_type: It determines how the image borders are handled, where ``border_value`` is the value
- when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
- outside the image when applying the operation.
- border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
- max_val: The value of the infinite elements in the kernel.
+ the set of neighbors of the ``origin`` cell over which the operation is applied, and their
+ magnitude is ignored. Its shape is :math:`(k_h, k_w)`, laid over the image's :math:`(H, W)` axes.
+ For a full neighborhood pass a ``kernel`` of all ones.
+ structuring_element: Non-flat structuring element, added to the neighbor values before the maximum
+ in :func:`dilation` and subtracted before the minimum in :func:`erosion`. Its shape must equal
+ ``kernel``'s, and any other shape raises a ``ValueError``.
+ origin: ``[row, col]`` index of the structuring-element cell placed on the output pixel.
+ Default: ``None``, which uses ``[k_h // 2, k_w // 2]`` for odd and for even sizes alike
+ (``[1, 1]`` for a :math:`2 \times 2` kernel).
+ border_type: How the image borders are handled. Default: ``geodesic``, which ignores the values
+ that are outside the image when applying the operation. The other accepted values are the
+ :func:`torch.nn.functional.pad` modes ``constant``, ``reflect``, ``replicate`` and ``circular``.
+ ``reflect`` and ``circular`` additionally require the pad the kernel needs to stay below the
+ image size (``reflect``) or at most match it (``circular``), and raise a ``RuntimeError``
+ otherwise. Any other value raises a ``ValueError``.
+ border_value: Value to fill past edges of input. It is used only when ``border_type`` is
+ ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
+ under ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: Finite stand-in for the infinite elements of the kernel. See the first warning above.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -275,20 +361,57 @@ def erosion(
The kernel must have 2 dimensions.
+ Convention:
+ Conventions as in :func:`dilation`, with one difference: ``erosion`` does **not** reflect the
+ structuring element. It is the Minkowski erosion
+ :math:`\varepsilon_B f(x) = \min_{b \in B} f(x + b)`, the convention of ``scipy.ndimage.grey_erosion``,
+ ``skimage.morphology.erosion`` and ``cv2.erode``. scipy (with ``mode="constant", cval=np.inf``) and
+ OpenCV agree with kornia pixel for pixel for odd-sized and even-sized kernels alike wherever the window
+ holds at least one in-image cell of the kernel and :math:`|x|` stays well below ``max_val``;
+ scikit-image centres an even-sized footprint one cell earlier, so it matches kornia's ``erosion`` at
+ ``origin=[(k_h - 1) // 2, (k_w - 1) // 2]`` instead.
+ Under ``border_type="geodesic"`` a window with no in-image kernel cell is empty. scipy and
+ scikit-image return ``inf`` there, while kornia returns a finite value built from ``max_val`` and the
+ image (``-max_val`` and the image in :func:`dilation`), not an infinity; see the first warning in
+ :func:`dilation`.
+
+ Under ``border_type="geodesic"`` or ``"circular"``, with a flat structuring element and any engine but
+ ``"convolution"``, ``dilation`` and ``erosion`` with the same ``kernel`` and ``origin`` are an adjoint
+ pair -- ``dilation(x) <= y`` everywhere exactly when ``x <= erosion(y)`` everywhere -- while no window
+ is empty and :math:`|x|` stays well below ``max_val``. Otherwise the finite sentinel can break the
+ pair, and the ``constant``, ``reflect`` and ``replicate`` pads can break it with no window empty. The
+ duality of
+ ``dilation`` and ``erosion`` under negation is ``erosion(tensor, kernel, origin=origin)`` equals
+ ``-dilation(-tensor, kernel.flip((0, 1)), origin=[k_h - 1 - origin[0], k_w - 1 - origin[1]])``, which
+ is exact up to the sign of a zero for a flat structuring element and, under ``border_type="constant"``,
+ ``border_value=0``; a non-flat ``structuring_element`` has to be flipped with the kernel, and under
+ ``constant`` a non-zero ``border_value`` has to be negated (the other borders ignore it).
+
+ The two ``.. warning::`` blocks in :func:`dilation` describe this function too.
+
Args:
tensor: Image with shape :math:`(B, C, H, W)`.
kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
- the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
- For full structural elements use torch.ones_like(structural_element).
- structuring_element (torch.Tensor, optional): Structuring element used for the grayscale dilation.
- It may be a non-flat structuring element.
- origin: Origin of the structuring element. Default: ``None`` and uses the center of
- the structuring element as origin (rounding towards zero).
- border_type: It determines how the image borders are handled, where ``border_value`` is the value
- when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
- outside the image when applying the operation.
- border_value: Value to fill past edges of input if border_type is ``constant``.
- max_val: The value of the infinite elements in the kernel.
+ the set of neighbors of the ``origin`` cell over which the operation is applied, and their
+ magnitude is ignored. Its shape is :math:`(k_h, k_w)`, laid over the image's :math:`(H, W)` axes.
+ For a full neighborhood pass a ``kernel`` of all ones.
+ structuring_element: Non-flat structuring element, added to the neighbor values before the maximum
+ in :func:`dilation` and subtracted before the minimum in :func:`erosion`. Its shape must equal
+ ``kernel``'s, and any other shape raises a ``ValueError``.
+ origin: ``[row, col]`` index of the structuring-element cell placed on the output pixel.
+ Default: ``None``, which uses ``[k_h // 2, k_w // 2]`` for odd and for even sizes alike
+ (``[1, 1]`` for a :math:`2 \times 2` kernel).
+ border_type: How the image borders are handled. Default: ``geodesic``, which ignores the values
+ that are outside the image when applying the operation. The other accepted values are the
+ :func:`torch.nn.functional.pad` modes ``constant``, ``reflect``, ``replicate`` and ``circular``.
+ ``reflect`` and ``circular`` additionally require the pad the kernel needs to stay below the
+ image size (``reflect``) or at most match it (``circular``), and raise a ``RuntimeError``
+ otherwise. Any other value raises a ``ValueError``.
+ border_value: Value to fill past edges of input. It is used only when ``border_type`` is
+ ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
+ under ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: Finite stand-in for the infinite elements of the kernel. See the first warning in
+ :func:`dilation`.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -393,20 +516,61 @@ def opening(
The kernel must have 2 dimensions.
+ Convention:
+ ``opening`` is ``dilation(erosion(tensor))`` with the same ``kernel`` in both halves. Because
+ :func:`dilation` reflects the structuring element and :func:`erosion` does not, the composition is a
+ morphological opening -- anti-extensive and idempotent -- for an asymmetric kernel as well, within the
+ border, engine and structuring-element limits below and up to the ``max_val`` sentinel: while
+ :math:`|x|` stays well below ``max_val``, a window that reaches outside the image round-trips the
+ sentinel and can move a pixel by a fraction of its spacing; once :math:`|x|` approaches ``max_val``
+ the sentinel clips the data instead and the invariants miss by the clip (see the first warning in
+ :func:`dilation`).
+
+ With a flat structuring element, any ``engine`` but ``"convolution"`` (the default ``"auto"`` never
+ picks it), a ``border_type`` of ``geodesic``, ``replicate`` or ``circular`` and :math:`|x|` well
+ below ``max_val``, the invariants are exact for ``[[0, 1, 1]]`` and for
+ ``[[0, 0, 0], [0, 1, 1], [0, 1, 0]]`` at the default origin and for ``ones(3, 3)`` at
+ ``origin=[0, 0]``; the ``constant`` and ``reflect`` borders can break them even for those kernels,
+ and so can a non-flat ``structuring_element``, which is subtracted and added back and can round on
+ the way, and ``engine="convolution"`` wherever its ``conv2d`` rounds.
+ ``[[1, 0, 0]]``, whose window leaves the image on one side only, depends on the border: under the
+ default ``geodesic`` it can miss idempotence, and on negative data anti-extensivity too, by less than
+ one ULP of ``max_val`` in the image's dtype; under ``replicate`` it stays idempotent but is not
+ anti-extensive at all; under ``circular`` it is exact.
+
+ ``skimage.morphology.opening`` with ``mode="ignore"`` mirrors its footprint in the second half, so it
+ is this opening at ``origin=[(k_h - 1) // 2, (k_w - 1) // 2]``, where its erosion half anchors (see
+ :func:`erosion`): the default origin for an odd-sized kernel, one cell earlier for an even one. It is
+ bit-equal to ``opening`` at that origin on random frames for odd and even kernels alike while no
+ window is empty (an empty one returns an infinity there and a finite value here: the sentinel, or an
+ ordinary-looking one such as ``0``).
+ ``scipy.ndimage.grey_opening`` has no ignore mode, so it differs from ``opening`` at the border.
+ OpenCV's ``MORPH_OPEN`` composes without a flip, so it agrees with ``opening`` only for a kernel
+ symmetric about its anchor. Conventions otherwise as in :func:`dilation`.
+
Args:
tensor: Image with shape :math:`(B, C, H, W)`.
kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
- the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
- For full structural elements use torch.ones_like(structural_element).
- structuring_element: Structuring element used for the grayscale dilation. It may be a
- non-flat structuring element.
- origin: Origin of the structuring element. Default: ``None`` and uses the center of
- the structuring element as origin (rounding towards zero).
- border_type: It determines how the image borders are handled, where ``border_value`` is the value
- when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
- outside the image when applying the operation.
- border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
- max_val: The value of the infinite elements in the kernel.
+ the set of neighbors of the ``origin`` cell over which the operation is applied, and their
+ magnitude is ignored. Its shape is :math:`(k_h, k_w)`, laid over the image's :math:`(H, W)` axes.
+ For a full neighborhood pass a ``kernel`` of all ones.
+ structuring_element: Non-flat structuring element, added to the neighbor values before the maximum
+ in :func:`dilation` and subtracted before the minimum in :func:`erosion`. Its shape must equal
+ ``kernel``'s, and any other shape raises a ``ValueError``.
+ origin: ``[row, col]`` index of the structuring-element cell placed on the output pixel.
+ Default: ``None``, which uses ``[k_h // 2, k_w // 2]`` for odd and for even sizes alike
+ (``[1, 1]`` for a :math:`2 \times 2` kernel).
+ border_type: How the image borders are handled. Default: ``geodesic``, which ignores the values
+ that are outside the image when applying the operation. The other accepted values are the
+ :func:`torch.nn.functional.pad` modes ``constant``, ``reflect``, ``replicate`` and ``circular``.
+ ``reflect`` and ``circular`` additionally require the pad the kernel needs to stay below the
+ image size (``reflect``) or at most match it (``circular``), and raise a ``RuntimeError``
+ otherwise. Any other value raises a ``ValueError``.
+ border_value: Value to fill past edges of input. It is used only when ``border_type`` is
+ ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
+ under ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: Finite stand-in for the infinite elements of the kernel. See the first warning in
+ :func:`dilation`.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -423,7 +587,7 @@ def opening(
pass, which is more memory than ``"unfold"``, not less.
Returns:
- torch.Tensor: Opened image with shape :math:`(B, C, H, W)`.
+ Opened image with shape :math:`(B, C, H, W)`.
.. note::
See a working example `here <https://www.kornia.org/tutorials/nbs/morphology_101.html>`__.
@@ -483,20 +647,59 @@ def closing(
The kernel must have 2 dimensions.
+ Convention:
+ ``closing`` is ``erosion(dilation(tensor))`` with the same ``kernel`` in both halves, so it is a
+ morphological closing -- extensive and idempotent -- for an asymmetric kernel as well, within the
+ border, engine and structuring-element limits below and up to the ``max_val`` sentinel: while
+ :math:`|x|` stays well below ``max_val``, a window that reaches outside the image round-trips the
+ sentinel and can move a pixel by a fraction of its spacing; once :math:`|x|` approaches ``max_val``
+ the sentinel clips the data instead and the invariants miss by the clip (see the first warning in
+ :func:`dilation`).
+
+ With a flat structuring element, any ``engine`` but ``"convolution"`` (the default ``"auto"`` never
+ picks it), a ``border_type`` of ``geodesic``, ``replicate`` or ``circular`` and :math:`|x|` well
+ below ``max_val``, the invariants are exact for ``[[0, 1, 1]]`` and for
+ ``[[0, 0, 0], [0, 1, 1], [0, 1, 0]]`` at the default origin and for ``ones(3, 3)`` at
+ ``origin=[0, 0]``; the ``constant`` and ``reflect`` borders can break them even for those kernels,
+ and so can a non-flat ``structuring_element``, which is added and subtracted back and can round on
+ the way, and ``engine="convolution"`` wherever its ``conv2d`` rounds.
+ ``[[1, 0, 0]]``, whose window leaves the image on one side only, depends on the border: under the
+ default ``geodesic`` it can miss extensivity, and on negative data idempotence too, by less than one
+ ULP of ``max_val`` in the image's dtype; under ``replicate`` it stays idempotent but is not extensive
+ at all; under ``circular`` it is exact.
+
+ ``skimage.morphology.closing`` with ``mode="ignore"`` mirrors its footprint in the second half, which
+ makes it kornia's closing by the *flipped* kernel at the default origin -- bit-equal to
+ ``closing(x, kernel.flip((0, 1)))`` on random frames for odd-sized and even-sized kernels alike while
+ no window is empty (an empty one returns an infinity there and a finite value here: the sentinel, or
+ an ordinary-looking one) -- so it is a closing too, but a different one for an asymmetric kernel.
+ ``scipy.ndimage.grey_closing`` has no ignore mode, so it differs from ``closing`` at the border.
+ OpenCV's ``MORPH_CLOSE`` composes without a flip, so it agrees with ``closing`` only for a kernel
+ symmetric about its anchor. Conventions otherwise as in :func:`dilation`.
+
Args:
tensor: Image with shape :math:`(B, C, H, W)`.
kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
- the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
- For full structural elements use torch.ones_like(structural_element).
- structuring_element: Structuring element used for the grayscale dilation. It may be a
- non-flat structuring element.
- origin: Origin of the structuring element. Default is None and uses the center of
- the structuring element as origin (rounding towards zero).
- border_type: It determines how the image borders are handled, where ``border_value`` is the value
- when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
- outside the image when applying the operation.
- border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
- max_val: The value of the infinite elements in the kernel.
+ the set of neighbors of the ``origin`` cell over which the operation is applied, and their
+ magnitude is ignored. Its shape is :math:`(k_h, k_w)`, laid over the image's :math:`(H, W)` axes.
+ For a full neighborhood pass a ``kernel`` of all ones.
+ structuring_element: Non-flat structuring element, added to the neighbor values before the maximum
+ in :func:`dilation` and subtracted before the minimum in :func:`erosion`. Its shape must equal
+ ``kernel``'s, and any other shape raises a ``ValueError``.
+ origin: ``[row, col]`` index of the structuring-element cell placed on the output pixel.
+ Default: ``None``, which uses ``[k_h // 2, k_w // 2]`` for odd and for even sizes alike
+ (``[1, 1]`` for a :math:`2 \times 2` kernel).
+ border_type: How the image borders are handled. Default: ``geodesic``, which ignores the values
+ that are outside the image when applying the operation. The other accepted values are the
+ :func:`torch.nn.functional.pad` modes ``constant``, ``reflect``, ``replicate`` and ``circular``.
+ ``reflect`` and ``circular`` additionally require the pad the kernel needs to stay below the
+ image size (``reflect``) or at most match it (``circular``), and raise a ``RuntimeError``
+ otherwise. Any other value raises a ``ValueError``.
+ border_value: Value to fill past edges of input. It is used only when ``border_type`` is
+ ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
+ under ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: Finite stand-in for the infinite elements of the kernel. See the first warning in
+ :func:`dilation`.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -575,20 +778,33 @@ def gradient(
That means, (dilation - erosion) applying the same kernel in each channel.
The kernel must have 2 dimensions.
+ Convention:
+ ``gradient`` is ``dilation(tensor) - erosion(tensor)`` with the same ``kernel`` and the same
+ options, so the conventions of :func:`dilation` and :func:`erosion` apply to it unchanged.
+
Args:
tensor: Image with shape :math:`(B, C, H, W)`.
kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
- the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
- For full structural elements use torch.ones_like(structural_element).
- structuring_element: Structuring element used for the grayscale dilation. It may be a
- non-flat structuring element.
- origin: Origin of the structuring element. Default is None and uses the center of
- the structuring element as origin (rounding towards zero).
- border_type: It determines how the image borders are handled, where ``border_value`` is the value
- when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
- outside the image when applying the operation.
- border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
- max_val: The value of the infinite elements in the kernel.
+ the set of neighbors of the ``origin`` cell over which the operation is applied, and their
+ magnitude is ignored. Its shape is :math:`(k_h, k_w)`, laid over the image's :math:`(H, W)` axes.
+ For a full neighborhood pass a ``kernel`` of all ones.
+ structuring_element: Non-flat structuring element, added to the neighbor values before the maximum
+ in :func:`dilation` and subtracted before the minimum in :func:`erosion`. Its shape must equal
+ ``kernel``'s, and any other shape raises a ``ValueError``.
+ origin: ``[row, col]`` index of the structuring-element cell placed on the output pixel.
+ Default: ``None``, which uses ``[k_h // 2, k_w // 2]`` for odd and for even sizes alike
+ (``[1, 1]`` for a :math:`2 \times 2` kernel).
+ border_type: How the image borders are handled. Default: ``geodesic``, which ignores the values
+ that are outside the image when applying the operation. The other accepted values are the
+ :func:`torch.nn.functional.pad` modes ``constant``, ``reflect``, ``replicate`` and ``circular``.
+ ``reflect`` and ``circular`` additionally require the pad the kernel needs to stay below the
+ image size (``reflect``) or at most match it (``circular``), and raise a ``RuntimeError``
+ otherwise. Any other value raises a ``ValueError``.
+ border_value: Value to fill past edges of input. It is used only when ``border_type`` is
+ ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
+ under ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: Finite stand-in for the infinite elements of the kernel. See the first warning in
+ :func:`dilation`.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -656,20 +872,35 @@ def top_hat(
See :func:`~kornia.morphology.opening` for details.
+ Convention:
+ ``top_hat`` is ``tensor - opening(tensor)`` with the same ``kernel`` and the same options, so the
+ conventions of :func:`opening` apply to it unchanged, its scikit-image counterpart included:
+ ``skimage.morphology.white_tophat`` with ``mode="ignore"`` is ``top_hat`` at
+ ``origin=[(k_h - 1) // 2, (k_w - 1) // 2]`` while no window is empty.
+
Args:
tensor: Image with shape :math:`(B, C, H, W)`.
kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
- the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
- For full structural elements use torch.ones_like(structural_element).
- structuring_element: Structuring element used for the grayscale dilation. It may be a
- non-flat structuring element.
- origin: Origin of the structuring element. Default: ``None`` and uses the center of
- the structuring element as origin (rounding towards zero).
- border_type: It determines how the image borders are handled, where ``border_value`` is the value
- when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
- outside the image when applying the operation.
- border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
- max_val: The value of the infinite elements in the kernel.
+ the set of neighbors of the ``origin`` cell over which the operation is applied, and their
+ magnitude is ignored. Its shape is :math:`(k_h, k_w)`, laid over the image's :math:`(H, W)` axes.
+ For a full neighborhood pass a ``kernel`` of all ones.
+ structuring_element: Non-flat structuring element, added to the neighbor values before the maximum
+ in :func:`dilation` and subtracted before the minimum in :func:`erosion`. Its shape must equal
+ ``kernel``'s, and any other shape raises a ``ValueError``.
+ origin: ``[row, col]`` index of the structuring-element cell placed on the output pixel.
+ Default: ``None``, which uses ``[k_h // 2, k_w // 2]`` for odd and for even sizes alike
+ (``[1, 1]`` for a :math:`2 \times 2` kernel).
+ border_type: How the image borders are handled. Default: ``geodesic``, which ignores the values
+ that are outside the image when applying the operation. The other accepted values are the
+ :func:`torch.nn.functional.pad` modes ``constant``, ``reflect``, ``replicate`` and ``circular``.
+ ``reflect`` and ``circular`` additionally require the pad the kernel needs to stay below the
+ image size (``reflect``) or at most match it (``circular``), and raise a ``RuntimeError``
+ otherwise. Any other value raises a ``ValueError``.
+ border_value: Value to fill past edges of input. It is used only when ``border_type`` is
+ ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
+ under ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: Finite stand-in for the infinite elements of the kernel. See the first warning in
+ :func:`dilation`.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -740,20 +971,35 @@ def bottom_hat(
See :func:`~kornia.morphology.closing` for details.
+ Convention:
+ ``bottom_hat`` is ``closing(tensor) - tensor`` with the same ``kernel`` and the same options, so the
+ conventions of :func:`closing` apply to it unchanged, its scikit-image counterpart included:
+ ``skimage.morphology.black_tophat`` with ``mode="ignore"`` is ``bottom_hat`` by the flipped kernel
+ while no window is empty.
+
Args:
tensor: Image with shape :math:`(B, C, H, W)`.
kernel: Positions of non-infinite elements of a flat structuring element. Non-zero values give
- the set of neighbors of the center over which the operation is applied. Its shape is :math:`(k_x, k_y)`.
- For full structural elements use torch.ones_like(structural_element).
- structuring_element: Structuring element used for the grayscale dilation. It may be a
- non-flat structuring element.
- origin: Origin of the structuring element. Default: ``None`` and uses the center of
- the structuring element as origin (rounding towards zero).
- border_type: It determines how the image borders are handled, where ``border_value`` is the value
- when ``border_type`` is equal to ``constant``. Default: ``geodesic`` which ignores the values that are
- outside the image when applying the operation.
- border_value: Value to fill past edges of input if ``border_type`` is ``constant``.
- max_val: The value of the infinite elements in the kernel.
+ the set of neighbors of the ``origin`` cell over which the operation is applied, and their
+ magnitude is ignored. Its shape is :math:`(k_h, k_w)`, laid over the image's :math:`(H, W)` axes.
+ For a full neighborhood pass a ``kernel`` of all ones.
+ structuring_element: Non-flat structuring element, added to the neighbor values before the maximum
+ in :func:`dilation` and subtracted before the minimum in :func:`erosion`. Its shape must equal
+ ``kernel``'s, and any other shape raises a ``ValueError``.
+ origin: ``[row, col]`` index of the structuring-element cell placed on the output pixel.
+ Default: ``None``, which uses ``[k_h // 2, k_w // 2]`` for odd and for even sizes alike
+ (``[1, 1]`` for a :math:`2 \times 2` kernel).
+ border_type: How the image borders are handled. Default: ``geodesic``, which ignores the values
+ that are outside the image when applying the operation. The other accepted values are the
+ :func:`torch.nn.functional.pad` modes ``constant``, ``reflect``, ``replicate`` and ``circular``.
+ ``reflect`` and ``circular`` additionally require the pad the kernel needs to stay below the
+ image size (``reflect``) or at most match it (``circular``), and raise a ``RuntimeError``
+ otherwise. Any other value raises a ``ValueError``.
+ border_value: Value to fill past edges of input. It is used only when ``border_type`` is
+ ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
+ under ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: Finite stand-in for the infinite elements of the kernel. See the first warning in
+ :func:`dilation`.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -770,7 +1016,7 @@ def bottom_hat(
pass, which is more memory than ``"unfold"``, not less.
Returns:
- Top hat transformed image with shape :math:`(B, C, H, W)`.
+ Bottom hat transformed image with shape :math:`(B, C, H, W)`.
.. note::
See a working example `here <https://www.kornia.org/tutorials/nbs/morphology_101.html>`__.
diff --git a/tests/morphology/test_bottom_hat.py b/tests/morphology/test_bottom_hat.py
index 1266f91a7..75195f53c 100644
--- a/tests/morphology/test_bottom_hat.py
+++ b/tests/morphology/test_bottom_hat.py
@@ -18,7 +18,8 @@
import pytest
import torch
-from kornia.morphology import bottom_hat
+from kornia.morphology import bottom_hat, closing
+from kornia.morphology import morphology as morphology_module
from testing.base import BaseTester, assert_close
from testing.parametrized_tester import parametrized_test
@@ -122,3 +123,36 @@ class TestBottomHat(BaseTester):
expected = op(sample, kernel)
assert_close(actual, expected)
+
+ def test_convention_bottom_hat_is_closing_minus_image(self, device, dtype, monkeypatch):
+ # `bottom_hat` is exactly `closing(x) - x` with the same kernel and the same options, so every
+ # convention of :func:`kornia.morphology.closing` applies to it unchanged. This pins the
+ # composition: both sides call the same `closing`, whose conventions are pinned in
+ # test_closing.py. The equality is repeated with a non-default `border_type`, `border_value`, `origin`
+ # and `max_val`, so a `bottom_hat` that dropped one of the options would show.
+ # `bottom_hat` evaluates that very expression, so the two sides are bitwise equal in every dtype.
+ # Generated with:
+ # L = torch.tensor([[0., 0., 0.], [0., 1., 1.], [0., 1., 0.]])
+ # torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0))
+ # A local `torch.Generator` avoids touching the process-global (and any device) RNG state.
+ l_kernel = torch.tensor([[0.0, 0.0, 0.0], [0.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)
+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+
+ assert torch.equal(bottom_hat(tensor, l_kernel), closing(tensor, l_kernel) - tensor)
+ # The closing is extensive, so the bottom hat is non-negative.
+ assert (bottom_hat(tensor, l_kernel) >= 0).all()
+ # `max_val=0.1` is inside the data range, so a `bottom_hat` that dropped it for the default `1e4` would show.
+ options = {"border_type": "constant", "border_value": 0.5, "origin": [0, 0], "max_val": 0.1}
+ assert torch.equal(bottom_hat(tensor, l_kernel, **options), closing(tensor, l_kernel, **options) - tensor)
+
+ # ... and both halves of the `closing` receive the caller's `engine`, which the result need not reveal.
+ seen = []
+ resolve = morphology_module._resolve_engine
+
+ def record(engine, *args):
+ seen.append(engine)
+ return resolve(engine, *args)
+
+ monkeypatch.setattr(morphology_module, "_resolve_engine", record)
+ bottom_hat(tensor, l_kernel, engine="unfold")
+ assert seen == ["unfold", "unfold"]
diff --git a/tests/morphology/test_closing.py b/tests/morphology/test_closing.py
index afe8c1f97..1126c4f47 100644
--- a/tests/morphology/test_closing.py
+++ b/tests/morphology/test_closing.py
@@ -18,9 +18,10 @@
import pytest
import torch
-from kornia.morphology import closing
+from kornia.morphology import closing, dilation, erosion
+from kornia.morphology import morphology as morphology_module
-from testing.base import BaseTester, assert_close
+from testing.base import BaseTester, assert_close, supports_replicate_padding
from testing.parametrized_tester import parametrized_test
@@ -140,3 +141,122 @@ class TestClosing(BaseTester):
closed = closing(tensor, kernel, origin=[0, 0])
assert (closed >= tensor).all()
assert torch.equal(closing(closed, kernel, origin=[0, 0]), closed)
+
+ def test_convention_closing_is_a_morphological_closing(self, device, dtype, monkeypatch):
+ # `closing` is `erosion(dilation(x))` with the SAME kernel in both halves, so it is a
+ # morphological closing: extensive and idempotent for an asymmetric kernel. That holds EXACTLY
+ # for the two kernels below at the default origin (and, for ones(3, 3) at origin=[0, 0], in
+ # the custom-origin test above); the last block of this test pins the kernel where it does NOT
+ # hold exactly, so the docstring's `max_val` qualification is on record rather than assumed.
+ # scikit-image mirrors the footprint inside `closing`, which makes it kornia's closing by the
+ # FLIPPED kernel: on the 7x10 rand(seed 0) frame `sm.closing(x, A, mode="ignore")` is bit-equal
+ # to `closing(x, A.flip((0, 1)))` and differs from `closing(x, A)` on 5 border pixels of
+ # column 0 (the interiors agree); the same flipped-kernel equality holds for the L kernel and, at
+ # the default origin, for the even kernels [[1, 0]], ones(2, 2), [[1, 1, 0, 1]] and [[0, 1, 1, 1]]
+ # (`torch.rand(1, 1, 7, 10, dtype=torch.float64)` with `torch.Generator().manual_seed(s)`, s = 0..2).
+ # scipy has no ignore mode: `grey_closing(..., mode="constant",
+ # cval=inf)` pads its dilation half with +inf as well, so it is extensive but differs from
+ # kornia's at the border (0.40 for A on `np.random.default_rng(0).random((7, 9))`) and returns inf on
+ # the whole first column for `[[1, 0, 0]]`; it equals `blk` below only because that frame's border is
+ # already 0. OpenCV's `MORPH_CLOSE` composes without a flip and is not a closing for an asymmetric
+ # kernel at all, nor for an even-sized one at its default anchor (`ones(2, 2)`: extensive on 0 of
+ # 100 random 6x8 frames, where the odd symmetric `[[1, 0, 1]]` is on all 100).
+ # `max`/`min` only select an already-present value of the input, so the idempotence compares
+ # with `torch.equal` and the `>=` never needs a tolerance.
+ # Generated with (scipy 1.17.1, scikit-image 0.26.0, opencv-python-headless 5.0.0, numpy 2.0.0):
+ # blk = np.zeros((9, 11), np.float32); blk[3:6, 3:7] = 1.0; A = np.array([[0, 1, 1]], bool)
+ # ndi.grey_closing(blk, footprint=A, mode="constant", cval=np.inf) == blk -> True
+ # sm.closing(blk, A, mode="ignore") == blk -> True
+ # cv2.morphologyEx(blk, cv2.MORPH_CLOSE, A.astype(np.uint8)) == blk -> False
+ # torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0)) for the invariants.
+ # A local `torch.Generator` avoids touching the process-global (and any device) RNG state.
+ asymmetric = torch.tensor([[0.0, 1.0, 1.0]], device=device, dtype=dtype)
+ block = torch.zeros(1, 1, 9, 11, device=device, dtype=dtype)
+ block[..., 3:6, 3:7] = 1.0
+ assert torch.equal(closing(block, asymmetric), block)
+
+ l_kernel = torch.tensor([[0.0, 0.0, 0.0], [0.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)
+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+ closed = closing(tensor, l_kernel)
+ assert (closed >= tensor).all()
+ assert torch.equal(closing(closed, l_kernel), closed)
+
+ # The docstring names `[[0, 1, 1]]` as exact too, so the invariants are executed for it on the
+ # same frame rather than only the block equality above. Measured with kornia in this worktree
+ # (torch 2.14.0, CPU) over 20 seeds of rand(1, 1, 7, 10) in float32 and float64: the worst
+ # anti-extensivity, opening-idempotence, extensivity and closing-idempotence violation is 0.
+ asymmetric_closed = closing(tensor, asymmetric)
+ assert (asymmetric_closed >= tensor).all()
+ assert torch.equal(closing(asymmetric_closed, asymmetric), asymmetric_closed)
+
+ # The invariants are exact only up to the `max_val` sentinel, so the docstring qualifies them.
+ # `[[1, 0, 0]]` at the default origin reads `x(p + 1)`, so its window leaves the image on the
+ # right; `dilation` can then emit `x - max_val`, and the next stage's `+ max_val` returns `x`
+ # quantised to `max_val`'s spacing, which can push `closing(x)` just BELOW `x`.
+ # Generated with kornia in this worktree (torch 2.14.0, CPU, same rand(1, 1, 7, 10) seed 0):
+ # max(x - closing(x)).clamp(min=0): float32 4.7034e-04, float64 0, float16 9.7998e-01,
+ # bfloat16 9.8047e-01 (float32 ULP of max_val=1e4 is 9.7656e-4; float16's is 8, bf16's 64)
+ # The float64 0 is an artefact of this frame, which is float32 `rand` cast up and so has no bits
+ # below float64's ULP of `max_val`: `torch.rand(..., dtype=torch.float64)` seed 0 falls short by
+ # 7.8804e-13 (worst of 20 seeds 8.96e-13), under that ULP of 1.8190e-12 but not zero.
+ # Over 20 seeds in all four dtypes the shortfall stays in columns W-2 and W-1, the column whose
+ # dilation window is empty and the one before it, so everywhere else the extensivity is exact.
+ # That confinement is what can still fail in half precision, where one ULP of `max_val` (8 in float16,
+ # 64 in bfloat16) is wider than the data. `torch.finfo(dtype).eps * 8192` is that ULP for the default
+ # `max_val=1e4`, which lies in [8192, 16384); over 1000 frames the miss stays within half of it.
+ # On this non-negative frame idempotence survives this kernel exactly; it is the opening half that
+ # loses it (see tests/morphology/test_opening.py). Tracked in #4734.
+ one_ulp = torch.finfo(dtype).eps * 8192.0
+ side_kernel = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)
+ side_closed = closing(tensor, side_kernel)
+ shortfall = (tensor - side_closed).clamp(min=0)
+ assert shortfall.max() < one_ulp
+ assert not bool(shortfall[..., :-2].any())
+ assert torch.equal(closing(side_closed, side_kernel), side_closed)
+ genuine = tensor
+ if dtype == torch.float64:
+ genuine = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0), dtype=dtype).to(device)
+ genuine_shortfall = (genuine - closing(genuine, side_kernel)).clamp(min=0).max()
+ assert 0.0 < genuine_shortfall < one_ulp
+ # On negative data the erosion half's empty window (column 0, `max_val + m`) carries the data into the
+ # next closing's round trip, so the geodesic closing loses idempotence too, by less than that ULP.
+ # Measured with kornia in this worktree (torch 2.14.0 and 2.5.1, CPU and MPS) on the negated frame:
+ # float32 3.5977e-04 in column 1, float16 0.99707 and bfloat16 0.99609 in columns 1-2, genuine float64
+ # 3.6238e-13.
+ negative = -genuine
+ negative_closed = closing(negative, side_kernel)
+ drift = (closing(negative_closed, side_kernel) - negative_closed).abs()
+ assert 0.0 < drift.max() < one_ulp
+
+ # That is the geodesic story only. `dilation` reads `x(p + 1)` and `erosion` reads `y(p - 1)`, so
+ # under `replicate` the first column of the closing is `x(1)`, not `x(0)`, and the closing is not
+ # extensive at all (idempotence survives); under `circular` the two shifts cancel and the closing
+ # is exactly `x`. Measured with kornia in this worktree (torch 2.14.0, CPU, float32) over
+ # rand(1, 1, 7, 10) with `torch.Generator().manual_seed(s)`, s = 0..19: worst replicate extensivity
+ # miss 0.914, worst replicate idempotence miss 0, worst circular deviation from `x` 0.
+ # torch 2.5.1 has no float16 CPU `replication_pad2d`, so the replicate lines follow the probe.
+ if supports_replicate_padding(device, dtype):
+ dip = torch.tensor([[1.0, 0.0, 1.0]], device=device, dtype=dtype)[None, None]
+ replicated = closing(dip, side_kernel, border_type="replicate")
+ assert replicated.flatten().tolist() == [0.0, 0.0, 1.0]
+ assert not bool((replicated >= dip).all())
+ assert torch.equal(closing(replicated, side_kernel, border_type="replicate"), replicated)
+ assert torch.equal(closing(tensor, side_kernel, border_type="circular"), tensor)
+
+ # The composition itself: both halves get every option. `max_val=0.1` is inside the data range, so a
+ # half that fell back to the default `1e4` would show.
+ options = {"border_type": "constant", "border_value": 0.5, "origin": [0, 0], "max_val": 0.1}
+ halves = erosion(dilation(tensor, l_kernel, **options), l_kernel, **options)
+ assert torch.equal(closing(tensor, l_kernel, **options), halves)
+
+ # ... and each half receives the caller's `engine`, which its result alone need not reveal.
+ seen = []
+ resolve = morphology_module._resolve_engine
+
+ def record(engine, *args):
+ seen.append(engine)
+ return resolve(engine, *args)
+
+ monkeypatch.setattr(morphology_module, "_resolve_engine", record)
+ closing(tensor, l_kernel, engine="unfold")
+ assert seen == ["unfold", "unfold"]
diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.py
index 7f7928036..9f998f525 100644
--- a/tests/morphology/test_dilation.py
+++ b/tests/morphology/test_dilation.py
@@ -79,9 +79,17 @@ class TestDilate(BaseTester):
None, None, :, :
]
assert_close(dilation(tensor, kernel, engine="unfold"), expected, atol=1e-4, rtol=1e-4)
- # The convolution engine measures ~3.9e-4 absolute / ~1.5e-3 relative error on macOS's
- # Apple-backend float32 conv path, above the harness's generic float32 default
- # (atol=1e-5, rtol=1e-4). This explicit tolerance is scoped to this backend-specific case.
+ # The convolution engine measures 3.9065e-4 absolute / 4.3405e-4 relative error on THIS
+ # fixture (re-measured for `dilation`; `erosion`'s figures differ, see test_erosion.py),
+ # above the harness's generic float32 default (atol=1e-5, rtol=1e-4). The cause is the geodesic
+ # `-max_val` pad, which `engine="convolution"` feeds through `F.conv2d` together with the image,
+ # so the error scales with `max_val` rather than with the image range. The conv bias, which holds
+ # `-max_val` for the masked cells, is not the cause: under `border_type="replicate"` the same
+ # fixture's gap is 5.96e-8. The backend matters too: CPU float32 shows the gap and MPS measures
+ # exactly 0 on this fixture (torch 2.14.0). One float32 ULP at the default `max_val=1e4` is
+ # 9.7656e-4, and the largest engine gap measured (rand(1, 1, 9, 11) seed 0, ones(3, 3)) is
+ # 1.2736e-3, i.e. ~1.3 ULP. `engine="unfold"` is exact. Tracked in #4734; this tolerance is scoped
+ # to the convolution engine.
assert_close(dilation(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)
def test_structural_element(self, device, dtype):
@@ -100,8 +108,9 @@ class TestDilate(BaseTester):
),
expected,
)
- # See test_kernel: convolution engine needs an explicit tolerance for macOS's
- # Apple-backend float32 numerical error, above the harness's generic float32 default.
+ # See test_kernel: the convolution engine needs an explicit tolerance because the geodesic
+ # `-max_val` pad it feeds through `F.conv2d` costs on the order of one ULP of `max_val`
+ # (9.7656e-4 in float32 at the default `max_val=1e4`) on CPU. Tracked in #4734.
assert_close(
dilation(
tensor,
@@ -565,10 +574,269 @@ class TestDilate(BaseTester):
expected[..., row, col] = 1.0
if engine == "convolution":
- # See test_kernel: the convolution engine can carry tiny floating noise on some
- # backends even for 0/1 inputs, so compare the full tensor at the harness's
- # default per-dtype tolerance instead of a strict nonzero() index list; the
- # fixture is 0/1 so this is exact anyway.
+ # See test_kernel: `engine="convolution"` feeds the geodesic `-max_val` pad through
+ # `F.conv2d`, so the gap between the engines scales with `max_val` rather than with the
+ # image range (#4734), on the backends whose conv shows it at all (CPU float32, not MPS).
+ # On this 0/1 fixture the gap measures exactly 0 on CPU in float32, float64, float16
+ # and bfloat16 and on MPS in float32, float16 and bfloat16 (torch 2.14.0); CUDA is
+ # unmeasured, so this compares the full tensor at the harness's default per-dtype
+ # tolerance rather than a strict nonzero() index list.
self.assert_close(actual, expected)
else:
assert sorted(actual.nonzero()[:, 2:].tolist()) == expected_nonzero
+
+ def test_convention_dilation_reflects_kernel(self, device, dtype):
+ # `dilation` is the Minkowski dilation `out(p) = max_{q: kernel[q] != 0} x(p - (q - origin))`,
+ # so the kernel *contents* are reflected. The asymmetric kernel is the whole point: `ones(3, 3)`
+ # is invariant under the flip and cannot tell the two conventions apart.
+ # The fixture is 0/1 and the engine gap on it measures exactly 0 on CPU in all four dtypes
+ # and on MPS in float32/float16/bfloat16 (torch 2.14.0), but CUDA is unmeasured and the gap is
+ # a geodesic-pad effect that scales with `max_val` (#4734), so this compares at the harness's
+ # default per-dtype tolerance, like the neighbouring convolution branch above.
+ # Generated with (scipy 1.17.1, scikit-image 0.26.0, opencv-python-headless 5.0.0, numpy 2.0.0):
+ # x = np.zeros((1, 7), np.float32); x[0, 3] = 1.0; A = np.array([[0, 1, 1]], bool)
+ # ndi.grey_dilation(x, footprint=A, mode="constant", cval=-np.inf)
+ # -> [0, 0, 0, 1, 1, 0, 0] (cols {3, 4}; same as kornia)
+ # sm.dilation(x, A, mode="ignore") -> [0, 0, 1, 1, 0, 0, 0] (cols {2, 3})
+ # cv2.dilate(x, A.astype(np.uint8)) -> [0, 0, 1, 1, 0, 0, 0] (cols {2, 3})
+ # Neither reference reflects. scikit-image returns kornia's dilation by the flipped kernel at
+ # every kernel size; OpenCV does so only for an odd-sized kernel, because it also anchors an
+ # even-sized kernel one cell earlier. Measured on
+ # `torch.rand(7, 9, generator=torch.Generator().manual_seed(0), dtype=torch.float64)`, comparing
+ # each reference at its default anchor against `dilation(x, K.flip((0, 1)))`:
+ # K = ones(1, 3) / [[0, 1, 1]] (odd): skimage 0, cv2 0 at the default origin
+ # K = [[1, 0]] / ones(2, 2) / [[1, 1, 0, 1]] (even): skimage 0 at the default origin, while
+ # cv2 differs there (`ones(2, 2)` 0.825, `[[1, 1, 0, 1]]` 0.732, `[[1, 0]]` 0.956 plus a
+ # -DBL_MAX column 0) and is 0 at `origin=[(k_h - 1) // 2, (k_w - 1) // 2]` -- except that for
+ # `[[1, 0]]` column 0 is then an empty window, where cv2 keeps -DBL_MAX and kornia returns
+ # `-max_val + x[:, 0]` (-9999.71 to -9999.03).
+ tensor = torch.zeros(1, 1, 1, 7, device=device, dtype=dtype)
+ tensor[..., 3] = 1.0
+ kernel = torch.tensor([[0.0, 1.0, 1.0]], device=device, dtype=dtype)
+
+ expected = torch.zeros(1, 1, 1, 7, device=device, dtype=dtype)
+ expected[..., 3] = 1.0
+ expected[..., 4] = 1.0
+
+ # The default engine (`shift` on CPU and MPS without autograd) reflects too.
+ self.assert_close(dilation(tensor, kernel), expected)
+ self.assert_close(dilation(tensor, kernel, engine="unfold"), expected)
+ self.assert_close(dilation(tensor, kernel, engine="convolution"), expected)
+
+ def test_convention_dilation_non_flat_se_is_additive_and_reflected(self, device, dtype):
+ # `structuring_element` is the additive (grey-level) part: the neighbourhood value `SE[q]` is
+ # ADDED to `x` before the max (and SUBTRACTED before the min in `erosion`), while `kernel` only
+ # selects the members. It is reflected in `dilation` together with the kernel, so the peak of
+ # `SE = [0, 0.5, 1]` lands to the RIGHT of the hot pixel.
+ # Every literal below is a multiple of 0.5 and therefore exact in float16/bfloat16 too.
+ # Generated with scipy 1.17.1 / numpy 2.0.0:
+ # x = np.zeros((1, 7), np.float32); x[0, 3] = 1.0; SE = np.array([[0, .5, 1.]])
+ # ndi.grey_dilation(x, structure=SE, footprint=np.ones((1, 3), bool),
+ # mode="constant", cval=-np.inf) -> [0.5, 1, 1, 1.5, 2, 1, 1]
+ # ndi.grey_erosion(x + 5, structure=SE, footprint=np.ones((1, 3), bool),
+ # mode="constant", cval=np.inf) -> [4, 4, 4.5, 4, 4, 4, 4.5]
+ # scikit-image and OpenCV have no non-flat structuring element at all.
+ tensor = torch.zeros(1, 1, 1, 7, device=device, dtype=dtype)
+ tensor[..., 3] = 1.0
+ kernel = torch.ones(1, 3, device=device, dtype=dtype)
+ structuring_element = torch.tensor([[0.0, 0.5, 1.0]], device=device, dtype=dtype)
+
+ dilated = dilation(tensor, kernel, structuring_element=structuring_element)
+ self.assert_close(
+ dilated,
+ torch.tensor([[[[0.5, 1.0, 1.0, 1.5, 2.0, 1.0, 1.0]]]], device=device, dtype=dtype),
+ )
+
+ eroded = erosion(tensor + 5.0, kernel, structuring_element=structuring_element)
+ self.assert_close(
+ eroded,
+ torch.tensor([[[[4.0, 4.0, 4.5, 4.0, 4.0, 4.0, 4.5]]]], device=device, dtype=dtype),
+ )
+
+ def test_convention_kernel_is_a_membership_mask(self, device, dtype):
+ # `kernel` is a flat membership mask tested with `!= 0`: negative and fractional entries are
+ # members just like a 1, and their magnitude is ignored (use `structuring_element` for weights).
+ # Generated with scikit-image 0.26.0 / scipy 1.17.1 / numpy 2.0.0 on the hot-pixel row:
+ # ndi.grey_dilation(x, footprint=np.array([[-1, 1, 0]]), ...) -> [0, 0, 1, 1, 0, 0, 0]
+ # (2 members; scipy reflects too, so this is kornia's own output)
+ # sm.dilation(x, np.array([[-1, 1, 0]]), mode="ignore") -> [0, 0, 0, 1, 1, 0, 0]
+ # scikit-image KEEPS the -1 cell: its `[[-1, 1, 0]]` output is bit-equal to its `[[1, 1, 0]]`
+ # output and differs from its `[[0, 1, 0]]` output ([0, 0, 0, 1, 0, 0, 0]), which is what
+ # dropping the cell would give. The remaining difference from kornia is the reflection --
+ # cols {3, 4} there against cols {2, 3} here -- not the membership rule.
+ # Entries of `structuring_element` under a zero `kernel` cell are overwritten by the
+ # `-max_val` sentinel and never reach the output: with a zero structuring element elsewhere the
+ # result is the flat one, in `dilation` and in `erosion` alike.
+ tensor = torch.rand(1, 2, 5, 6, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+ reference_kernel = torch.tensor([[1.0, 1.0, 0.0]], device=device, dtype=dtype)
+ expected_dilation = dilation(tensor, reference_kernel)
+ expected_erosion = erosion(tensor, reference_kernel)
+
+ for entry in (-1.0, 0.5, 2.0):
+ kernel = torch.tensor([[entry, 1.0, 0.0]], device=device, dtype=dtype)
+ assert torch.equal(dilation(tensor, kernel), expected_dilation), entry
+ assert torch.equal(erosion(tensor, kernel), expected_erosion), entry
+
+ masked_kernel = torch.tensor([[0.0, 1.0, 1.0]], device=device, dtype=dtype)
+ loud = torch.tensor([[99.0, 0.0, 0.0]], device=device, dtype=dtype)
+ assert torch.equal(dilation(tensor, masked_kernel, structuring_element=loud), dilation(tensor, masked_kernel))
+ assert torch.equal(erosion(tensor, masked_kernel, structuring_element=loud), erosion(tensor, masked_kernel))
+
+ def test_convention_engines_agree_within_a_few_ulps_of_max_val(self, device, dtype, cudnn_tf32_follows_option):
+ # Both engines implement the same operation. `engine="unfold"` is exact; `engine="convolution"`
+ # feeds the geodesic `-max_val` pad through `F.conv2d` together with the image, so on CPU its error
+ # scales with `max_val` rather than with the image range (`ones(3, 3)` has no masked cell, so the
+ # conv bias is all zeros here and plays no part). The exact gap is platform-dependent --
+ # only CPU and MPS on torch 2.14.0 were measured here, and CUDA's `conv2d` picks a different
+ # algorithm -- so this pins a BOUND, not the value, and the bound carries slack (4 eps rather
+ # than the 2 eps that would just fit the measurement) so that one extra ULP on an unmeasured
+ # backend or on the torch 2.5.1 floor does not red the pin. `cudnn_tf32_follows_option` keeps
+ # CUDA's float32 `conv2d` out of TF32 unless `--tf32` is passed; TF32's 10-bit mantissa would swamp
+ # a bound in float32 ULPs.
+ # Tracked in #4734.
+ # Measured (CPU, torch 2.14.0, float32, x = rand(1, 1, 9, 11) seed 0, kernel ones(3, 3)):
+ # max_val=1 -> 1.1921e-07 max_val=1e2 -> 7.1526e-06 max_val=1e4 -> 1.2736e-03
+ # i.e. 1.0, 0.94 and 1.3 float32 ULPs of `max_val` (ULP(1) = 1.1921e-07, ULP(1e2) = 7.6294e-06,
+ # ULP(1e4) = 9.7656e-04). float64, float16 and bfloat16 measured 0 at all three values.
+ tensor = torch.rand(1, 1, 9, 11, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ for max_val in (1.0, 1e2, 1e4):
+ unfolded = dilation(tensor, kernel, max_val=max_val, engine="unfold")
+ convolved = dilation(tensor, kernel, max_val=max_val, engine="convolution")
+ self.assert_close(convolved, unfolded, atol=4.0 * torch.finfo(dtype).eps * max_val, rtol=0.0)
+
+ def test_wart_dilation_max_val_sentinel_leaks_4734(self, device):
+ # `max_val` is a finite stand-in for infinity, not an infinity: it is SUBTRACTED from the
+ # masked-out neighbourhood cells and, under the default geodesic border, padded into the border,
+ # so it reaches the output whenever the window is empty or the range of the image plus the
+ # structuring element approaches `max_val`. scipy and scikit-image's `mode="ignore"` return a true
+ # -inf/+inf in the empty window and the true dilation in the range cases. Tracked in #4734.
+ # float32 only: 40000 is not representable in bfloat16 and the claim is about the float32
+ # default `max_val=1e4`, so the dtype is explicit rather than taken from the fixture.
+ # Generated with kornia in this worktree (torch 2.14.0, CPU, float32):
+ # dilation(torch.ones(1, 1, 1, 1), [[1., 0., 0.]], origin=[0, 2]).item() -> -9999.0
+ # erosion(torch.ones(1, 1, 1, 1), [[1., 0., 0.]], origin=[0, 2]).item() -> 10000.0
+ # dilation([[0., 5e4, 0.]], [[1., 0., 1.]]) -> [50000., 40000., 50000.] (true: [5e4, 0, 5e4])
+ # dilation([[-5e4, -6e4]], torch.ones(1, 3)) -> [-10000., -10000.] (true: [-5e4, -5e4])
+ dtype = torch.float32
+ single = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)
+ side_kernel = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)
+
+ # The window is empty at this origin, so the output is the sentinel plus the pixel, not the pixel.
+ assert dilation(single, side_kernel, origin=[0, 2]).item() == -9999.0
+ assert erosion(single, side_kernel, origin=[0, 2]).item() == 10000.0
+
+ big = torch.tensor([[0.0, 5e4, 0.0]], device=device, dtype=dtype)[None, None]
+ gapped_kernel = torch.tensor([[1.0, 0.0, 1.0]], device=device, dtype=dtype)
+ assert dilation(big, gapped_kernel).flatten().tolist() == [50000.0, 40000.0, 50000.0]
+ # With a `max_val` above the image range the same call is correct, which is the diagnosis.
+ assert dilation(big, gapped_kernel, max_val=1e6).flatten().tolist() == [50000.0, 0.0, 50000.0]
+
+ negative = torch.tensor([[-5e4, -6e4]], device=device, dtype=dtype)[None, None]
+ assert dilation(negative, torch.ones(1, 3, device=device, dtype=dtype)).flatten().tolist() == [
+ -10000.0,
+ -10000.0,
+ ]
+
+ # An empty window is not `max_val` either: a masked-out in-image cell contributes `x + max_val`
+ # to `erosion` (`x - max_val` to `dilation`), so a negative pixel under it pulls the result below
+ # the sentinel. Generated with kornia in this worktree (torch 2.14.0, CPU and MPS, float32):
+ # erosion([[-2.]], [[0., 1.]], origin=[0, 0]) -> 9998.0 (scipy, cval=inf, origin=(0, -1): inf)
+ # dilation([[5.]], [[0., 1.]], origin=[0, 0]) -> -9995.0 (scipy, cval=-inf, origin=(0, -1): -inf)
+ # In general the empty window returns `max_val + min(0, m)` (`-max_val + max(0, M)` in `dilation`),
+ # `m` (`M`) the smallest (largest) in-image pixel under a masked-out cell, rounded in the image's dtype.
+ corner_kernel = torch.tensor([[0.0, 1.0]], device=device, dtype=dtype)
+ minus_two = torch.full((1, 1, 1, 1), -2.0, device=device, dtype=dtype)
+ assert erosion(minus_two, corner_kernel, origin=[0, 0]).item() == 9998.0
+ five = torch.full((1, 1, 1, 1), 5.0, device=device, dtype=dtype)
+ assert dilation(five, corner_kernel, origin=[0, 0]).item() == -9995.0
+ # The same sentinel is stored into a structuring element when one is given.
+ flat_corner = torch.zeros_like(corner_kernel)
+ assert erosion(minus_two, corner_kernel, structuring_element=flat_corner, origin=[0, 0]).item() == 9998.0
+ assert dilation(five, corner_kernel, structuring_element=flat_corner, origin=[0, 0]).item() == -9995.0
+
+ # The same empty window breaks the adjunction `dilation(x) <= y <=> x <= erosion(y)`, which holds
+ # while no window is empty (see test_convention_adjunction_without_empty_windows in test_erosion.py).
+ # max_val=1, x = y = [[-2.]]: dilation(x) -> -1.0, erosion(y) -> -1.0
+ dilated = dilation(minus_two, corner_kernel, origin=[0, 0], max_val=1.0)
+ eroded = erosion(minus_two, corner_kernel, origin=[0, 0], max_val=1.0)
+ assert dilated.item() == -1.0
+ assert eroded.item() == -1.0
+ assert not bool((dilated <= minus_two).all())
+ assert bool((minus_two <= eroded).all())
+
+ # Only the geodesic border is padded with the sentinel (`constant` pads `border_value`); a non-flat
+ # structuring element that reaches `max_val` lets that border back in even on a zero image; and an
+ # all-zero kernel has no member in the pad, so its empty window is `x + max_val`, not
+ # `max_val + min(0, x)`. Generated with kornia in this worktree (torch 2.14.0, CPU and MPS, float32):
+ # dilation([[3., 4., 5.]], [[0., 1.]], origin=[0, 0]) -> [-9997, 3, 4]
+ # dilation(..., border_type="constant") -> [0, 3, 4]
+ # dilation(zeros(1, 1, 1, 4), ones(1, 3), structuring_element=[[0., 0., 15000.]])
+ # -> [5000, 15000, 15000, 15000] (scipy, cval=-inf: [0, 15000, 15000, 15000])
+ # erosion([[5.]], [[0.]]) -> 10005.0
+ ramp = torch.tensor([[3.0, 4.0, 5.0]], device=device, dtype=dtype)[None, None]
+ assert dilation(ramp, corner_kernel, origin=[0, 0]).flatten().tolist() == [-9997.0, 3.0, 4.0]
+ constant_ramp = dilation(ramp, corner_kernel, origin=[0, 0], border_type="constant")
+ assert constant_ramp.flatten().tolist() == [0.0, 3.0, 4.0]
+ valued_ramp = dilation(ramp, corner_kernel, origin=[0, 0], border_type="constant", border_value=7.0)
+ assert valued_ramp.flatten().tolist() == [7.0, 3.0, 4.0]
+ tall_se = torch.tensor([[0.0, 0.0, 15000.0]], device=device, dtype=dtype)
+ leaked = dilation(
+ torch.zeros(1, 1, 1, 4, device=device, dtype=dtype),
+ torch.ones(1, 3, device=device, dtype=dtype),
+ structuring_element=tall_se,
+ )
+ assert leaked.flatten().tolist() == [5000.0, 15000.0, 15000.0, 15000.0]
+ assert erosion(five, torch.zeros(1, 1, device=device, dtype=dtype)).item() == 10005.0
+
+ # `max_val` has to be finite in the operands' dtype, and a representable one works in float16, both in
+ # the geodesic pad and in the kernel's masked-out cells. (A larger one raises or rounds depending on the
+ # backend and the torch release, which is torch's cast and is left unasserted.)
+ half_image = torch.rand(1, 1, 4, 4, generator=torch.Generator().manual_seed(0)).to(device, torch.float16)
+ half_cross = torch.tensor(
+ [[0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=torch.float16
+ )
+ assert torch.equal(dilation(half_image, half_cross, max_val=65504.0), dilation(half_image, half_cross))
+
+ def test_wart_non_float_image_is_not_rejected_4735(self, device):
+ # Only floating-point images are supported, but a non-float image is not rejected. What it then does
+ # depends on the border, the engine, the backend and the torch release, so the pin records only the
+ # portable symptom that a fix for #4735 flips: a `uint8` image under `border_type="constant"` runs
+ # and returns the float kernel's dtype. Dtypes are explicit, so this pin takes `device` only.
+ # Generated with kornia in this worktree (torch 2.14.0 and 2.5.1, CPU and MPS):
+ # dilation(zeros(1, 1, 1, 5, uint8), ones(1, 3), border_type="constant") -> float32 zeros
+ zeros_uint8 = torch.zeros(1, 1, 1, 5, dtype=torch.uint8, device=device)
+ float_kernel = torch.ones(1, 3, device=device)
+ for op in (dilation, erosion):
+ out = op(zeros_uint8, float_kernel, border_type="constant")
+ assert out.dtype == torch.float32, op.__name__
+ assert out.flatten().tolist() == [0.0] * 5, op.__name__
+
+ def test_convention_mask_kernel_with_structuring_element(self, device, dtype):
+ # With a floating structuring element the sentinel is stored there, the kernel is only the
+ # `kernel == 0` mask, and a `uint8` or `bool` kernel returns what the floating kernel does.
+ frame = torch.rand(1, 1, 4, 5, generator=torch.Generator().manual_seed(0)).to(device, dtype)
+ flat_se = torch.zeros(1, 3, device=device, dtype=dtype)
+ float_kernel = torch.tensor([[1.0, 0.0, 1.0]], device=device, dtype=dtype)
+ for mask_dtype in (torch.uint8, torch.bool):
+ for op in (dilation, erosion):
+ assert torch.equal(
+ op(frame, float_kernel.to(mask_dtype), structuring_element=flat_se),
+ op(frame, float_kernel, structuring_element=flat_se),
+ ), (mask_dtype, op.__name__)
+
+ def test_wart_convolution_engine_keeps_image_dtype_4762(self, device):
+ # `unfold` and `shift` compute in, and return, the promoted dtype of the image and the kernel (or
+ # the structuring element); `engine="convolution"` casts the kernel to the image's dtype instead,
+ # so the result dtype depends on the engine. Tracked in #4762. Dtypes are explicit (the claim is
+ # about a float16 image with a float32 kernel), so this pin takes `device` only.
+ # Generated with kornia in this worktree (torch 2.14.0; CPU and MPS agree):
+ # dilation(float16 image, ones(3, 3) float32, engine=e).dtype -> unfold/shift float32, convolution float16
+ # erosion(...) likewise
+ tensor = torch.rand(1, 1, 4, 5, generator=torch.Generator().manual_seed(0)).to(device, torch.float16)
+ kernel = torch.ones(3, 3, device=device)
+ for op in (dilation, erosion):
+ assert op(tensor, kernel, engine="unfold").dtype == torch.float32, op.__name__
+ assert op(tensor, kernel, engine="shift").dtype == torch.float32, op.__name__
+ assert op(tensor, kernel, engine="convolution").dtype == torch.float16, op.__name__
diff --git a/tests/morphology/test_erosion.py b/tests/morphology/test_erosion.py
index 9c44b2c91..e6c4f58c6 100644
--- a/tests/morphology/test_erosion.py
+++ b/tests/morphology/test_erosion.py
@@ -18,7 +18,7 @@
import pytest
import torch
-from kornia.morphology import erosion
+from kornia.morphology import dilation, erosion
from kornia.morphology import morphology as morphology_module
from kornia.morphology.morphology import _records_grad, _resolve_engine
@@ -79,9 +79,18 @@ class TestErode(BaseTester):
None, None, :, :
]
assert_close(erosion(tensor, kernel), expected, atol=1e-4, rtol=1e-4)
- # The convolution engine measures ~3.9e-4 absolute / ~1.5e-3 relative error on macOS's
- # Apple-backend float32 conv path, above the harness's generic float32 default
- # (atol=1e-5, rtol=1e-4). This explicit tolerance is scoped to this backend-specific case.
+ # The convolution engine measures 3.9062e-4 absolute / 1.4649e-3 relative error on THIS
+ # fixture (re-measured for `erosion`; `dilation`'s relative figure is 4.3405e-4, not this one),
+ # above the harness's generic float32 default (atol=1e-5, rtol=1e-4). The cause is the geodesic
+ # `+max_val` pad, which `engine="convolution"` feeds through `F.conv2d` together with the image, so
+ # the error scales with `max_val` rather than with the image range; under `replicate` the same
+ # fixture's gap is 2.98e-8, and MPS measures exactly 0 here (torch 2.14.0), so the backend matters
+ # too. One float32 ULP at the default `max_val=1e4` is 9.7656e-4, and the largest
+ # erosion engine gap measured (rand(1, 1, 9, 11) seed 0, ones(3, 3)) is 1.2360e-3, i.e. ~1.3 ULP.
+ # The relative figure exceeds `rtol=1e-3`; the assertion passes on `atol=1e-3`, because the
+ # error is absolute and the tightest entry here is `expected == 0.2`, where the absolute error
+ # measures 2.9297e-4, i.e. the reported relative figure is (2.9297e-4 / 0.2).
+ # `engine="unfold"` is exact. Tracked in #4734; this tolerance is scoped to the convolution engine.
assert_close(erosion(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)
def test_structural_element(self, device, dtype):
@@ -100,8 +109,9 @@ class TestErode(BaseTester):
atol=1e-4,
rtol=1e-4,
)
- # See test_kernel: convolution engine needs an explicit tolerance for macOS's
- # Apple-backend float32 numerical error, above the harness's generic float32 default.
+ # See test_kernel: the convolution engine needs an explicit tolerance because the geodesic
+ # `+max_val` pad it feeds through `F.conv2d` costs on the order of one ULP of `max_val`
+ # (9.7656e-4 in float32 at the default `max_val=1e4`) on CPU. Tracked in #4734.
assert_close(
erosion(
tensor,
@@ -123,8 +133,9 @@ class TestErode(BaseTester):
None, None, :, :
]
assert_close(erosion(tensor, kernel, engine="unfold"), expected, atol=1e-4, rtol=1e-4)
- # See test_kernel: convolution engine needs an explicit tolerance for macOS's
- # Apple-backend float32 numerical error, above the harness's generic float32 default.
+ # See test_kernel: the convolution engine needs an explicit tolerance because the geodesic
+ # `+max_val` pad it feeds through `F.conv2d` costs on the order of one ULP of `max_val`
+ # (9.7656e-4 in float32 at the default `max_val=1e4`) on CPU. Tracked in #4734.
assert_close(erosion(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)
def test_exception(self, device, dtype):
@@ -432,3 +443,275 @@ class TestErode(BaseTester):
kernel = torch.ones(3, 3, device=device, dtype=dtype)
assert torch.equal(op_script(tensor, kernel, engine="shift"), erosion(tensor, kernel, engine="shift"))
+
+ def test_convention_erosion_does_not_reflect_kernel(self, device, dtype):
+ # `erosion` is the Minkowski erosion `out(p) = min_{q: kernel[q] != 0} x(p + (q - origin))`:
+ # the kernel is NOT reflected, unlike in `dilation`. The complement form `1 - erosion(1 - x, A)`
+ # makes the two conventions land on different columns for the asymmetric kernel `[[0, 1, 1]]`;
+ # `ones(3, 3)` is invariant under the flip and could not tell them apart.
+ # The fixtures are 0/1 and small integers, exact in every dtype; the engine gap on them
+ # measures exactly 0 on CPU in all four dtypes and on MPS in float32/float16/bfloat16
+ # (torch 2.14.0), but it is a `max_val` effect and CUDA is unmeasured (#4734), so the
+ # comparison uses the harness's default per-dtype tolerance.
+ # Generated with (scipy 1.17.1, scikit-image 0.26.0, opencv-python-headless 5.0.0, numpy 2.0.0):
+ # x = np.zeros((1, 7), np.float32); x[0, 3] = 1.0; A = np.array([[0, 1, 1]], bool)
+ # 1 - ndi.grey_erosion(1 - x, footprint=A, mode="constant", cval=np.inf) -> cols {2, 3}
+ # 1 - sm.erosion(1 - x, A, mode="ignore") -> cols {2, 3}
+ # 1 - cv2.erode(1 - x, A.astype(np.uint8)) -> cols {2, 3}
+ # All three references agree with kornia on this ODD kernel; it is `dilation` that reflects.
+ # For an EVEN-sized footprint scikit-image anchors one cell earlier than the other three.
+ # On the ramp below with the even asymmetric kernel [[1, 1, 0, 1]] (default origin [0, 2]):
+ # ramp = np.array([[1., 2., 3., 0., 5., 6., 7., 8.]], np.float32); K = ...[[1, 1, 0, 1]]
+ # ndi.grey_erosion(ramp, footprint=K != 0, mode="constant", cval=1e8)
+ # -> [2, 1, 0, 2, 0, 0, 5, 6] (= kornia, below)
+ # cv2.erode(ramp, K.astype(np.uint8)) -> [2, 1, 0, 2, 0, 0, 5, 6] (= kornia)
+ # sm.erosion(ramp, K != 0, mode="ignore") -> [1, 0, 2, 0, 0, 5, 6, 7] (one cell earlier,
+ # which is kornia's erosion at origin=[(k_h - 1) // 2, (k_w - 1) // 2] = [0, 1])
+ # Measured the same way on a 7x9 rand(seed 0) float64 frame, over the windows that hold an
+ # in-image kernel cell: scipy and cv2 match kornia's default for [[1, 0]], ones(2, 2),
+ # ones(1, 3), [[0, 1, 1]] and [[1, 1, 0, 1]], while skimage differs on the three even ones by
+ # 0.956 / 0.682 / 0.822 and matches at the earlier origin. For [[1, 0]] kornia's column 0 is an
+ # empty window at the default origin and holds the `max_val` sentinel (10000) where scipy holds
+ # `inf`, so that column is outside the comparison (#4734).
+ tensor = torch.zeros(1, 1, 1, 7, device=device, dtype=dtype)
+ tensor[..., 3] = 1.0
+ kernel = torch.tensor([[0.0, 1.0, 1.0]], device=device, dtype=dtype)
+
+ expected = torch.zeros(1, 1, 1, 7, device=device, dtype=dtype)
+ expected[..., 2] = 1.0
+ expected[..., 3] = 1.0
+
+ self.assert_close(1 - erosion(1 - tensor, kernel, engine="unfold"), expected)
+ self.assert_close(1 - erosion(1 - tensor, kernel, engine="convolution"), expected)
+
+ # The even-sized kernel is where scikit-image parts company; the kornia literal is the one
+ # scipy and OpenCV also produce. Every value is a small integer, exact in every dtype, and no
+ # window here is empty, so the `max_val` sentinel never reaches the output.
+ ramp = torch.tensor([[1.0, 2.0, 3.0, 0.0, 5.0, 6.0, 7.0, 8.0]], device=device, dtype=dtype)[None, None]
+ even_kernel = torch.tensor([[1.0, 1.0, 0.0, 1.0]], device=device, dtype=dtype)
+ even_expected = torch.tensor([[2.0, 1.0, 0.0, 2.0, 0.0, 0.0, 5.0, 6.0]], device=device, dtype=dtype)[None, None]
+ self.assert_close(erosion(ramp, even_kernel), even_expected)
+ # scikit-image's answer is this one, and it is kornia's at the earlier origin.
+ skimage_expected = torch.tensor([[1.0, 0.0, 2.0, 0.0, 0.0, 5.0, 6.0, 7.0]], device=device, dtype=dtype)[
+ None, None
+ ]
+ self.assert_close(erosion(ramp, even_kernel, origin=[0, 1]), skimage_expected)
+
+ def test_convention_adjunction_without_empty_windows(self, device, dtype):
+ # Under `border_type="geodesic"` or `"circular"`, `dilation` and `erosion` with the same kernel and
+ # origin are an adjoint pair, `dilation(x) <= y` everywhere exactly when `x <= erosion(y)`
+ # everywhere, while no window is empty and the image range stays well below `max_val`. The kernel
+ # changes under a 180-degree flip, so a reflection mismatch between the two would break the pair,
+ # and it holds its default origin cell [1, 1], so no window is empty. Every value is a small
+ # integer, exact in every dtype. The empty-window counterexample is pinned in
+ # test_wart_dilation_max_val_sentinel_leaks_4734.
+ # Measured with kornia in this worktree (torch 2.14.0, CPU, float64, `torch.Generator().manual_seed(0)`):
+ # 6000 random kernels of size 1-4 with a random origin whose cell is set, integer images in [-5, 5] of
+ # size 4-7, a third with an integer non-flat structuring element in [-3, 3], and the tightest
+ # y = dilation(x) -- geodesic 0 and circular 0 failures, replicate 2819, reflect 4179, constant 4837.
+ x = torch.tensor(
+ [[3.0, 0.0, 5.0, 1.0, 2.0, 7.0], [0.0, 4.0, 1.0, 6.0, 0.0, 2.0], [2.0, 1.0, 0.0, 3.0, 5.0, 1.0]],
+ device=device,
+ dtype=dtype,
+ )[None, None]
+ kernel = torch.tensor([[1.0, 1.0, 0.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)
+ for border_type in ("geodesic", "circular"):
+ dilated = dilation(x, kernel, border_type=border_type)
+ # y = dilation(x) is the smallest y with dilation(x) <= y, so x <= erosion(y) must hold ...
+ assert bool((x <= erosion(dilated, kernel, border_type=border_type)).all()), border_type
+ # ... and lowering y at any one pixel breaks the left side, so it must break the right side too.
+ for row in range(x.shape[-2]):
+ for col in range(x.shape[-1]):
+ lowered = dilated.clone()
+ lowered[..., row, col] -= 1
+ assert not bool((x <= erosion(lowered, kernel, border_type=border_type)).all()), (
+ border_type,
+ row,
+ col,
+ )
+
+ # The other pads can break the pair with no window empty. Under `constant` (border_value 0) with
+ # ones(3, 3) and x = y = -1, the dilation reads the 0 pad on the border and exceeds y, while the
+ # erosion's min(-1, 0) is -1 >= x everywhere.
+ minus_one = torch.full((1, 1, 3, 4), -1.0, device=device, dtype=dtype)
+ box = torch.ones(3, 3, device=device, dtype=dtype)
+ assert not bool((dilation(minus_one, box, border_type="constant") <= minus_one).all())
+ assert bool((minus_one <= erosion(minus_one, box, border_type="constant")).all())
+
+ def test_convention_geodesic_border_ignores_outside(self, device, dtype):
+ # The default `border_type="geodesic"` makes the operation ignore the pixels outside the image,
+ # which is scikit-image's `mode="ignore"` and OpenCV's default border for morphology (scipy has
+ # no such mode; it is spelled `mode="constant", cval=+/-inf` there). `border_type="constant"`
+ # instead pads `border_value`, and under `geodesic` any `border_value` the caller passes is
+ # silently overwritten. scipy 1.17.1 and scikit-image 0.26.0 both DEFAULT to `mode="reflect"`,
+ # re-executed in the throwaway env:
+ # inspect.signature(ndi.grey_erosion) -> (input, size=None, footprint=None, structure=None,
+ # output=None, mode='reflect', cval=0.0, origin=0, *, axes=None)
+ # inspect.signature(sm.erosion) -> (image, footprint=None, out=None, *, mode='reflect',
+ # cval=0.0)
+ # and THEIR `reflect` is not torch's (torch's is their `mirror`; see
+ # test_convention_border_type_names_match_scipy_modes), so a comparison against either has to
+ # pass the mode explicitly; `cv2.erode(np.ones((3, 4), np.float32), np.ones((3, 3), np.uint8))`
+ # returns all ones, i.e. OpenCV's default ignores the outside like `geodesic`.
+ # 0/1 and -5 fixtures are exact in every dtype, so this compares with `torch.equal`.
+ # Generated with kornia in this worktree (torch 2.14.0, CPU, float32):
+ # erosion(torch.ones(1, 1, 3, 4), torch.ones(3, 3)) -> all 1
+ # erosion(..., border_type="constant") -> 1 only at (1, 1:3)
+ # erosion(..., border_value=-5.0) -> all 1 (ignored)
+ # erosion(..., border_type="constant", border_value=-5.0) -> -5 on the border
+ # erosion(..., border_type="reflect", border_value=-5.0) -> all 1 (ignored)
+ # `reflect`, `replicate` and `circular` ignore `border_value` as well; before #4748 was fixed
+ # kornia forwarded it to `F.pad`, which rejects any value other than 0.0 for those modes.
+ tensor = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ assert torch.equal(erosion(tensor, kernel), tensor)
+ # `border_value` is used only under `border_type="constant"`.
+ assert torch.equal(erosion(tensor, kernel, border_value=-5.0), tensor)
+
+ padded = torch.full((1, 1, 3, 4), -5.0, device=device, dtype=dtype)
+ padded[..., 1, 1:3] = 1.0
+ assert torch.equal(erosion(tensor, kernel, border_type="constant", border_value=-5.0), padded)
+
+ # Outside `geodesic` and `constant` a non-zero `border_value` is ignored too: filled in, the -5
+ # would reach the border pixels, as it does under `constant` above. (torch 2.5.1 has no half-precision
+ # CPU `reflect`/`replicate` pad, so those two are probed first.)
+ for border_type in ("reflect", "replicate", "circular"):
+ if border_type == "reflect" and not supports_reflect_padding(device, dtype):
+ continue
+ if border_type == "replicate" and not supports_replicate_padding(device, dtype):
+ continue
+ assert torch.equal(erosion(tensor, kernel, border_type=border_type, border_value=-5.0), tensor)
+
+ def test_convention_duality_under_negation_borders(self, device, dtype):
+ # `erosion(x, kernel, origin=o) == -dilation(-x, kernel.flip((0, 1)), origin=[k_h-1-o0, k_w-1-o1])`
+ # holds under every border and engine with a flat structuring element: `geodesic` pads -max_val on
+ # the dilation side and +max_val on the erosion side, the pixel-copying pads are symmetric under
+ # negation, and `constant` needs `border_value` negated on the dilation side. The other borders ignore
+ # `border_value` (#4758), so there an unnegated value keeps the identity; under `constant` it breaks
+ # it. The asymmetric kernel and off-centre origin make the flip and the origin map load-bearing, and
+ # both sides only select and negate values of `x`, so `torch.equal` is exact in every dtype.
+ # Generated with kornia in this worktree (torch 2.14.0 and 2.5.1, CPU and MPS): equal on all
+ # 5 borders x 3 engines; under `constant` with `border_value=5.0` on both sides the two differ.
+ # torch 2.5.1 has no half-precision CPU reflect/replicate pad, so those two follow the probes.
+ tensor = torch.rand(2, 1, 7, 9, generator=torch.Generator().manual_seed(3)) * 2 - 1
+ tensor = tensor.to(device=device, dtype=dtype)
+ kernel = torch.tensor(
+ [[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype
+ )
+ k_h, k_w = kernel.shape
+ origin = [0, 3]
+ dual_origin = [k_h - 1 - origin[0], k_w - 1 - origin[1]]
+ flipped = kernel.flip((0, 1))
+ for border_type in ("geodesic", "constant", "reflect", "replicate", "circular"):
+ if border_type == "reflect" and not supports_reflect_padding(device, dtype):
+ continue
+ if border_type == "replicate" and not supports_replicate_padding(device, dtype):
+ continue
+ for engine in ("shift", "unfold", "convolution"):
+ lhs = erosion(tensor, kernel, origin=origin, border_type=border_type, border_value=5.0, engine=engine)
+ dual_value = -5.0 if border_type == "constant" else 5.0
+ rhs = -dilation(
+ -tensor,
+ flipped,
+ origin=dual_origin,
+ border_type=border_type,
+ border_value=dual_value,
+ engine=engine,
+ )
+ assert torch.equal(lhs, rhs), (border_type, engine)
+ if border_type == "constant":
+ unnegated = -dilation(
+ -tensor, flipped, origin=dual_origin, border_type=border_type, border_value=5.0, engine=engine
+ )
+ assert not torch.equal(lhs, unnegated), engine
+
+ def test_convention_border_type_names_match_scipy_modes(self, device, dtype):
+ # `border_type` accepts the four `torch.nn.functional.pad` modes on top of `geodesic`, and the
+ # NAMES are a trap: torch's `reflect` is scipy's / scikit-image's `mirror` (the edge sample is
+ # not repeated), while their `reflect` is a different rule that kornia has no name for.
+ # A single-cell kernel at the default origin `[0, 2]` reads `x(p - 2)`, so the two leftmost
+ # outputs are pure padding and each mode is visible on its own. A full kernel cannot separate
+ # `reflect` from `replicate` at all, because both pad with values the window already contains.
+ # The ramp is integral, so every literal is exact in float16/bfloat16 too.
+ # Generated with (scipy 1.17.1, scikit-image 0.26.0, opencv-python-headless 5.0.0, numpy 2.0.0):
+ # ramp = np.array([[1., 2., 3., 4., 5.]], np.float32); K = np.array([[1, 0, 0, 0, 0]], bool)
+ # ndi.grey_erosion(ramp, footprint=K, mode=m) / sm.erosion(ramp, K, mode=m), identical:
+ # mirror -> [3, 2, 1, 2, 3] nearest -> [1, 1, 1, 2, 3]
+ # wrap -> [4, 5, 1, 2, 3] constant (cval=0) -> [0, 0, 1, 2, 3]
+ # reflect -> [2, 1, 1, 2, 3] <- NOT kornia's "reflect"
+ # cv2.erode(ramp, K, borderType=cv2.BORDER_REFLECT_101) -> [3, 2, 1, 2, 3]
+ # cv2.erode(ramp, K, borderType=cv2.BORDER_REPLICATE) -> [1, 1, 1, 2, 3]
+ # cv2.BORDER_WRAP is rejected by OpenCV's morphology.
+ ramp = torch.tensor([[1.0, 2.0, 3.0, 4.0, 5.0]], device=device, dtype=dtype)[None, None]
+ kernel = torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)
+
+ expected = {
+ "reflect": [3.0, 2.0, 1.0, 2.0, 3.0],
+ "replicate": [1.0, 1.0, 1.0, 2.0, 3.0],
+ "circular": [4.0, 5.0, 1.0, 2.0, 3.0],
+ "constant": [0.0, 0.0, 1.0, 2.0, 3.0],
+ }
+ # torch 2.5.1 has no float16 CPU `reflection_pad2d` / `replication_pad2d`; those rows follow the probes.
+ supported = {
+ "reflect": supports_reflect_padding(device, dtype),
+ "replicate": supports_replicate_padding(device, dtype),
+ }
+ for border_type, row in expected.items():
+ if not supported.get(border_type, True):
+ continue
+ actual = erosion(ramp, kernel, border_type=border_type, border_value=0.0)
+ expected_row = torch.tensor([row], device=device, dtype=dtype)[None, None]
+ assert torch.equal(actual, expected_row), border_type
+
+ def test_convention_geodesic_is_not_replicate(self, device, dtype):
+ if not supports_replicate_padding(device, dtype):
+ pytest.skip("replication_pad2d is unavailable for this device/dtype")
+ # `geodesic` and `replicate` are different modes. They can differ once the structuring element
+ # can reach outside the image -- reaching outside is necessary but not sufficient, and it is
+ # NOT only when the element stops covering the output pixel itself that they part: the
+ # gapped kernel `[[1, 0, 1, 0, 1]]` has a non-zero origin cell (default origin `[0, 2]`) and
+ # still separates them, so "covers the pixel" is not a sufficient condition for them to agree.
+ # They do agree for a rectangle of ones, where every pixel the replicate pad duplicates is
+ # already inside the window.
+ # With a single-cell kernel that reads `x(p - 2)`, `geodesic` has nothing to take the minimum
+ # over on the two leftmost pixels and returns the `max_val` sentinel instead of ignoring them
+ # (`max_val` is not an infinity; tracked in #4734), while `replicate` returns `x(0)`.
+ # The ramp and the 0/9 row are integral, and the `10000.0` literal is built at the fixture
+ # dtype so it rounds exactly the way `F.pad(..., value=max_val)` rounds it (both give 9984.0
+ # in bfloat16), so every comparison below is exact in every dtype.
+ # Generated with kornia in this worktree (torch 2.14.0, CPU, float32):
+ # erosion(ramp, [[1, 0, 0, 0, 0]]) -> [10000, 10000, 1, 2, 3]
+ # erosion(ramp, [[1, 0, 0, 0, 0]], border_type="replicate") -> [1, 1, 1, 2, 3]
+ # x = [[0, 9, 9, 9, 9]], k = [[1, 0, 1, 0, 1]] (k[0, 2] != 0, so the window covers the pixel)
+ # erosion(x, k) -> [0, 9, 0, 9, 9]
+ # erosion(x, k, border_type="replicate") -> [0, 0, 0, 9, 9]
+ # erosion(rand(1, 1, 4, 5) seed 3, F): geodesic == replicate for every rectangle of ones
+ # F in {ones(3, 3), ones(1, 4), ones(4, 1), ones(2, 2)}
+ ramp = torch.tensor([[1.0, 2.0, 3.0, 4.0, 5.0]], device=device, dtype=dtype)[None, None]
+ side_kernel = torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)
+
+ sentinel = torch.tensor([[10000.0, 10000.0, 1.0, 2.0, 3.0]], device=device, dtype=dtype)[None, None]
+ assert torch.equal(erosion(ramp, side_kernel), sentinel)
+ replicated = torch.tensor([[1.0, 1.0, 1.0, 2.0, 3.0]], device=device, dtype=dtype)[None, None]
+ assert torch.equal(erosion(ramp, side_kernel, border_type="replicate"), replicated)
+
+ # Covering the output pixel is not enough: this kernel's origin cell is a member and the two
+ # modes still disagree, because the OUTER members still reach outside the image.
+ gapped_row = torch.tensor([[0.0, 9.0, 9.0, 9.0, 9.0]], device=device, dtype=dtype)[None, None]
+ gapped_kernel = torch.tensor([[1.0, 0.0, 1.0, 0.0, 1.0]], device=device, dtype=dtype)
+ assert torch.equal(
+ erosion(gapped_row, gapped_kernel),
+ torch.tensor([[0.0, 9.0, 0.0, 9.0, 9.0]], device=device, dtype=dtype)[None, None],
+ )
+ assert torch.equal(
+ erosion(gapped_row, gapped_kernel, border_type="replicate"),
+ torch.tensor([[0.0, 0.0, 0.0, 9.0, 9.0]], device=device, dtype=dtype)[None, None],
+ )
+
+ tensor = torch.rand(1, 1, 4, 5, generator=torch.Generator().manual_seed(3)).to(device=device, dtype=dtype)
+ for shape in ((3, 3), (1, 4), (4, 1), (2, 2)):
+ full_kernel = torch.ones(*shape, device=device, dtype=dtype)
+ assert torch.equal(erosion(tensor, full_kernel), erosion(tensor, full_kernel, border_type="replicate")), (
+ shape
+ )
diff --git a/tests/morphology/test_gradient.py b/tests/morphology/test_gradient.py
index e51867864..dd85dc0ef 100644
--- a/tests/morphology/test_gradient.py
+++ b/tests/morphology/test_gradient.py
@@ -18,7 +18,8 @@
import pytest
import torch
-from kornia.morphology import gradient
+from kornia.morphology import dilation, erosion, gradient
+from kornia.morphology import morphology as morphology_module
from testing.base import BaseTester, assert_close
from testing.parametrized_tester import parametrized_test
@@ -122,3 +123,41 @@ class TestGradient(BaseTester):
expected = op(tensor, kernel)
assert_close(actual, expected)
+
+ def test_convention_gradient_is_dilation_minus_erosion(self, device, dtype, monkeypatch):
+ # `gradient` is exactly `dilation(x) - erosion(x)` with the same kernel and the same options,
+ # so every convention of :func:`kornia.morphology.dilation` applies to it unchanged -- including
+ # the kernel reflection in the dilation half and its absence in the erosion half. This pins the
+ # composition, not those conventions: both sides call the same `dilation` and `erosion`, so a
+ # reflection bug would move both sides alike (reflection is pinned in test_dilation.py and
+ # test_erosion.py). The equality is repeated with a non-default `border_type`, `border_value`, `origin`
+ # and `max_val`, so a half that dropped one of the options would show.
+ # `gradient` evaluates that very expression, so the two sides are bitwise equal in every dtype.
+ # Generated with:
+ # L = torch.tensor([[0., 0., 0.], [0., 1., 1.], [0., 1., 0.]])
+ # torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0))
+ # A local `torch.Generator` avoids touching the process-global (and any device) RNG state.
+ l_kernel = torch.tensor([[0.0, 0.0, 0.0], [0.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)
+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+
+ assert torch.equal(gradient(tensor, l_kernel), dilation(tensor, l_kernel) - erosion(tensor, l_kernel))
+ # A morphological gradient is non-negative wherever the kernel covers the pixel itself.
+ assert (gradient(tensor, l_kernel) >= 0).all()
+ # `max_val=0.1` is inside the data range, so a half that fell back to the default `1e4` would show.
+ options = {"border_type": "constant", "border_value": 0.5, "origin": [0, 0], "max_val": 0.1}
+ assert torch.equal(
+ gradient(tensor, l_kernel, **options),
+ dilation(tensor, l_kernel, **options) - erosion(tensor, l_kernel, **options),
+ )
+
+ # ... and each half receives the caller's `engine`, which its result alone need not reveal.
+ seen = []
+ resolve = morphology_module._resolve_engine
+
+ def record(engine, *args):
+ seen.append(engine)
+ return resolve(engine, *args)
+
+ monkeypatch.setattr(morphology_module, "_resolve_engine", record)
+ gradient(tensor, l_kernel, engine="unfold")
+ assert seen == ["unfold", "unfold"]
diff --git a/tests/morphology/test_opening.py b/tests/morphology/test_opening.py
index 18439181b..248c1be3a 100644
--- a/tests/morphology/test_opening.py
+++ b/tests/morphology/test_opening.py
@@ -18,9 +18,10 @@
import pytest
import torch
-from kornia.morphology import opening
+from kornia.morphology import dilation, erosion, opening
+from kornia.morphology import morphology as morphology_module
-from testing.base import BaseTester, assert_close
+from testing.base import BaseTester, assert_close, supports_replicate_padding
from testing.parametrized_tester import parametrized_test
@@ -145,3 +146,132 @@ class TestOpening(BaseTester):
opened = opening(tensor, kernel, origin=[0, 0])
assert (opened <= tensor).all()
assert torch.equal(opening(opened, kernel, origin=[0, 0]), opened)
+
+ def test_convention_opening_is_a_morphological_opening(self, device, dtype, monkeypatch):
+ # `opening` is `dilation(erosion(x))` with the SAME kernel in both halves. Because `dilation`
+ # reflects the kernel and `erosion` does not, the composition is a morphological opening:
+ # anti-extensive and idempotent for an asymmetric kernel, and it leaves a block that is a union
+ # of translates of the kernel untouched. That holds EXACTLY for the two kernels below at the
+ # default origin (and, for ones(3, 3) at origin=[0, 0], in the custom-origin test above); the
+ # last block of this test pins the kernel where it does NOT hold exactly, so the docstring's
+ # `max_val` qualification is on record rather than assumed.
+ # OpenCV composes without a flip, so its `MORPH_OPEN` is not an opening for an asymmetric
+ # kernel, nor for an even-sized one at its default anchor (`ones(2, 2)`: anti-extensive on 0 of
+ # 100 random 6x8 frames, where the odd symmetric `[[1, 0, 1]]` is on all 100).
+ # scikit-image mirrors the footprint inside `opening`, and on the 7x10 rand(seed 0)
+ # frame `sm.opening(x, A, mode="ignore")` is bit-equal to `opening(x, A)`; so is the L kernel's.
+ # For the even kernels [[1, 0]], ones(2, 2), [[1, 1, 0, 1]] and [[0, 1, 1, 1]] it is bit-equal to
+ # `opening(x, K, origin=[(k_h - 1) // 2, (k_w - 1) // 2])` (`torch.rand(1, 1, 7, 10, dtype=torch.float64)`
+ # with `torch.Generator().manual_seed(s)`, s = 0..2),
+ # where its erosion half anchors. For the three multi-cell ones it equals neither `opening(x, K)`
+ # nor the flipped-kernel opening at the default origin (ones(2, 2): 0.805 apart on seed 0); for
+ # `[[1, 0]]` the flipped-kernel opening and the earlier-origin one are both the identity, so it
+ # equals that one too. scipy has no ignore
+ # mode: `grey_opening(..., mode="constant", cval=-inf)` pads its erosion half with -inf as well,
+ # so it is anti-extensive but differs from kornia's at the border (0.61 for A, 0.37 for
+ # ones(3, 3) on `np.random.default_rng(0).random((7, 9))`) and returns -inf on the whole last column
+ # for `[[1, 0, 0]]`; it equals `blk` below only because that frame's border is already 0.
+ # 0/1 fixtures are exact in every dtype and `max`/`min` only ever select an already-present
+ # value, so both the block equality and the idempotence compare with `torch.equal`.
+ # Generated with (scipy 1.17.1, scikit-image 0.26.0, opencv-python-headless 5.0.0, numpy 2.0.0):
+ # blk = np.zeros((9, 11), np.float32); blk[3:6, 3:7] = 1.0; A = np.array([[0, 1, 1]], bool)
+ # ndi.grey_opening(blk, footprint=A, mode="constant", cval=-np.inf) == blk -> True
+ # sm.opening(blk, A, mode="ignore") == blk -> True
+ # cv2.morphologyEx(blk, cv2.MORPH_OPEN, A.astype(np.uint8)) == blk -> False
+ # torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0)) for the invariants.
+ # A local `torch.Generator` avoids touching the process-global (and any device) RNG state.
+ asymmetric = torch.tensor([[0.0, 1.0, 1.0]], device=device, dtype=dtype)
+ block = torch.zeros(1, 1, 9, 11, device=device, dtype=dtype)
+ block[..., 3:6, 3:7] = 1.0
+ assert torch.equal(opening(block, asymmetric), block)
+
+ l_kernel = torch.tensor([[0.0, 0.0, 0.0], [0.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)
+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+ opened = opening(tensor, l_kernel)
+ assert (opened <= tensor).all()
+ assert torch.equal(opening(opened, l_kernel), opened)
+
+ # The docstring names `[[0, 1, 1]]` as exact too, so the invariants are executed for it on the
+ # same frame rather than only the block equality above. Measured with kornia in this worktree
+ # (torch 2.14.0, CPU) over 20 seeds of rand(1, 1, 7, 10) in float32 and float64: the worst
+ # anti-extensivity, opening-idempotence, extensivity and closing-idempotence violation is 0.
+ asymmetric_opened = opening(tensor, asymmetric)
+ assert (asymmetric_opened <= tensor).all()
+ assert torch.equal(opening(asymmetric_opened, asymmetric), asymmetric_opened)
+
+ # The invariants are exact only up to the `max_val` sentinel, so the docstring qualifies them.
+ # `[[1, 0, 0]]` at the default origin reads `x(p + 1)`, so its window leaves the image on the
+ # right; `dilation` can then emit `x - max_val`, and the next stage's `+ max_val` returns `x`
+ # quantised to `max_val`'s spacing. Idempotence then misses by a fraction of that spacing --
+ # exactly, not approximately, zero is what a sentinel-free implementation would give.
+ # Generated with kornia in this worktree (torch 2.14.0, CPU, same rand(1, 1, 7, 10) seed 0):
+ # max|opening(opening(x)) - opening(x)|: float32 2.0671e-04, float64 0, float16 9.2969e-01,
+ # bfloat16 9.2969e-01 (float32 ULP of max_val=1e4 is 9.7656e-4; float16's is 8, bf16's 64)
+ # The float64 0 is an artefact of this frame, which is float32 `rand` cast up and so has no bits
+ # below float64's ULP of `max_val`: `torch.rand(..., dtype=torch.float64)` seed 0 misses by
+ # 6.6624e-13 (worst of 20 seeds 9.07e-13), under that ULP of 1.8190e-12 but not zero.
+ # Over 20 seeds in all four dtypes the miss stays in columns W-3 and W-2, the two before the column
+ # whose dilation window is empty, so everywhere else the idempotence is exact. That confinement is
+ # what can still fail in half precision, where one ULP of `max_val` (8 in float16, 64 in bfloat16)
+ # is wider than the data. `torch.finfo(dtype).eps * 8192` is that ULP for the default `max_val=1e4`,
+ # which lies in [8192, 16384); over 1000 frames the miss stays within half of it.
+ # On this non-negative frame anti-extensivity survives this kernel exactly; extensivity is the half
+ # that fails for `closing` (see tests/morphology/test_closing.py). Tracked in #4734.
+ one_ulp = torch.finfo(dtype).eps * 8192.0
+ side_kernel = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)
+ side_opened = opening(tensor, side_kernel)
+ assert (side_opened <= tensor).all()
+ deviation = (opening(side_opened, side_kernel) - side_opened).abs()
+ assert deviation.max() < one_ulp
+ assert not bool(deviation[..., :-3].any())
+ assert not bool(deviation[..., -1].any())
+ genuine = tensor
+ if dtype == torch.float64:
+ genuine = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0), dtype=dtype).to(device)
+ genuine_opened = opening(genuine, side_kernel)
+ genuine_miss = (opening(genuine_opened, side_kernel) - genuine_opened).abs().max()
+ assert 0.0 < genuine_miss < one_ulp
+ # On negative data the empty erosion window's `max_val + min(0, m)` carries `m` through the round trip,
+ # so the geodesic opening loses anti-extensivity too, by less than that ULP. Measured with kornia in
+ # this worktree (torch 2.14.0 and 2.5.1, CPU and MPS) on the negated frame: float32 3.5977e-04 in
+ # column 1, float16 0.99707 and bfloat16 0.99609 in columns 0-1, genuine float64 2.8855e-13.
+ negative = -genuine
+ overshoot = (opening(negative, side_kernel) - negative).clamp(min=0)
+ assert 0.0 < overshoot.max() < one_ulp
+ # An empty window is not an infinity here, and not always the sentinel either: `[0.5, 0.7]` opens to
+ # `[0.5, 0.0]` in every dtype, where scikit-image's `mode="ignore"` gives `[0.5, -inf]`.
+ pair = torch.tensor([[0.5, 0.7]], device=device, dtype=dtype)[None, None]
+ assert opening(pair, side_kernel).flatten().tolist() == [0.5, 0.0]
+
+ # That is the geodesic story only. `erosion` reads `x(p - 1)` and `dilation` reads `y(p + 1)`, so
+ # under `replicate` the last column of the opening is `x(W - 2)`, not `x(W - 1)`, and the opening
+ # is not anti-extensive at all (idempotence survives); under `circular` the two shifts cancel and
+ # the opening is exactly `x`. Measured with kornia in this worktree (torch 2.14.0, CPU, float32)
+ # over rand(1, 1, 7, 10) with `torch.Generator().manual_seed(s)`, s = 0..19: worst replicate
+ # anti-extensivity miss 0.862, worst replicate idempotence miss 0, worst circular deviation from `x` 0.
+ # torch 2.5.1 has no float16 CPU `replication_pad2d`, so the replicate lines follow the probe.
+ if supports_replicate_padding(device, dtype):
+ bump = torch.tensor([[0.0, 1.0, 0.0]], device=device, dtype=dtype)[None, None]
+ replicated = opening(bump, side_kernel, border_type="replicate")
+ assert replicated.flatten().tolist() == [0.0, 1.0, 1.0]
+ assert not bool((replicated <= bump).all())
+ assert torch.equal(opening(replicated, side_kernel, border_type="replicate"), replicated)
+ assert torch.equal(opening(tensor, side_kernel, border_type="circular"), tensor)
+
+ # The composition itself: both halves get every option. `max_val=0.1` is inside the data range, so a
+ # half that fell back to the default `1e4` would show.
+ options = {"border_type": "constant", "border_value": 0.5, "origin": [0, 0], "max_val": 0.1}
+ halves = dilation(erosion(tensor, l_kernel, **options), l_kernel, **options)
+ assert torch.equal(opening(tensor, l_kernel, **options), halves)
+
+ # ... and each half receives the caller's `engine`, which its result alone need not reveal.
+ seen = []
+ resolve = morphology_module._resolve_engine
+
+ def record(engine, *args):
+ seen.append(engine)
+ return resolve(engine, *args)
+
+ monkeypatch.setattr(morphology_module, "_resolve_engine", record)
+ opening(tensor, l_kernel, engine="unfold")
+ assert seen == ["unfold", "unfold"]
diff --git a/tests/morphology/test_top_hat.py b/tests/morphology/test_top_hat.py
index 2c47b32a7..abc97a53b 100644
--- a/tests/morphology/test_top_hat.py
+++ b/tests/morphology/test_top_hat.py
@@ -18,7 +18,8 @@
import pytest
import torch
-from kornia.morphology import top_hat
+from kornia.morphology import morphology as morphology_module
+from kornia.morphology import opening, top_hat
from testing.base import BaseTester, assert_close
from testing.parametrized_tester import parametrized_test
@@ -122,3 +123,36 @@ class TestTopHat(BaseTester):
expected = op(sample, kernel)
assert_close(actual, expected)
+
+ def test_convention_top_hat_is_image_minus_opening(self, device, dtype, monkeypatch):
+ # `top_hat` is exactly `x - opening(x)` with the same kernel and the same options, so every
+ # convention of :func:`kornia.morphology.opening` applies to it unchanged. This pins the
+ # composition: both sides call the same `opening`, whose conventions are pinned in
+ # test_opening.py. The equality is repeated with a non-default `border_type`, `border_value`, `origin`
+ # and `max_val`, so a `top_hat` that dropped one of the options would show.
+ # `top_hat` evaluates that very expression, so the two sides are bitwise equal in every dtype.
+ # Generated with:
+ # L = torch.tensor([[0., 0., 0.], [0., 1., 1.], [0., 1., 0.]])
+ # torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0))
+ # A local `torch.Generator` avoids touching the process-global (and any device) RNG state.
+ l_kernel = torch.tensor([[0.0, 0.0, 0.0], [0.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)
+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+
+ assert torch.equal(top_hat(tensor, l_kernel), tensor - opening(tensor, l_kernel))
+ # The opening is anti-extensive, so the top hat is non-negative.
+ assert (top_hat(tensor, l_kernel) >= 0).all()
+ # `max_val=0.1` is inside the data range, so a `top_hat` that dropped it for the default `1e4` would show.
+ options = {"border_type": "constant", "border_value": 0.5, "origin": [0, 0], "max_val": 0.1}
+ assert torch.equal(top_hat(tensor, l_kernel, **options), tensor - opening(tensor, l_kernel, **options))
+
+ # ... and both halves of the `opening` receive the caller's `engine`, which the result need not reveal.
+ seen = []
+ resolve = morphology_module._resolve_engine
+
+ def record(engine, *args):
+ seen.append(engine)
+ return resolve(engine, *args)
+
+ monkeypatch.setattr(morphology_module, "_resolve_engine", record)
+ top_hat(tensor, l_kernel, engine="unfold")
+ assert seen == ["unfold", "unfold"]