π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(morphology): trim convention blocks and pins to kornia scope (#4789)
Dmytro Mishkinab66872cec6f
diff --git a/changelog.d/4789.fixed.md b/changelog.d/4789.fixed.mdnew file mode 100644index 000000000..471d306c4--- /dev/null+++ b/changelog.d/4789.fixed.md@@ -0,0 +1 @@+The `kornia.morphology` docstrings are trimmed to what a caller needs: `dilation` carries the one convention block and lists the known defects (#4734, #4735, #4762) in one place, the other six functions refer to it, and an out-of-range `reflect` or `circular` pad is documented as raising an error rather than a `RuntimeError`, since that error comes from torch. The morphology table on the Conventions & Pitfalls page now holds the scipy, scikit-image and OpenCV mapping, including the kornia calls equal to their dilation, erosion, opening and closing and the `replicate` -> `nearest` and `circular` -> `wrap` border names.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 9cd034ccc..a9060b4eb 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -392,17 +392,9 @@ Serializing an augmentationMorphology------------ :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.+:func:`kornia.morphology.dilation` reflects the kernel and :func:`kornia.morphology.erosion` does not; ``origin``+is a ``[row, col]`` index and ``border_type`` takes torch's pad names. Below, ``K`` is a kernel of shape+:math:`(k_h, k_w)`, and each call row assumes the matching border from the border rows:.. list-table:::header-rows: 1@@ -417,26 +409,64 @@ Morphology- yes- no- no+ * - kornia call equal to their dilation by ``K``+ - (reference)+ - ``dilation(x, K)``+ - ``dilation(x, K.flip((0, 1)))``+ - ``dilation(x, K.flip((0, 1)), origin=[k_h - 1 - a_y, k_w - 1 - a_x])`` for ``anchor=(a_x, a_y)``; at the+ default anchor the flip alone is enough only for an odd-sized ``K``* - ``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+ * - kornia call equal to their erosion by ``K``+ - (reference)+ - ``erosion(x, K)``+ - ``erosion(x, K, origin=[(k_h - 1) // 2, (k_w - 1) // 2])``, which differs from the default only for an+ even size+ - ``erosion(x, K, origin=[a_y, a_x])``; the default anchor is the default origin+ * - kornia call equal to their opening / closing by ``K``+ - (reference)+ - ``opening(x, K)`` / ``closing(x, K)``, except under ``geodesic``: one ``cval`` serves both passes, so+ ``grey_opening`` has no ignore mode+ - ``opening(x, K, origin=[(k_h - 1) // 2, (k_w - 1) // 2])`` / ``closing(x, K.flip((0, 1)))``, and likewise+ ``white_tophat`` / ``black_tophat`` for ``top_hat`` / ``bottom_hat``+ - ``MORPH_OPEN`` / ``MORPH_CLOSE`` agree only for a ``K`` symmetric about its anchor* - origin/anchor semantics- - ``[row, col]`` index+ - ``[row, col]`` index, default ``[k_h // 2, k_w // 2]`` for even sizes too- 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)+ - ``reflect``, which repeats the edge sample (**not** torch's ``reflect``)+ - ``reflect``, the same rule as scipy's- ignore outside- * - name of torch's ``reflect``+ * - kornia's ``geodesic``+ - ``geodesic``+ - ``mode="constant"`` with ``cval=-np.inf`` (dilation) or ``np.inf`` (erosion)+ - ``mode="ignore"``+ - default border+ * - torch's ``reflect``- ``reflect``- ``mirror``- ``mirror``- ``BORDER_REFLECT_101``+ * - torch's ``replicate``+ - ``replicate``+ - ``nearest``+ - ``nearest``+ - ``BORDER_REPLICATE``+ * - torch's ``circular``+ - ``circular``+ - ``wrap``+ - ``wrap``+ - rejected (``BORDER_WRAP``)++The equivalences hold on every window that holds an in-image kernel cell while :math:`|x|` stays well below+``max_val``: an empty ``geodesic`` window returns an infinity in scipy and scikit-image and a finite value built+from ``max_val`` in kornia (`#4734 <https://github.com/kornia/kornia/issues/4734>`_).Pitfall checklist-----------------diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.pyindex d801e43c4..12a35e0d6 100644--- a/kornia/morphology/morphology.py+++ b/kornia/morphology/morphology.py@@ -158,82 +158,18 @@ 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>`_).+ - ``dilation`` reflects the structuring element: it is the Minkowski dilation+ :math:`\delta_B f(x) = \max_{b \in B} f(x - b)`, as in ``scipy.ndimage``; :func:`erosion` does not+ reflect.+ - ``border_type="geodesic"`` ignores the pixels outside the image; the other modes carry torch's pad+ names. :doc:`Conventions & Pitfalls </get-started/conventions>` maps both, and the kernel+ conventions, onto scipy, scikit-image and OpenCV.+ - Known defects: the finite ``max_val`` sentinel reaches the output in an empty window and once the+ data range approaches it (`#4734 <https://github.com/kornia/kornia/issues/4734>`_); a non-float+ image is not rejected (`#4735 <https://github.com/kornia/kornia/issues/4735>`_); and+ ``engine="convolution"`` returns the image dtype where ``unfold`` and ``shift`` return the dtype+ promoted with ``structuring_element``, or with ``kernel`` when none is given+ (`#4762 <https://github.com/kornia/kornia/issues/4762>`_).Args:tensor: Image with shape :math:`(B, C, H, W)`.@@ -251,20 +187,20 @@ def dilation(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``+ image size (``reflect``) or at most match it (``circular``), and raise an errorotherwise. 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``, andunder ``reflect``, ``replicate`` and ``circular`` it is ignored.- max_val: Finite stand-in for the infinite elements of the kernel. See the first warning above.+ max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the+ image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equaloutput; only the sign of a zero can differ, because a backend's ``max``/``min`` may return eithertied operand.``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call- which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it- to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The- measurements behind that rule are recorded in the ``_resolve_engine`` source.+ which computes in float32 or float64 (the image dtype, or the wider dtype of ``structuring_element``,+ else of ``kernel``) and records a backward graph takes ``"unfold"``, where ``"shift"`` is slower.``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds theoutput. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the@@ -362,32 +298,10 @@ 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.+ As :func:`dilation`, except that ``erosion`` does **not** reflect the structuring element: it is the+ Minkowski erosion :math:`\varepsilon_B f(x) = \min_{b \in B} f(x + b)`, as in ``scipy.ndimage`` and+ OpenCV. ``structuring_element`` is subtracted before the minimum. The known defects listed in+ :func:`dilation` apply here too.Args:tensor: Image with shape :math:`(B, C, H, W)`.@@ -405,21 +319,20 @@ def erosion(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``+ image size (``reflect``) or at most match it (``circular``), and raise an errorotherwise. 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``, andunder ``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`.+ max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the+ image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equaloutput; only the sign of a zero can differ, because a backend's ``max``/``min`` may return eithertied operand.``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call- which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it- to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The- measurements behind that rule are recorded in the ``_resolve_engine`` source.+ which computes in float32 or float64 (the image dtype, or the wider dtype of ``structuring_element``,+ else of ``kernel``) and records a backward graph takes ``"unfold"``, where ``"shift"`` is slower.``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds theoutput. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the@@ -517,36 +430,12 @@ 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`.+ ``opening`` is ``dilation(erosion(tensor))`` with the same arguments in both halves. As only+ :func:`dilation` reflects the kernel, it is a morphological opening (anti-extensive and idempotent) for+ an asymmetric kernel too, under ``geodesic`` or ``circular`` and up to the ``max_val`` sentinel+ (`#4734 <https://github.com/kornia/kornia/issues/4734>`_); a non-flat ``structuring_element`` or+ ``engine="convolution"`` holds both properties only to roundoff, and ``constant``, ``reflect`` and+ ``replicate`` can break them.Args:tensor: Image with shape :math:`(B, C, H, W)`.@@ -564,21 +453,20 @@ def opening(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``+ image size (``reflect``) or at most match it (``circular``), and raise an errorotherwise. 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``, andunder ``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`.+ max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the+ image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equaloutput; only the sign of a zero can differ, because a backend's ``max``/``min`` may return eithertied operand.``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call- which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it- to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The- measurements behind that rule are recorded in the ``_resolve_engine`` source.+ which computes in float32 or float64 (the image dtype, or the wider dtype of ``structuring_element``,+ else of ``kernel``) and records a backward graph takes ``"unfold"``, where ``"shift"`` is slower.``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds theoutput. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the@@ -648,34 +536,12 @@ 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`.+ ``closing`` is ``erosion(dilation(tensor))`` with the same arguments in both halves. As only+ :func:`dilation` reflects the kernel, it is a morphological closing (extensive and idempotent) for an+ asymmetric kernel too, under ``geodesic`` or ``circular`` and up to the ``max_val`` sentinel+ (`#4734 <https://github.com/kornia/kornia/issues/4734>`_); a non-flat ``structuring_element`` or+ ``engine="convolution"`` holds both properties only to roundoff, and ``constant``, ``reflect`` and+ ``replicate`` can break them.Args:tensor: Image with shape :math:`(B, C, H, W)`.@@ -693,21 +559,20 @@ def closing(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``+ image size (``reflect``) or at most match it (``circular``), and raise an errorotherwise. 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``, andunder ``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`.+ max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the+ image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equaloutput; only the sign of a zero can differ, because a backend's ``max``/``min`` may return eithertied operand.``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call- which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it- to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The- measurements behind that rule are recorded in the ``_resolve_engine`` source.+ which computes in float32 or float64 (the image dtype, or the wider dtype of ``structuring_element``,+ else of ``kernel``) and records a backward graph takes ``"unfold"``, where ``"shift"`` is slower.``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds theoutput. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the@@ -779,8 +644,7 @@ def gradient(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.+ ``gradient`` is ``dilation(tensor) - erosion(tensor)`` with the same arguments; see :func:`dilation`.Args:tensor: Image with shape :math:`(B, C, H, W)`.@@ -798,21 +662,20 @@ def gradient(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``+ image size (``reflect``) or at most match it (``circular``), and raise an errorotherwise. 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``, andunder ``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`.+ max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the+ image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equaloutput; only the sign of a zero can differ, because a backend's ``max``/``min`` may return eithertied operand.``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call- which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it- to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The- measurements behind that rule are recorded in the ``_resolve_engine`` source.+ which computes in float32 or float64 (the image dtype, or the wider dtype of ``structuring_element``,+ else of ``kernel``) and records a backward graph takes ``"unfold"``, where ``"shift"`` is slower.``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds theoutput. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the@@ -873,10 +736,7 @@ 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.+ ``top_hat`` is ``tensor - opening(tensor)`` with the same arguments.Args:tensor: Image with shape :math:`(B, C, H, W)`.@@ -894,21 +754,20 @@ def top_hat(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``+ image size (``reflect``) or at most match it (``circular``), and raise an errorotherwise. 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``, andunder ``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`.+ max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the+ image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equaloutput; only the sign of a zero can differ, because a backend's ``max``/``min`` may return eithertied operand.``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call- which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it- to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The- measurements behind that rule are recorded in the ``_resolve_engine`` source.+ which computes in float32 or float64 (the image dtype, or the wider dtype of ``structuring_element``,+ else of ``kernel``) and records a backward graph takes ``"unfold"``, where ``"shift"`` is slower.``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds theoutput. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the@@ -972,10 +831,7 @@ 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.+ ``bottom_hat`` is ``closing(tensor) - tensor`` with the same arguments.Args:tensor: Image with shape :math:`(B, C, H, W)`.@@ -993,21 +849,20 @@ def bottom_hat(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``+ image size (``reflect``) or at most match it (``circular``), and raise an errorotherwise. 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``, andunder ``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`.+ max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the+ image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equaloutput; only the sign of a zero can differ, because a backend's ``max``/``min`` may return eithertied operand.``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call- which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it- to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The- measurements behind that rule are recorded in the ``_resolve_engine`` source.+ which computes in float32 or float64 (the image dtype, or the wider dtype of ``structuring_element``,+ else of ``kernel``) and records a backward graph takes ``"unfold"``, where ``"shift"`` is slower.``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds theoutput. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of thediff --git a/tests/morphology/test_bottom_hat.py b/tests/morphology/test_bottom_hat.pyindex 75195f53c..1266f91a7 100644--- a/tests/morphology/test_bottom_hat.py+++ b/tests/morphology/test_bottom_hat.py@@ -18,8 +18,7 @@import pytestimport torch-from kornia.morphology import bottom_hat, closing-from kornia.morphology import morphology as morphology_module+from kornia.morphology import bottom_hatfrom testing.base import BaseTester, assert_closefrom testing.parametrized_tester import parametrized_test@@ -123,36 +122,3 @@ 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.pyindex 1126c4f47..5450b141a 100644--- a/tests/morphology/test_closing.py+++ b/tests/morphology/test_closing.py@@ -18,8 +18,7 @@import pytestimport torch-from kornia.morphology import closing, dilation, erosion-from kornia.morphology import morphology as morphology_module+from kornia.morphology import closingfrom testing.base import BaseTester, assert_close, supports_replicate_paddingfrom testing.parametrized_tester import parametrized_test@@ -142,34 +141,15 @@ class TestClosing(BaseTester):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):+ def test_convention_closing_is_a_morphological_closing(self, device, dtype):+ # `closing` is `erosion(dilation(x))` with the same kernel in both halves; as only `dilation`+ # reflects, it is extensive and idempotent for an asymmetric kernel too, and leaves a block that is+ # already closed untouched.+ # 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@@ -177,64 +157,15 @@ class TestClosing(BaseTester):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+ for kernel in (l_kernel, asymmetric):+ closed = closing(tensor, kernel)+ assert (closed >= tensor).all()+ assert torch.equal(closing(closed, kernel), closed)++ # `[[1, 0, 0]]` reads `x(p + 1)` in the dilation half and `y(p - 1)` in the erosion half. Under+ # `replicate` the first column becomes `x(1)`, so the closing is not extensive (idempotence+ # survives); under `circular` the two shifts cancel and the closing is exactly `x`.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")@@ -243,20 +174,25 @@ class TestClosing(BaseTester):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 test_wart_closing_sentinel_round_trip_4734(self, device, dtype):+ # Under `geodesic` the dilation window of `[[1, 0, 0]]` leaves the image on the right, so it can emit+ # `x - max_val`, and the erosion's `+ max_val` returns `x` quantised to `max_val`'s spacing:+ # extensivity, and on negative data idempotence, miss by less than one ULP of `max_val` in the+ # image's dtype, in the columns next to the empty window. A true infinity would miss by exactly 0.+ # Tracked in #4734. `torch.finfo(dtype).eps * 8192` is that ULP for the default `max_val=1e4`.+ one_ulp = torch.finfo(dtype).eps * 8192.0+ side_kernel = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)+ # A float64 frame drawn in float32 has no bits below float64's ULP of `max_val`, so draw it natively.+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0), dtype=torch.float64)+ tensor = tensor.to(device=device, dtype=dtype)- def record(engine, *args):- seen.append(engine)- return resolve(engine, *args)+ closed = closing(tensor, side_kernel)+ shortfall = (tensor - closed).clamp(min=0)+ assert 0.0 < shortfall.max() < one_ulp+ assert not bool(shortfall[..., :-2].any())+ assert torch.equal(closing(closed, side_kernel), closed)- monkeypatch.setattr(morphology_module, "_resolve_engine", record)- closing(tensor, l_kernel, engine="unfold")- assert seen == ["unfold", "unfold"]+ negative = -tensor+ negative_closed = closing(negative, side_kernel)+ drift = (closing(negative_closed, side_kernel) - negative_closed).abs()+ assert 0.0 < drift.max() < one_ulpdiff --git a/tests/morphology/test_composites.py b/tests/morphology/test_composites.pynew file mode 100644index 000000000..c0b3665d1--- /dev/null+++ b/tests/morphology/test_composites.py@@ -0,0 +1,61 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import pytest+import torch++from kornia.morphology import bottom_hat, closing, dilation, erosion, gradient, opening, top_hat+from kornia.morphology import morphology as morphology_module++from testing.base import BaseTester++# Each composite with the expression it is defined as, and whether its output is non-negative.+COMPOSITES = {+ "opening": (opening, lambda x, k, **o: dilation(erosion(x, k, **o), k, **o), False),+ "closing": (closing, lambda x, k, **o: erosion(dilation(x, k, **o), k, **o), False),+ "gradient": (gradient, lambda x, k, **o: dilation(x, k, **o) - erosion(x, k, **o), True),+ "top_hat": (top_hat, lambda x, k, **o: x - opening(x, k, **o), True),+ "bottom_hat": (bottom_hat, lambda x, k, **o: closing(x, k, **o) - x, True),+}+++class TestComposites(BaseTester):+ @pytest.mark.parametrize("name", list(COMPOSITES))+ def test_convention_composite_is_its_definition(self, device, dtype, monkeypatch, name):+ # Each composite evaluates its defining expression with the same kernel and options in every half,+ # so the two sides are bitwise equal in every dtype. `max_val=0.1` is inside the data range, so a+ # half that fell back to the default `1e4` would show; the engine is checked by recording it.+ op, definition, non_negative = COMPOSITES[name]+ 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(op(tensor, l_kernel), definition(tensor, l_kernel))+ if non_negative:+ assert (op(tensor, l_kernel) >= 0).all()+ options = {"border_type": "constant", "border_value": 0.5, "origin": [0, 0], "max_val": 0.1}+ assert torch.equal(op(tensor, l_kernel, **options), definition(tensor, l_kernel, **options))++ seen = []+ resolve = morphology_module._resolve_engine++ def record(engine, *args):+ seen.append(engine)+ return resolve(engine, *args)++ monkeypatch.setattr(morphology_module, "_resolve_engine", record)+ op(tensor, l_kernel, engine="unfold")+ assert seen == ["unfold", "unfold"]diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.pyindex 9f998f525..f1ee45cb7 100644--- a/tests/morphology/test_dilation.py+++ b/tests/morphology/test_dilation.py@@ -79,17 +79,8 @@ class TestDilate(BaseTester):None, None, :, :]assert_close(dilation(tensor, kernel, engine="unfold"), expected, atol=1e-4, rtol=1e-4)- # 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.+ # `engine="convolution"` feeds the geodesic `-max_val` pad through `F.conv2d`, so its error scales with+ # `max_val` (about one float32 ULP of the default 1e4 on CPU); `engine="unfold"` is exact. Tracked in #4734.assert_close(dilation(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)def test_structural_element(self, device, dtype):@@ -108,9 +99,7 @@ class TestDilate(BaseTester):),expected,)- # 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.+ # See test_kernel: the convolution engine's error scales with `max_val` (#4734).assert_close(dilation(tensor,@@ -574,42 +563,18 @@ class TestDilate(BaseTester):expected[..., row, col] = 1.0if engine == "convolution":- # 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.+ # See test_kernel: the convolution engine's error scales with `max_val` (#4734), so this+ # compares at the harness's per-dtype tolerance rather than a strict nonzero() index list.self.assert_close(actual, expected)else:assert sorted(actual.nonzero()[:, 2:].tolist()) == expected_nonzerodef 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):+ # `dilation` reflects the kernel: `out(p) = max_{q: kernel[q] != 0} x(p - (q - origin))`. The kernel+ # is asymmetric because `ones(3, 3)` cannot tell the two conventions apart.+ # Generated with scipy 1.17.1 / numpy 2.0.0 (scikit-image and OpenCV do not reflect: cols {2, 3}):# 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).+ # ndi.grey_dilation(x, footprint=A, mode="constant", cval=-np.inf) -> [0, 0, 0, 1, 1, 0, 0]tensor = torch.zeros(1, 1, 1, 7, device=device, dtype=dtype)tensor[..., 3] = 1.0kernel = torch.tensor([[0.0, 1.0, 1.0]], device=device, dtype=dtype)@@ -656,17 +621,7 @@ class TestDilate(BaseTester):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.+ # Entries of `structuring_element` under a zero `kernel` cell never reach the output.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)@@ -683,21 +638,10 @@ class TestDilate(BaseTester):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.+ # `engine="unfold"` is exact; `engine="convolution"` feeds the geodesic `-max_val` pad through+ # `F.conv2d`, so its error scales with `max_val` (#4734). This pins a bound of a few ULPs of `max_val`,+ # not the platform-dependent value. `cudnn_tf32_follows_option` keeps CUDA's float32 `conv2d` out of+ # TF32 unless `--tf32` is passed.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)@@ -707,18 +651,10 @@ class TestDilate(BaseTester):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])+ # `max_val` is a finite stand-in for infinity: it reaches the output whenever the window is empty or+ # the range of the image plus the structuring element approaches it, where scipy and scikit-image's+ # `mode="ignore"` return -inf/+inf and the true dilation. Tracked in #4734. float32 only: the literals+ # are about the float32 default `max_val=1e4` (40000 is not representable in bfloat16).dtype = torch.float32single = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)side_kernel = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)@@ -739,13 +675,8 @@ class TestDilate(BaseTester):-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.+ # 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`), where scipy returns inf (-inf).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@@ -757,8 +688,7 @@ class TestDilate(BaseTester):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+ # while no window is empty (test_erosion.py).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@@ -767,14 +697,8 @@ class TestDilate(BaseTester):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+ # structuring element that reaches `max_val` lets that border back in (scipy, cval=-inf:+ # [0, 15000, 15000, 15000]); and an all-zero kernel's empty window is `x + max_val`.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")@@ -790,28 +714,24 @@ class TestDilate(BaseTester):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.)+ # A `max_val` representable in float16 works there, in the geodesic pad and in the masked-out cells.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))+ @pytest.mark.xfail(strict=True, reason="a non-float image is not rejected (#4735)")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)+ # Only floating-point images are supported; kornia should reject the others. A `uint8` or `bool`+ # image under `border_type="constant"` runs today on every backend, so this XPASSes when #4735 adds+ # the check. Dtypes are explicit, so this pin takes `device` only.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__+ for image_dtype in (torch.uint8, torch.bool):+ image = torch.zeros(1, 1, 1, 5, dtype=image_dtype, device=device)+ for op in (dilation, erosion):+ with pytest.raises((TypeError, ValueError)):+ op(image, float_kernel, border_type="constant")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@@ -827,13 +747,9 @@ class TestDilate(BaseTester):), (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+ # `unfold` and `shift` 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, so this pin takes `device` only.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):diff --git a/tests/morphology/test_erosion.py b/tests/morphology/test_erosion.pyindex e6c4f58c6..eb9102fbe 100644--- a/tests/morphology/test_erosion.py+++ b/tests/morphology/test_erosion.py@@ -79,18 +79,8 @@ class TestErode(BaseTester):None, None, :, :]assert_close(erosion(tensor, kernel), expected, atol=1e-4, rtol=1e-4)- # 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.+ # `engine="convolution"` feeds the geodesic `+max_val` pad through `F.conv2d`, so its error scales with+ # `max_val` (about one float32 ULP of the default 1e4 on CPU); `engine="unfold"` is exact. Tracked in #4734.assert_close(erosion(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)def test_structural_element(self, device, dtype):@@ -109,9 +99,7 @@ class TestErode(BaseTester):atol=1e-4,rtol=1e-4,)- # 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.+ # See test_kernel: the convolution engine's error scales with `max_val` (#4734).assert_close(erosion(tensor,@@ -133,9 +121,7 @@ class TestErode(BaseTester):None, None, :, :]assert_close(erosion(tensor, kernel, engine="unfold"), expected, atol=1e-4, rtol=1e-4)- # 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.+ # See test_kernel: the convolution engine's error scales with `max_val` (#4734).assert_close(erosion(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)def test_exception(self, device, dtype):@@ -445,34 +431,15 @@ class TestErode(BaseTester):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):+ # `erosion` does not reflect the kernel: `out(p) = min_{q: kernel[q] != 0} x(p + (q - origin))`. The+ # complement form `1 - erosion(1 - x, A)` separates the two conventions for the asymmetric `A`.+ # 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).+ # (1 - sm.erosion(1 - x, A, mode="ignore") and 1 - cv2.erode(1 - x, A.astype(np.uint8)) agree)+ # ramp = np.array([[1., 2., 3., 0., 5., 6., 7., 8.]], np.float32); K = np.array([[1, 1, 0, 1]])+ # ndi.grey_erosion(ramp, footprint=K != 0, mode="constant", cval=1e8) -> [2, 1, 0, 2, 0, 0, 5, 6]+ # (cv2.erode agrees); sm.erosion(ramp, K != 0, mode="ignore") -> [1, 0, 2, 0, 0, 5, 6, 7]tensor = torch.zeros(1, 1, 1, 7, device=device, dtype=dtype)tensor[..., 3] = 1.0kernel = torch.tensor([[0.0, 1.0, 1.0]], device=device, dtype=dtype)@@ -484,9 +451,7 @@ class TestErode(BaseTester):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.+ # The even-sized kernel is where scikit-image centres one cell earlier than scipy and OpenCV.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]@@ -500,15 +465,9 @@ class TestErode(BaseTester):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.+ # everywhere, while no window is empty. 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. The empty-window counterexample is test_wart_dilation_max_val_sentinel_leaks_4734.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,@@ -539,29 +498,9 @@ class TestErode(BaseTester):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.+ # The default `border_type="geodesic"` ignores the pixels outside the image (scikit-image's+ # `mode="ignore"`, OpenCV's default: `cv2.erode(np.ones((3, 4), np.float32), np.ones((3, 3), np.uint8))`+ # returns all ones). `border_value` is used only under `border_type="constant"`.tensor = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)kernel = torch.ones(3, 3, device=device, dtype=dtype)@@ -574,8 +513,7 @@ class TestErode(BaseTester):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.)+ # would reach the border pixels, as it does under `constant` above.for border_type in ("reflect", "replicate", "circular"):if border_type == "reflect" and not supports_reflect_padding(device, dtype):continue@@ -585,15 +523,9 @@ class TestErode(BaseTester):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.+ # under every border and engine with a flat structuring element; under `constant` the dilation side+ # needs `border_value` negated, and the other borders ignore it. The asymmetric kernel and off-centre+ # origin make the flip and the origin map load-bearing.tensor = torch.rand(2, 1, 7, 9, generator=torch.Generator().manual_seed(3)) * 2 - 1tensor = tensor.to(device=device, dtype=dtype)kernel = torch.tensor(@@ -626,23 +558,14 @@ class TestErode(BaseTester):)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):+ def test_convention_border_type_uses_torch_pad_names(self, device, dtype):+ # `border_type` takes torch's pad names, which differ from scipy's and scikit-image's: torch's+ # `reflect` is their `mirror`, `replicate` their `nearest` and `circular` their `wrap`. A single-cell+ # kernel at the default origin `[0, 2]` reads `x(p - 2)`, so the two leftmost outputs are pure padding.+ # Generated with scipy 1.17.1 / numpy 2.0.0 (scikit-image 0.26.0 agrees):# 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.+ # ndi.grey_erosion(ramp, footprint=K, mode=m): 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]; their reflect -> [2, 1, 1, 2, 3]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)@@ -652,7 +575,6 @@ class TestErode(BaseTester):"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),@@ -667,37 +589,21 @@ class TestErode(BaseTester):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)}+ # `geodesic` and `replicate` can differ once the structuring element reaches outside the image, even+ # when its origin cell is a member (`[[1, 0, 1, 0, 1]]`); they 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)`, the two leftmost `geodesic` windows are empty (what+ # they return is the #4734 wart, pinned in test_dilation.py), while `replicate` returns `x(0)`.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)+ geodesic = erosion(ramp, side_kernel)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)+ assert torch.equal(geodesic[..., 2:], replicated[..., 2:])+ assert not bool((geodesic[..., :2] == replicated[..., :2]).any())- # 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.+ # The origin cell is a member here, and 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(diff --git a/tests/morphology/test_gradient.py b/tests/morphology/test_gradient.pyindex dd85dc0ef..e51867864 100644--- a/tests/morphology/test_gradient.py+++ b/tests/morphology/test_gradient.py@@ -18,8 +18,7 @@import pytestimport torch-from kornia.morphology import dilation, erosion, gradient-from kornia.morphology import morphology as morphology_module+from kornia.morphology import gradientfrom testing.base import BaseTester, assert_closefrom testing.parametrized_tester import parametrized_test@@ -123,41 +122,3 @@ 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.pyindex 248c1be3a..ef993e320 100644--- a/tests/morphology/test_opening.py+++ b/tests/morphology/test_opening.py@@ -18,8 +18,7 @@import pytestimport torch-from kornia.morphology import dilation, erosion, opening-from kornia.morphology import morphology as morphology_module+from kornia.morphology import openingfrom testing.base import BaseTester, assert_close, supports_replicate_paddingfrom testing.parametrized_tester import parametrized_test@@ -147,39 +146,15 @@ class TestOpening(BaseTester):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):+ def test_convention_opening_is_a_morphological_opening(self, device, dtype):+ # `opening` is `dilation(erosion(x))` with the same kernel in both halves; as only `dilation`+ # reflects, it is anti-extensive and idempotent for an asymmetric kernel too, and leaves a block that+ # is a union of translates of the kernel untouched.+ # 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@@ -187,69 +162,15 @@ class TestOpening(BaseTester):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+ for kernel in (l_kernel, asymmetric):+ opened = opening(tensor, kernel)+ assert (opened <= tensor).all()+ assert torch.equal(opening(opened, kernel), opened)++ # `[[1, 0, 0]]` reads `x(p - 1)` in the erosion half and `y(p + 1)` in the dilation half. Under+ # `replicate` the last column becomes `x(W - 2)`, so the opening is not anti-extensive (idempotence+ # survives); under `circular` the two shifts cancel and the opening is exactly `x`.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")@@ -258,20 +179,29 @@ class TestOpening(BaseTester):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 test_wart_opening_sentinel_round_trip_4734(self, device, dtype):+ # Under `geodesic` the dilation window of `[[1, 0, 0]]` leaves the image on the right, so it can emit+ # `x - max_val`, and the next stage's `+ max_val` returns `x` quantised to `max_val`'s spacing:+ # idempotence, and on negative data anti-extensivity, miss by less than one ULP of `max_val` in the+ # image's dtype, in the columns next to the empty window. A true infinity would miss by exactly 0.+ # Tracked in #4734. `torch.finfo(dtype).eps * 8192` is that ULP for the default `max_val=1e4`.+ one_ulp = torch.finfo(dtype).eps * 8192.0+ side_kernel = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)+ # A float64 frame drawn in float32 has no bits below float64's ULP of `max_val`, so draw it natively.+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0), dtype=torch.float64)+ tensor = tensor.to(device=device, dtype=dtype)- def record(engine, *args):- seen.append(engine)- return resolve(engine, *args)+ opened = opening(tensor, side_kernel)+ assert (opened <= tensor).all()+ deviation = (opening(opened, side_kernel) - opened).abs()+ assert 0.0 < deviation.max() < one_ulp+ assert not bool(deviation[..., :-3].any())+ assert not bool(deviation[..., -1].any())- monkeypatch.setattr(morphology_module, "_resolve_engine", record)- opening(tensor, l_kernel, engine="unfold")- assert seen == ["unfold", "unfold"]+ negative = -tensor+ overshoot = (opening(negative, side_kernel) - negative).clamp(min=0)+ assert 0.0 < overshoot.max() < one_ulp+ # The empty window is not an infinity: `[0.5, 0.7]` opens to `[0.5, 0.0]`, 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]diff --git a/tests/morphology/test_top_hat.py b/tests/morphology/test_top_hat.pyindex abc97a53b..2c47b32a7 100644--- a/tests/morphology/test_top_hat.py+++ b/tests/morphology/test_top_hat.py@@ -18,8 +18,7 @@import pytestimport torch-from kornia.morphology import morphology as morphology_module-from kornia.morphology import opening, top_hat+from kornia.morphology import top_hatfrom testing.base import BaseTester, assert_closefrom testing.parametrized_tester import parametrized_test@@ -123,36 +122,3 @@ 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"]