Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): return the x > threshold comparison as otsu_threshold's mask (#5182)

εŒΊζ’“ηfa19c3d689f3
diff --git a/changelog.d/5182.fixed.md b/changelog.d/5182.fixed.md
new file mode 100644
index 000000000..6b684c630
--- /dev/null
+++ b/changelog.d/5182.fixed.md
@@ -0,0 +1,6 @@
+`otsu_threshold(x, return_mask=True)` now returns the comparison `x > threshold`, taken per image and channel against
+that plane's Otsu threshold and reshaped to the input, so a foreground pixel whose value is 0 or negative is `True`
+(#5173). Previously the mask was `result > 0` with `result = x * (x > threshold)`: on data whose upper level is 0 or
+below, for example values in {-1, 0} or {-2, -1}, the threshold separated the two levels but every mask pixel came out
+`False`. Only a negative threshold is affected: the pixels in `(threshold, 0]` are now `True`, and the mask is unchanged
+whenever the data are non-negative. The thresholded image is unchanged.
diff --git a/kornia/filters/otsu_thresholding.py b/kornia/filters/otsu_thresholding.py
index 8fac6c249..c862e70e0 100644
--- a/kornia/filters/otsu_thresholding.py
+++ b/kornia/filters/otsu_thresholding.py
@@ -188,11 +188,14 @@ def otsu_threshold(
x (Tensor): Input tensor (image or batch of images).
nbins (int): Number of bins for histogram computation, default is 256.
slow_and_differentiable (bool): If True, use a differentiable histogram computation. Default is False.
- return_mask (bool): If True, return a binary mask indicating the thresholded pixels. If False,
- return the thresholded image.
+ return_mask (bool): If True, return the boolean mask ``x > threshold`` in place of the thresholded image,
+ with each pixel compared against the threshold of its own image and channel. If False, return the
+ thresholded image.
Returns:
- Tuple[torch.Tensor, torch.Tensor]: Thresholded tensor and the computed threshold values.
+ Tuple[torch.Tensor, torch.Tensor]: Thresholded tensor, or the boolean mask ``x > threshold`` when
+ ``return_mask`` is True, and the computed threshold values. The thresholded tensor cannot tell a kept pixel
+ of value 0 from a dropped one; use the mask for that.
Raises:
ValueError: If the input tensor has unsupported dimensionality or dtype.
@@ -224,6 +227,9 @@ def otsu_threshold(
result, threshold = module(x, nbins=nbins, slow_and_differentiable=slow_and_differentiable)
if return_mask:
- return result > 0, threshold
+ # `result > 0` is not the mask: it is False for a kept pixel whose value is 0 or below. Recompute the comparison
+ # `forward` applies, `x > threshold`, against the threshold of each image and channel of the flattened input.
+ x_flattened, _ = module.transform_input(x)
+ return (x_flattened > threshold[:, None]).reshape(x.shape), threshold
return result, threshold
diff --git a/tests/filters/test_otsu_thresholding.py b/tests/filters/test_otsu_thresholding.py
index 9d847c896..e4938325d 100644
--- a/tests/filters/test_otsu_thresholding.py
+++ b/tests/filters/test_otsu_thresholding.py
@@ -110,6 +110,46 @@ def test_mask(device, dtype):
assert_close(thresh_result, expected)
[email protected]("slow_and_differentiable", [False, True])
+ "values",
+ [(-1.0, 0.0), (-2.0, -1.0), (0.0, 1.0), (1.0, 2.0)],
+)
+def test_mask_is_the_comparison_5173(values, slow_and_differentiable, device, dtype):
+ # #5173: the mask used to be `result > 0`, so a foreground pixel of value 0 or below, above the threshold but not
+ # above 0, came out False. The mask is `x > threshold`, whatever the sign of the data.
+ low, high = values
+ x = torch.tensor([[low, low, high, high]], device=device, dtype=dtype)
+ mask, threshold = otsu_threshold(x, slow_and_differentiable=slow_and_differentiable, return_mask=True)
+ assert mask.dtype == torch.bool
+ assert_close(mask, x > threshold)
+ assert mask.tolist() == [[False, False, True, True]]
+
+
+def test_mask_per_channel_threshold_5173(device, dtype):
+ # Each channel of a (B, C, H, W) input has its own threshold; the mask follows its channel's comparison and keeps
+ # the input shape. Channel 0 is non-positive data, channel 1 positive.
+ x = torch.tensor([[[[-1.0, -1.0], [0.0, 0.0]], [[1.0, 1.0], [2.0, 2.0]]]], device=device, dtype=dtype)
+ mask, threshold = otsu_threshold(x, return_mask=True)
+ assert mask.shape == x.shape
+ assert threshold.shape == (2,)
+ assert_close(mask, x > threshold.reshape(1, 2, 1, 1))
+ assert mask[0, 0].tolist() == [[False, False], [True, True]]
+ assert mask[0, 1].tolist() == [[False, False], [True, True]]
+
+
[email protected]("slow_and_differentiable", [False, True])
+def test_mask_agrees_with_the_thresholded_image_5173(slow_and_differentiable, device):
+ # Integer input: the threshold is truncated to the input dtype, so on the fast path one pixel (0) equals it, and a
+ # `>=` in the mask would keep that pixel while the thresholded image drops it.
+ x = torch.tensor([[-30, -20, -10], [0, 10, 20], [30, 40, 50]], device=device)
+ image, threshold = otsu_threshold(x, slow_and_differentiable=slow_and_differentiable)
+ mask, _ = otsu_threshold(x, slow_and_differentiable=slow_and_differentiable, return_mask=True)
+ assert torch.equal(mask, x > threshold)
+ assert torch.equal(image, torch.where(mask, x, torch.zeros_like(x)))
+ assert slow_and_differentiable or (x == threshold).any() # the fixture does contain a pixel equal to the threshold
+
+
@pytest.mark.parametrize("shape", [(1, 3, 5, 5), (2, 1, 10, 10)])
def test_otsu_threshold_basic(shape, device, dtype):
img = torch.rand(shape, device=device, dtype=dtype)