Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix morphology max_val sentinel leakage (#4818)

NiteeshGowda72ada146ad0f37
diff --git a/changelog.d/4818.breaking.md b/changelog.d/4818.breaking.md
new file mode 100644
index 000000000..f06f93d2b
--- /dev/null
+++ b/changelog.d/4818.breaking.md
@@ -0,0 +1 @@
+Morphology no longer uses the finite `max_val` sentinel for floating-point images. Before, a window with no kernel cell inside the image under `border_type="geodesic"` returned a finite value built from `max_val` (for example `-9999.0` from `dilation` with the default `max_val=1e4`), and a cell the kernel excludes still contributed its pixel minus `max_val`, so data of magnitude near `max_val` gave wrong results (`dilation` of `[0, 5e4, 0]` by `[[1, 0, 1]]` returned `40000` in the middle instead of `0`). Now an empty window returns `-inf` from `dilation` and `+inf` from `erosion`, as scipy and scikit-image do; `opening`, `closing`, `gradient`, `top_hat` and `bottom_hat` inherit those infinities; and `max_val` has no effect on floating-point images.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index ec5cae37f..f8a28d62a 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -521,9 +521,8 @@ is a ``[row, col]`` index and ``border_type`` takes torch's pad names. Below, ``
- ``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>`_).
+The equivalences cover empty ``geodesic`` windows too: scipy, scikit-image and kornia all return ``-inf`` from
+such a window in a dilation and ``+inf`` in an erosion, whatever the data range.
.. _two-view-conventions:
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index e1d0263d7..0f7bf58a9 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -58,16 +58,19 @@ def _can_reduce_in_place(padded: torch.Tensor, offsets: torch.Tensor) -> bool:
def _shift_reduce(
padded: torch.Tensor,
offsets: torch.Tensor,
+ kernel: torch.Tensor,
height: int,
width: int,
dilate: bool,
inplace: bool,
+ reduction_value: Optional[float],
) -> torch.Tensor:
"""Running max (``dilate``) or min over the ``k_h * k_w`` shifted views of ``padded`` plus their offsets.
The ``shift`` engine: output pixel ``(y, x)`` reduces ``padded[y + i, x + j] + offsets[i, j]`` over the
kernel positions, the same max-plus expression ``unfold`` evaluates, without materialising the window
- tensor. ``torch.compile`` fuses the loop.
+ tensor. ``torch.compile`` fuses the loop. A cell where ``kernel`` is zero takes ``reduction_value``, the
+ reduction identity; ``None``, for a non-float image, leaves the ``max_val`` already folded into ``offsets``.
Forward-only this holds one output-sized intermediate whatever the kernel area, so peak memory is flat
in ``k_h k_w`` where ``unfold`` and ``convolution`` grow with it (24 MiB against 1627 MiB at 15 x 15,
@@ -79,6 +82,12 @@ def _shift_reduce(
# Keep each offset two-dimensional so PyTorch applies tensor-tensor dtype promotion. Indexing
# down to a scalar would instead apply wrapped-scalar rules and silently keep ``padded.dtype``.
output = padded[..., 0:height, 0:width] + offsets[0:1, 0:1]
+ if reduction_value is not None:
+ output = torch.where(
+ kernel[0, 0] != 0,
+ output,
+ torch.full_like(output, reduction_value),
+ )
# ``unfold`` reduces the kernel-height dimension first and then kernel width; keep that traversal so
# tied values are met in the same order. Which of two tied operands a backend's ``max``/``min``
# returns is its own choice (CPU keeps the first, MPS the second), so the sign of a zero result is
@@ -88,6 +97,8 @@ def _shift_reduce(
if i == 0 and j == 0:
continue
shifted = padded[..., i : i + height, j : j + width] + offsets[i : i + 1, j : j + 1]
+ if reduction_value is not None:
+ shifted.masked_fill_(kernel[i, j] == 0, reduction_value)
if inplace:
torch.maximum(output, shifted, out=output) if dilate else torch.minimum(output, shifted, out=output)
else:
@@ -181,9 +192,11 @@ def dilation(
- ``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>`_), and a non-float
- image is not rejected (`#4735 <https://github.com/kornia/kornia/issues/4735>`_).
+ - Under ``geodesic`` a window with no kernel cell inside the image is empty and returns the reduction
+ identity, ``-inf`` here and ``+inf`` in :func:`erosion`, as scipy and scikit-image do; so does every
+ window of a kernel with no non-zero cell. The composite operations inherit these infinities.
+ - Known defects: a non-float image is not rejected
+ (`#4735 <https://github.com/kornia/kornia/issues/4735>`_).
Args:
tensor: Image with shape :math:`(B, C, H, W)`.
@@ -204,10 +217,11 @@ def dilation(
image size (``reflect``) or at most match it (``circular``), and raise an error
otherwise. Any other value raises a ``ValueError``.
border_value: Value to fill past edges of input. It is used only when ``border_type`` is
- ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
- under ``reflect``, ``replicate`` and ``circular`` it is ignored.
- max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the
- image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).
+ ``constant``; under ``geodesic`` the pixels outside the image are excluded instead, and under
+ ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: No effect on a floating-point image, whose excluded kernel cells and ``geodesic`` padding take
+ the reduction identity :math:`\mp\infty`; kept for backward compatibility. A non-float image,
+ which is not supported (`#4735 <https://github.com/kornia/kornia/issues/4735>`_), still uses it.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -247,26 +261,17 @@ def dilation(
if origin is None:
origin = [se_h // 2, se_w // 2]
- # pad
- # The kernel is reflected below (Minkowski dilation), so the window is anchored at the reflected origin.
- pad_e: List[int] = [se_w - origin[1] - 1, origin[1], se_h - origin[0] - 1, origin[0]]
- if border_type == "geodesic":
- border_value = -max_val
- border_type = "constant"
- if border_type == "constant":
- output: torch.Tensor = F.pad(tensor, pad_e, mode=border_type, value=border_value)
- else:
- output = F.pad(tensor, pad_e, mode=border_type)
-
# computation
if structuring_element is None:
- # ``kernel`` is only a membership mask: a bool or integer kernel cannot hold ``-max_val``, so a
- # floating-point image lends it its dtype. A float kernel keeps its own, which may widen the result.
+ # ``kernel`` is only a membership mask, so a bool or integer kernel does not set the compute dtype: a
+ # floating-point image lends it its own. A float kernel keeps its dtype, which may widen the result.
nb_dtype = tensor.dtype if tensor.is_floating_point() and not kernel.is_floating_point() else kernel.dtype
neighborhood = torch.zeros_like(kernel, dtype=nb_dtype)
- neighborhood[kernel == 0] = -max_val
else:
neighborhood = structuring_element.clone()
+ float_image = tensor.is_floating_point()
+ if not float_image:
+ # A non-float image is not supported (#4735); keep the finite ``max_val`` arithmetic it has always had.
neighborhood[kernel == 0] = -max_val
# The max-plus terms compute in the promoted dtype, which the dtype rule of ``auto`` has to see: a
@@ -274,21 +279,72 @@ def dilation(
compute_dtype = torch.promote_types(tensor.dtype, neighborhood.dtype)
recording_grad = _records_grad(tensor, structuring_element)
engine = _resolve_engine(engine, tensor, recording_grad, compute_dtype)
+
+ # pad
+ # The kernel is reflected below (Minkowski dilation), so the window is anchored at the reflected origin.
+ pad_e: List[int] = [se_w - origin[1] - 1, origin[1], se_h - origin[0] - 1, origin[0]]
+ is_geodesic = border_type == "geodesic"
+ if border_type == "geodesic":
+ geodesic_value = -float("inf") if float_image else -max_val
+ output: torch.Tensor = F.pad(tensor, pad_e, mode="constant", value=geodesic_value)
+ elif border_type == "constant":
+ output = F.pad(tensor, pad_e, mode=border_type, value=border_value)
+ else:
+ output = F.pad(tensor, pad_e, mode=border_type)
+
+ reduction_min: float = -float("inf")
if engine == "unfold":
output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
- output, _ = torch.max(output + neighborhood.flip((0, 1)), 4)
+ output = output + neighborhood.flip((0, 1))
+ if float_image:
+ output.masked_fill_(
+ kernel.flip((0, 1)).view(1, 1, 1, 1, se_h, se_w) == 0,
+ reduction_min,
+ )
+ output, _ = torch.max(output, 4)
output, _ = torch.max(output, 4)
elif engine == "convolution":
B, C, H, W = tensor.size()
h_pad, w_pad = output.shape[-2:]
- conv_input = output.to(dtype=compute_dtype)
+ output = output.to(dtype=compute_dtype)
reshape_kernel = _neight2channels_like_kernel(kernel).to(dtype=compute_dtype)
- output, _ = F.conv2d(
- conv_input.view(B * C, 1, h_pad, w_pad),
+ conv_neighborhood = neighborhood.masked_fill(kernel == 0, 0.0) if float_image else neighborhood
+
+ # ``conv2d`` multiplies every window cell by the one-hot weight, and ``inf * 0`` or ``nan * 0`` would
+ # spread to the whole window. Convolve zeros in their place, then route a code for each non-finite
+ # value (1: +inf, 2: -inf, 3: nan) through the same one-hot weight, which reproduces it exactly.
+ special = torch.zeros_like(output)
+ if output.is_floating_point():
+ special = special.masked_fill(torch.isposinf(output), 1.0)
+ special = special.masked_fill(torch.isneginf(output), 2.0)
+ special = special.masked_fill(torch.isnan(output), 3.0)
+ output = output.masked_fill(special != 0, 0.0)
+ special = F.conv2d(special.view(B * C, 1, h_pad, w_pad), reshape_kernel, padding=0)
+ output = F.conv2d(
+ output.view(B * C, 1, h_pad, w_pad),
reshape_kernel,
padding=0,
- bias=neighborhood.view(-1).flip(0).to(dtype=compute_dtype),
- ).max(dim=1)
+ bias=conv_neighborhood.view(-1).flip(0).to(dtype=compute_dtype),
+ )
+
+ if output.is_floating_point():
+ output = output.masked_fill(special == 1, float("inf"))
+ output = output.masked_fill(special == 2, -float("inf"))
+ output = output.masked_fill(special == 3, float("nan"))
+
+ if float_image:
+ output = output.masked_fill(
+ kernel.view(-1).flip(0).view(1, -1, 1, 1) == 0,
+ reduction_min,
+ )
+
+ if is_geodesic and float_image:
+ valid = torch.ones((1, 1, H, W), dtype=output.dtype, device=output.device)
+ valid = F.pad(valid, pad_e, mode="constant", value=0.0)
+ valid = F.conv2d(valid, reshape_kernel, padding=0)
+ output = output.masked_fill(valid == 0, reduction_min)
+
+ output = output.max(dim=1).values
output = output.view(B, C, H, W)
elif engine == "shift":
offsets = neighborhood.flip((0, 1))
@@ -298,10 +354,12 @@ def dilation(
output = _shift_reduce(
output,
offsets,
+ kernel.flip((0, 1)),
tensor.shape[-2],
tensor.shape[-1],
True,
inplace,
+ reduction_min if float_image else None,
)
else:
raise NotImplementedError(f"engine {engine} is unknown, use 'auto', 'convolution', 'shift' or 'unfold'")
@@ -349,10 +407,11 @@ def erosion(
image size (``reflect``) or at most match it (``circular``), and raise an error
otherwise. Any other value raises a ``ValueError``.
border_value: Value to fill past edges of input. It is used only when ``border_type`` is
- ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
- under ``reflect``, ``replicate`` and ``circular`` it is ignored.
- max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the
- image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).
+ ``constant``; under ``geodesic`` the pixels outside the image are excluded instead, and under
+ ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: No effect on a floating-point image, whose excluded kernel cells and ``geodesic`` padding take
+ the reduction identity :math:`\mp\infty`; kept for backward compatibility. A non-float image,
+ which is not supported (`#4735 <https://github.com/kornia/kornia/issues/4735>`_), still uses it.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -392,25 +451,17 @@ def erosion(
if origin is None:
origin = [se_h // 2, se_w // 2]
- # pad
- pad_e: List[int] = [origin[1], se_w - origin[1] - 1, origin[0], se_h - origin[0] - 1]
- if border_type == "geodesic":
- border_value = max_val
- border_type = "constant"
- if border_type == "constant":
- output: torch.Tensor = F.pad(tensor, pad_e, mode=border_type, value=border_value)
- else:
- output = F.pad(tensor, pad_e, mode=border_type)
-
# computation
if structuring_element is None:
- # ``kernel`` is only a membership mask: a bool or integer kernel cannot hold ``-max_val``, so a
- # floating-point image lends it its dtype. A float kernel keeps its own, which may widen the result.
+ # ``kernel`` is only a membership mask, so a bool or integer kernel does not set the compute dtype: a
+ # floating-point image lends it its own. A float kernel keeps its dtype, which may widen the result.
nb_dtype = tensor.dtype if tensor.is_floating_point() and not kernel.is_floating_point() else kernel.dtype
neighborhood = torch.zeros_like(kernel, dtype=nb_dtype)
- neighborhood[kernel == 0] = -max_val
else:
neighborhood = structuring_element.clone()
+ float_image = tensor.is_floating_point()
+ if not float_image:
+ # A non-float image is not supported (#4735); keep the finite ``max_val`` arithmetic it has always had.
neighborhood[kernel == 0] = -max_val
# The max-plus terms compute in the promoted dtype, which the dtype rule of ``auto`` has to see: a
@@ -418,21 +469,71 @@ def erosion(
compute_dtype = torch.promote_types(tensor.dtype, neighborhood.dtype)
recording_grad = _records_grad(tensor, structuring_element)
engine = _resolve_engine(engine, tensor, recording_grad, compute_dtype)
+
+ # pad
+ pad_e: List[int] = [origin[1], se_w - origin[1] - 1, origin[0], se_h - origin[0] - 1]
+ is_geodesic = border_type == "geodesic"
+ if border_type == "geodesic":
+ geodesic_value = float("inf") if float_image else max_val
+ output: torch.Tensor = F.pad(tensor, pad_e, mode="constant", value=geodesic_value)
+ elif border_type == "constant":
+ output = F.pad(tensor, pad_e, mode=border_type, value=border_value)
+ else:
+ output = F.pad(tensor, pad_e, mode=border_type)
+
+ reduction_max: float = float("inf")
if engine == "unfold":
output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
- output, _ = torch.min(output - neighborhood, 4)
+ output = output - neighborhood
+ if float_image:
+ output.masked_fill_(
+ kernel.view(1, 1, 1, 1, se_h, se_w) == 0,
+ reduction_max,
+ )
+ output, _ = torch.min(output, 4)
output, _ = torch.min(output, 4)
elif engine == "convolution":
B, C, H, W = tensor.size()
Hpad, Wpad = output.shape[-2:]
- conv_input = output.to(dtype=compute_dtype)
+ output = output.to(dtype=compute_dtype)
reshape_kernel = _neight2channels_like_kernel(kernel).to(dtype=compute_dtype)
- output, _ = F.conv2d(
- conv_input.view(B * C, 1, Hpad, Wpad),
+ conv_neighborhood = neighborhood.masked_fill(kernel == 0, 0.0) if float_image else neighborhood
+
+ # ``conv2d`` multiplies every window cell by the one-hot weight, and ``inf * 0`` or ``nan * 0`` would
+ # spread to the whole window. Convolve zeros in their place, then route a code for each non-finite
+ # value (1: +inf, 2: -inf, 3: nan) through the same one-hot weight, which reproduces it exactly.
+ special = torch.zeros_like(output)
+ if output.is_floating_point():
+ special = special.masked_fill(torch.isposinf(output), 1.0)
+ special = special.masked_fill(torch.isneginf(output), 2.0)
+ special = special.masked_fill(torch.isnan(output), 3.0)
+ output = output.masked_fill(special != 0, 0.0)
+ special = F.conv2d(special.view(B * C, 1, Hpad, Wpad), reshape_kernel, padding=0)
+ output = F.conv2d(
+ output.view(B * C, 1, Hpad, Wpad),
reshape_kernel,
padding=0,
- bias=-neighborhood.view(-1).to(dtype=compute_dtype),
- ).min(dim=1)
+ bias=-conv_neighborhood.view(-1).to(dtype=compute_dtype),
+ )
+
+ if output.is_floating_point():
+ output = output.masked_fill(special == 1, float("inf"))
+ output = output.masked_fill(special == 2, -float("inf"))
+ output = output.masked_fill(special == 3, float("nan"))
+
+ if float_image:
+ output = output.masked_fill(
+ kernel.view(-1).view(1, -1, 1, 1) == 0,
+ reduction_max,
+ )
+
+ if is_geodesic and float_image:
+ valid = torch.ones((1, 1, H, W), dtype=output.dtype, device=output.device)
+ valid = F.pad(valid, pad_e, mode="constant", value=0.0)
+ valid = F.conv2d(valid, reshape_kernel, padding=0)
+ output = output.masked_fill(valid == 0, reduction_max)
+
+ output = output.min(dim=1).values
output = output.view(B, C, H, W)
elif engine == "shift":
offsets = -neighborhood
@@ -442,10 +543,12 @@ def erosion(
output = _shift_reduce(
output,
offsets,
+ kernel,
tensor.shape[-2],
tensor.shape[-1],
False,
inplace,
+ reduction_max if float_image else None,
)
else:
raise NotImplementedError(f"engine {engine} is unknown, use 'auto', 'convolution', 'shift' or 'unfold'")
@@ -472,8 +575,7 @@ def opening(
Convention:
``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
+ an asymmetric kernel too, under ``geodesic`` or ``circular``; a non-flat ``structuring_element`` or
``engine="convolution"`` holds both properties only to roundoff, and ``constant``, ``reflect`` and
``replicate`` can break them.
@@ -496,10 +598,11 @@ def opening(
image size (``reflect``) or at most match it (``circular``), and raise an error
otherwise. Any other value raises a ``ValueError``.
border_value: Value to fill past edges of input. It is used only when ``border_type`` is
- ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
- under ``reflect``, ``replicate`` and ``circular`` it is ignored.
- max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the
- image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).
+ ``constant``; under ``geodesic`` the pixels outside the image are excluded instead, and under
+ ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: No effect on a floating-point image, whose excluded kernel cells and ``geodesic`` padding take
+ the reduction identity :math:`\mp\infty`; kept for backward compatibility. A non-float image,
+ which is not supported (`#4735 <https://github.com/kornia/kornia/issues/4735>`_), still uses it.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -578,8 +681,7 @@ def closing(
Convention:
``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
+ asymmetric kernel too, under ``geodesic`` or ``circular``; a non-flat ``structuring_element`` or
``engine="convolution"`` holds both properties only to roundoff, and ``constant``, ``reflect`` and
``replicate`` can break them.
@@ -602,10 +704,11 @@ def closing(
image size (``reflect``) or at most match it (``circular``), and raise an error
otherwise. Any other value raises a ``ValueError``.
border_value: Value to fill past edges of input. It is used only when ``border_type`` is
- ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
- under ``reflect``, ``replicate`` and ``circular`` it is ignored.
- max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the
- image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).
+ ``constant``; under ``geodesic`` the pixels outside the image are excluded instead, and under
+ ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: No effect on a floating-point image, whose excluded kernel cells and ``geodesic`` padding take
+ the reduction identity :math:`\mp\infty`; kept for backward compatibility. A non-float image,
+ which is not supported (`#4735 <https://github.com/kornia/kornia/issues/4735>`_), still uses it.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -705,10 +808,11 @@ def gradient(
image size (``reflect``) or at most match it (``circular``), and raise an error
otherwise. Any other value raises a ``ValueError``.
border_value: Value to fill past edges of input. It is used only when ``border_type`` is
- ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
- under ``reflect``, ``replicate`` and ``circular`` it is ignored.
- max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the
- image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).
+ ``constant``; under ``geodesic`` the pixels outside the image are excluded instead, and under
+ ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: No effect on a floating-point image, whose excluded kernel cells and ``geodesic`` padding take
+ the reduction identity :math:`\mp\infty`; kept for backward compatibility. A non-float image,
+ which is not supported (`#4735 <https://github.com/kornia/kornia/issues/4735>`_), still uses it.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -797,10 +901,11 @@ def top_hat(
image size (``reflect``) or at most match it (``circular``), and raise an error
otherwise. Any other value raises a ``ValueError``.
border_value: Value to fill past edges of input. It is used only when ``border_type`` is
- ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
- under ``reflect``, ``replicate`` and ``circular`` it is ignored.
- max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the
- image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).
+ ``constant``; under ``geodesic`` the pixels outside the image are excluded instead, and under
+ ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: No effect on a floating-point image, whose excluded kernel cells and ``geodesic`` padding take
+ the reduction identity :math:`\mp\infty`; kept for backward compatibility. A non-float image,
+ which is not supported (`#4735 <https://github.com/kornia/kornia/issues/4735>`_), still uses it.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
@@ -892,10 +997,11 @@ def bottom_hat(
image size (``reflect``) or at most match it (``circular``), and raise an error
otherwise. Any other value raises a ``ValueError``.
border_value: Value to fill past edges of input. It is used only when ``border_type`` is
- ``constant``: under ``geodesic`` it is silently overwritten with :math:`\mp` ``max_val``, and
- under ``reflect``, ``replicate`` and ``circular`` it is ignored.
- max_val: Finite stand-in for the infinite elements of the kernel. Keep it well above the range of the
- image plus ``structuring_element`` and finite in the image's dtype (at most 65504 for ``float16``).
+ ``constant``; under ``geodesic`` the pixels outside the image are excluded instead, and under
+ ``reflect``, ``replicate`` and ``circular`` it is ignored.
+ max_val: No effect on a floating-point image, whose excluded kernel cells and ``geodesic`` padding take
+ the reduction identity :math:`\mp\infty`; kept for backward compatibility. A non-float image,
+ which is not supported (`#4735 <https://github.com/kornia/kornia/issues/4735>`_), still uses it.
engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``
and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal
output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either
diff --git a/tests/morphology/test_closing.py b/tests/morphology/test_closing.py
index 5450b141a..685763d8b 100644
--- a/tests/morphology/test_closing.py
+++ b/tests/morphology/test_closing.py
@@ -174,25 +174,19 @@ 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)
- 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
+ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution"])
+ def test_convention_closing_empty_geodesic_window_is_infinite_4734(self, device, dtype, engine):
+ # Under `geodesic` the dilation window of `[[1, 0, 0]]` is empty in the first column, which becomes
+ # `+inf`; every other column round-trips exactly, so closing is extensive and idempotent on data of
+ # either sign. Before #4734 the finite `max_val` sentinel made both miss by up to one ULP of `max_val`.
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)
-
- 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)
-
- negative = -tensor
- negative_closed = closing(negative, side_kernel)
- drift = (closing(negative_closed, side_kernel) - negative_closed).abs()
- assert 0.0 < drift.max() < one_ulp
+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0), dtype=torch.float64).to(
+ device=device, dtype=dtype
+ )
+
+ for data in (tensor, -tensor):
+ closed = closing(data, side_kernel, engine=engine)
+ expected = torch.cat((torch.full_like(data[..., :1], float("inf")), data[..., 1:]), dim=-1)
+ assert torch.equal(closed, expected)
+ assert (closed >= data).all()
+ assert torch.equal(closing(closed, side_kernel, engine=engine), closed)
diff --git a/tests/morphology/test_composites.py b/tests/morphology/test_composites.py
index c0b3665d1..b92b0b1e1 100644
--- a/tests/morphology/test_composites.py
+++ b/tests/morphology/test_composites.py
@@ -37,8 +37,8 @@ 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.
+ # so the two sides are bitwise equal in every dtype. A non-default `border_value` and `origin` would
+ # show a half that fell back to its default; 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)
@@ -46,7 +46,7 @@ class TestComposites(BaseTester):
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}
+ options = {"border_type": "constant", "border_value": 0.5, "origin": [0, 0]}
assert torch.equal(op(tensor, l_kernel, **options), definition(tensor, l_kernel, **options))
seen = []
@@ -59,3 +59,18 @@ class TestComposites(BaseTester):
monkeypatch.setattr(morphology_module, "_resolve_engine", record)
op(tensor, l_kernel, engine="unfold")
assert seen == ["unfold", "unfold"]
+
+ @pytest.mark.parametrize("name", ["opening", "closing", "top_hat", "bottom_hat"])
+ def test_convention_composite_convolution_handles_infinite_intermediates_4734(self, device, dtype, name):
+ if not dtype.is_floating_point:
+ pytest.skip("Infinity regression requires a floating-point dtype.")
+
+ op = COMPOSITES[name][0]
+ kernel = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)
+ tensor = torch.tensor([[[[0.2, 0.5, 0.9, 0.4]]]], device=device, dtype=dtype)
+
+ convolved = op(tensor, kernel, engine="convolution")
+ unfolded = op(tensor, kernel, engine="unfold")
+
+ assert not torch.isnan(convolved).any()
+ self.assert_close(convolved, unfolded)
diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.py
index 7b657ac8f..b8c76ea15 100644
--- a/tests/morphology/test_dilation.py
+++ b/tests/morphology/test_dilation.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import functools
+
import pytest
import torch
@@ -79,8 +81,7 @@ class TestDilate(BaseTester):
None, None, :, :
]
assert_close(dilation(tensor, kernel, engine="unfold"), expected, atol=1e-4, rtol=1e-4)
- # `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.
+ # The convolution and unfold engines agree within the test tolerance.
assert_close(dilation(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)
def test_structural_element(self, device, dtype):
@@ -99,7 +100,7 @@ class TestDilate(BaseTester):
),
expected,
)
- # See test_kernel: the convolution engine's error scales with `max_val` (#4734).
+ # The convolution and unfold engines agree within the test tolerance.
assert_close(
dilation(
tensor,
@@ -170,6 +171,19 @@ class TestDilate(BaseTester):
assert actual.dtype == torch.int64
assert actual.flatten().tolist() == [3, 0, 3, 7, 0]
+ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution"])
+ def test_integer_image_keeps_max_val_arithmetic(self, device, engine):
+ # A non-float image keeps the finite `max_val` pad and exclusion until #4735 rejects it. A pad at the
+ # dtype minimum would wrap once a negative integer structuring element is added to it.
+ if engine == "convolution" and device.type == "mps":
+ pytest.skip("MPS has no integer convolution")
+ tensor = torch.tensor([[[[-5, -1, -6, -7]]]], dtype=torch.int32, device=device)
+ kernel = torch.tensor([[1, 0, 1]], dtype=torch.int32, device=device)
+ structuring_element = torch.full((1, 3), -1, dtype=torch.int32, device=device)
+ actual = dilation(tensor, kernel, structuring_element=structuring_element, engine=engine)
+ assert actual.dtype == torch.int32
+ assert actual.flatten().tolist() == [-2, -6, -2, -7]
+
@pytest.mark.parametrize("border_type", ["geodesic", "constant", "reflect", "replicate", "circular"])
def test_accepted_border_types(self, device, dtype, border_type):
# Every documented border_type must pass the validation (#4736).
@@ -522,7 +536,7 @@ class TestDilate(BaseTester):
original = morphology_module._shift_reduce
def wrapped(*args, **kwargs):
- calls.append(args[-1])
+ calls.append(args[-2])
return original(*args, **kwargs)
monkeypatch.setattr(morphology_module, "_shift_reduce", wrapped)
@@ -666,8 +680,7 @@ class TestDilate(BaseTester):
expected[..., row, col] = 1.0
if engine == "convolution":
- # 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.
+ # Compare 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_nonzero
@@ -740,89 +753,105 @@ class TestDilate(BaseTester):
assert torch.equal(dilation(tensor, masked_kernel, structuring_element=loud), dilation(tensor, masked_kernel))
assert torch.equal(erosion(tensor, masked_kernel, structuring_element=loud), erosion(tensor, masked_kernel))
- def test_convention_engines_agree_within_a_few_ulps_of_max_val(self, device, dtype, cudnn_tf32_follows_option):
- # `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.
+ def test_convention_engines_agree_independent_of_max_val(self, device, dtype, cudnn_tf32_follows_option):
+ # The convolution and unfold engines should agree independently of the finite `max_val`.
+ # `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)
for max_val in (1.0, 1e2, 1e4):
unfolded = dilation(tensor, kernel, max_val=max_val, engine="unfold")
convolved = dilation(tensor, kernel, max_val=max_val, engine="convolution")
- self.assert_close(convolved, unfolded, atol=4.0 * torch.finfo(dtype).eps * max_val, rtol=0.0)
+ self.assert_close(convolved, unfolded)
- def test_wart_dilation_max_val_sentinel_leaks_4734(self, device):
- # `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).
+ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution"])
+ def test_convention_dilation_ignores_finite_max_val_sentinel_4734(self, device, engine):
+ # Geodesic padding and masked kernel cells are excluded rather than represented by a finite
+ # sentinel: an empty window returns the reduction identity (`-inf` for dilation, `+inf` for erosion),
+ # as scipy (`cval=-inf`/`inf`) and scikit-image (`mode="ignore"`) do, and the result no longer depends on
+ # `max_val` or on the image range. float32 only: 5e4 and 15000 are not exact in half precision.
dtype = torch.float32
+ dilate = functools.partial(dilation, engine=engine)
+ erode = functools.partial(erosion, engine=engine)
single = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)
side_kernel = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)
- # The window is empty at this origin, so the output is the sentinel plus the pixel, not the pixel.
- assert dilation(single, side_kernel, origin=[0, 2]).item() == -9999.0
- assert erosion(single, side_kernel, origin=[0, 2]).item() == 10000.0
+ # The window is empty at this origin, so dilation/erosion return their reduction identities.
+ assert dilate(single, side_kernel, origin=[0, 2]).item() == float("-inf")
+ assert erode(single, side_kernel, origin=[0, 2]).item() == float("inf")
big = torch.tensor([[0.0, 5e4, 0.0]], device=device, dtype=dtype)[None, None]
gapped_kernel = torch.tensor([[1.0, 0.0, 1.0]], device=device, dtype=dtype)
- assert dilation(big, gapped_kernel).flatten().tolist() == [50000.0, 40000.0, 50000.0]
- # With a `max_val` above the image range the same call is correct, which is the diagnosis.
- assert dilation(big, gapped_kernel, max_val=1e6).flatten().tolist() == [50000.0, 0.0, 50000.0]
+ assert dilate(big, gapped_kernel).flatten().tolist() == [50000.0, 0.0, 50000.0]
+ # The result is independent of the finite `max_val` because excluded cells are masked out.
+ assert dilate(big, gapped_kernel, max_val=1e6).flatten().tolist() == [50000.0, 0.0, 50000.0]
negative = torch.tensor([[-5e4, -6e4]], device=device, dtype=dtype)[None, None]
- assert dilation(negative, torch.ones(1, 3, device=device, dtype=dtype)).flatten().tolist() == [
- -10000.0,
- -10000.0,
+ assert dilate(negative, torch.ones(1, 3, device=device, dtype=dtype)).flatten().tolist() == [
+ -50000.0,
+ -50000.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`), where scipy returns inf (-inf).
+ # A masked-out in-image cell must be excluded just like an out-of-image cell.
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
+ assert erode(minus_two, corner_kernel, origin=[0, 0]).item() == float("inf")
five = torch.full((1, 1, 1, 1), 5.0, device=device, dtype=dtype)
- assert dilation(five, corner_kernel, origin=[0, 0]).item() == -9995.0
- # The same sentinel is stored into a structuring element when one is given.
+ assert dilate(five, corner_kernel, origin=[0, 0]).item() == float("-inf")
+ # The same masking applies when a structuring element is given.
flat_corner = torch.zeros_like(corner_kernel)
- assert erosion(minus_two, corner_kernel, structuring_element=flat_corner, origin=[0, 0]).item() == 9998.0
- assert dilation(five, corner_kernel, structuring_element=flat_corner, origin=[0, 0]).item() == -9995.0
-
- # The same empty window breaks the adjunction `dilation(x) <= y <=> x <= erosion(y)`, which holds
- # while no window is empty (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
- assert eroded.item() == -1.0
- assert not bool((dilated <= minus_two).all())
- assert bool((minus_two <= eroded).all())
-
- # Only the geodesic border is padded with the sentinel (`constant` pads `border_value`); a non-flat
- # structuring element that reaches `max_val` lets that border back in (scipy, cval=-inf:
- # [0, 15000, 15000, 15000]); and an all-zero kernel's empty window is `x + max_val`.
+ assert erode(minus_two, corner_kernel, structuring_element=flat_corner, origin=[0, 0]).item() == float("inf")
+ assert dilate(five, corner_kernel, structuring_element=flat_corner, origin=[0, 0]).item() == float("-inf")
+
+ # Empty windows now use the reduction identities rather than a finite `max_val` sentinel.
+ dilated = dilate(minus_two, corner_kernel, origin=[0, 0], max_val=1.0)
+ eroded = erode(minus_two, corner_kernel, origin=[0, 0], max_val=1.0)
+ assert dilated.item() == float("-inf")
+ assert eroded.item() == float("inf")
+
+ # Geodesic padding ignores pixels outside the image; constant padding still uses `border_value`.
+ # A non-flat structuring element can therefore still make an outside position contribute through its
+ # actual structuring-element value, while an all-zero kernel has an empty window.
ramp = torch.tensor([[3.0, 4.0, 5.0]], device=device, dtype=dtype)[None, None]
- assert dilation(ramp, corner_kernel, origin=[0, 0]).flatten().tolist() == [-9997.0, 3.0, 4.0]
- constant_ramp = dilation(ramp, corner_kernel, origin=[0, 0], border_type="constant")
+ assert dilate(ramp, corner_kernel, origin=[0, 0]).flatten().tolist() == [float("-inf"), 3.0, 4.0]
+ constant_ramp = dilate(ramp, corner_kernel, origin=[0, 0], border_type="constant")
assert constant_ramp.flatten().tolist() == [0.0, 3.0, 4.0]
- valued_ramp = dilation(ramp, corner_kernel, origin=[0, 0], border_type="constant", border_value=7.0)
+ valued_ramp = dilate(ramp, corner_kernel, origin=[0, 0], border_type="constant", border_value=7.0)
assert valued_ramp.flatten().tolist() == [7.0, 3.0, 4.0]
tall_se = torch.tensor([[0.0, 0.0, 15000.0]], device=device, dtype=dtype)
- leaked = dilation(
+ leaked = dilate(
torch.zeros(1, 1, 1, 4, device=device, dtype=dtype),
torch.ones(1, 3, device=device, dtype=dtype),
structuring_element=tall_se,
)
- assert leaked.flatten().tolist() == [5000.0, 15000.0, 15000.0, 15000.0]
- assert erosion(five, torch.zeros(1, 1, device=device, dtype=dtype)).item() == 10005.0
+ assert leaked.flatten().tolist() == [0.0, 15000.0, 15000.0, 15000.0]
+ assert erode(five, torch.zeros(1, 1, device=device, dtype=dtype)).item() == float("inf")
- # A `max_val` representable in float16 works there, in the geodesic pad and in the masked-out cells.
+ # `max_val` no longer affects geodesic padding or 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))
+ assert torch.equal(dilate(half_image, half_cross, max_val=65504.0), dilate(half_image, half_cross))
+
+ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution"])
+ def test_convention_non_finite_inputs_agree_across_engines_4734(self, device, dtype, engine):
+ # A NaN or an infinity inside the window reaches the output; one in a cell the kernel excludes does
+ # not. `convolution` multiplies every window cell by a one-hot weight, so it has to keep `inf * 0` and
+ # `nan * 0` out of the excluded cells without dropping the values of the included ones.
+ nan, inf = float("nan"), float("inf")
+ tensor = torch.tensor([[[[0.25, nan, 0.75, inf, 0.5, -inf, 0.75]]]], device=device, dtype=dtype)
+ side_kernel = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)
+ cases = [
+ (dilation, torch.ones(1, 3, device=device, dtype=dtype), [nan, nan, nan, inf, inf, 0.75, 0.75]),
+ (erosion, torch.ones(1, 3, device=device, dtype=dtype), [nan, nan, nan, 0.5, -inf, -inf, -inf]),
+ (dilation, side_kernel, [nan, 0.75, inf, 0.5, -inf, 0.75, -inf]),
+ (erosion, side_kernel, [inf, 0.25, nan, 0.75, inf, 0.5, -inf]),
+ ]
+ for op, kernel, expected in cases:
+ actual = op(tensor, kernel, engine=engine).flatten()
+ expected_tensor = torch.tensor(expected, device=device, dtype=actual.dtype)
+ torch.testing.assert_close(actual, expected_tensor, rtol=0.0, atol=0.0, equal_nan=True)
@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):
@@ -837,8 +866,8 @@ class TestDilate(BaseTester):
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
- # `kernel == 0` mask, and a `uint8` or `bool` kernel returns what the floating kernel does.
+ # With a floating structuring element the kernel is only the `kernel == 0` mask, so a `uint8` or
+ # `bool` kernel returns what the floating kernel does.
frame = torch.rand(1, 1, 4, 5, generator=torch.Generator().manual_seed(0)).to(device, dtype)
flat_se = torch.zeros(1, 3, device=device, dtype=dtype)
float_kernel = torch.tensor([[1.0, 0.0, 1.0]], device=device, dtype=dtype)
diff --git a/tests/morphology/test_erosion.py b/tests/morphology/test_erosion.py
index fc8a5c7af..a63779c3e 100644
--- a/tests/morphology/test_erosion.py
+++ b/tests/morphology/test_erosion.py
@@ -79,8 +79,7 @@ class TestErode(BaseTester):
None, None, :, :
]
assert_close(erosion(tensor, kernel), expected, atol=1e-4, rtol=1e-4)
- # `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.
+ # The convolution and unfold engines agree within the test tolerance.
assert_close(erosion(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)
def test_structural_element(self, device, dtype):
@@ -99,7 +98,7 @@ class TestErode(BaseTester):
atol=1e-4,
rtol=1e-4,
)
- # See test_kernel: the convolution engine's error scales with `max_val` (#4734).
+ # The convolution and unfold engines agree within the test tolerance.
assert_close(
erosion(
tensor,
@@ -121,7 +120,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's error scales with `max_val` (#4734).
+ # The convolution and unfold engines agree within the test tolerance.
assert_close(erosion(tensor, kernel, engine="convolution"), expected, atol=1e-3, rtol=1e-3)
def test_exception(self, device, dtype):
@@ -169,6 +168,18 @@ class TestErode(BaseTester):
assert actual.dtype == torch.int64
assert actual.flatten().tolist() == [3, 0, 0, 0, 0]
+ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution"])
+ def test_integer_image_keeps_max_val_arithmetic(self, device, engine):
+ # A non-float image keeps the finite `max_val` pad and exclusion until #4735 rejects it. The int64
+ # maximum is not representable as a float, so a pad at the dtype maximum cannot be written.
+ if engine == "convolution" and device.type == "mps":
+ pytest.skip("MPS has no integer convolution")
+ tensor = torch.tensor([[[[1, 5, 2, 7]]]], dtype=torch.int64, device=device)
+ kernel = torch.tensor([[1, 0, 1]], dtype=torch.int64, device=device)
+ actual = erosion(tensor, kernel, engine=engine)
+ assert actual.dtype == torch.int64
+ assert actual.flatten().tolist() == [5, 1, 5, 2]
+
@pytest.mark.parametrize("border_type", ["geodesic", "constant", "reflect", "replicate", "circular"])
def test_accepted_border_types(self, device, dtype, border_type):
# Every documented border_type must pass the validation (#4736).
@@ -508,7 +519,7 @@ class TestErode(BaseTester):
original = morphology_module._shift_reduce
def wrapped(*args, **kwargs):
- calls.append(args[-1])
+ calls.append(args[-2])
return original(*args, **kwargs)
monkeypatch.setattr(morphology_module, "_shift_reduce", wrapped)
@@ -570,7 +581,8 @@ class TestErode(BaseTester):
# origin are an adjoint pair, `dilation(x) <= y` everywhere exactly when `x <= erosion(y)`
# 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.
+ # window is empty. Empty windows use the reduction identity; see
+ # test_convention_dilation_ignores_finite_max_val_sentinel_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,
@@ -696,7 +708,7 @@ class TestErode(BaseTester):
# 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)`.
+ # they return is the reduction identity, 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)
diff --git a/tests/morphology/test_opening.py b/tests/morphology/test_opening.py
index ef993e320..c845b77f3 100644
--- a/tests/morphology/test_opening.py
+++ b/tests/morphology/test_opening.py
@@ -179,29 +179,22 @@ 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)
- 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
+ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution"])
+ def test_convention_opening_empty_geodesic_window_is_infinite_4734(self, device, dtype, engine):
+ # Under `geodesic` the dilation window of `[[1, 0, 0]]` is empty in the last column, which becomes
+ # `-inf`; every other column round-trips exactly, so opening is anti-extensive and idempotent on data
+ # of either sign, and `[0.5, 0.7]` opens to `[0.5, -inf]` as in scikit-image's `mode="ignore"`. Before
+ # #4734 the finite `max_val` sentinel made both miss by up to one ULP of `max_val`.
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)
+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0), dtype=torch.float64).to(
+ device=device, dtype=dtype
+ )
- 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())
-
- 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]`.
+ for data in (tensor, -tensor):
+ opened = opening(data, side_kernel, engine=engine)
+ expected = torch.cat((data[..., :-1], torch.full_like(data[..., :1], -float("inf"))), dim=-1)
+ assert torch.equal(opened, expected)
+ assert (opened <= data).all()
+ assert torch.equal(opening(opened, side_kernel, engine=engine), opened)
pair = torch.tensor([[0.5, 0.7]], device=device, dtype=dtype)[None, None]
- assert opening(pair, side_kernel).flatten().tolist() == [0.5, 0.0]
+ assert opening(pair, side_kernel, engine=engine).flatten().tolist() == [0.5, float("-inf")]