π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): compare integer images with threshold's thresh as given (#5465)
Mohammad Hijjawibddf9de96526
diff --git a/changelog.d/5465.fixed.md b/changelog.d/5465.fixed.mdnew file mode 100644index 000000000..7a52f0cb1--- /dev/null+++ b/changelog.d/5465.fixed.md@@ -0,0 +1 @@+`threshold` and `Threshold` now compare an integer image with `thresh` as given: a fractional threshold is rounded down instead of truncated toward zero, and a threshold outside the image dtype's range passes every pixel or none instead of wrapping or raising.diff --git a/kornia/enhance/threshold.py b/kornia/enhance/threshold.pyindex 6c7f6c52a..b89959b2c 100644--- a/kornia/enhance/threshold.py+++ b/kornia/enhance/threshold.py@@ -46,6 +46,30 @@ class ThresholdType(IntEnum):THRESH_OTSU = 8+def _integer_threshold(input: Tensor, thresh: Union[float, Tensor]) -> tuple[Tensor, Tensor]:+ """Return ``input > thresh`` and the value THRESH_TRUNC writes, for an integer ``input``.++ Casting ``thresh`` to an integer dtype truncates a fraction toward zero and wraps or rejects a value outside the+ dtype's range, so the comparison would use another threshold. An integer is greater than ``thresh`` exactly when+ it is greater than ``floor(thresh)``, which OpenCV also compares with. A threshold below the dtype's range passes+ every element, one at or above its maximum passes none, and ``nan`` passes none, as for a floating-point input.+ """+ low, high = (0, 1) if input.dtype == torch.bool else (torch.iinfo(input.dtype).min, torch.iinfo(input.dtype).max)+ if not isinstance(thresh, Tensor):+ # float64 and int64 hold any Python number a pixel can be compared with. The tensor stays on the CPU, as MPS+ # has no float64; only the results below move to the input's device.+ thresh = torch.tensor(thresh, dtype=torch.int64 if isinstance(thresh, int) else torch.float64)+ if thresh.is_floating_point():+ thresh = thresh.floor()+ below = thresh < low+ inside = (thresh >= low) & (thresh < high)+ safe = torch.where(inside, thresh, 0).to(input.dtype).to(input.device)+ below, inside = below.to(input.device), inside.to(input.device)+ mask = ((input > safe) & inside) | below+ # Where an element passes, the threshold is in range, or below it and the element is clamped to the minimum.+ return mask, torch.where(below, torch.full_like(safe, low), safe)++def threshold(input: Tensor,thresh: Union[float, Tensor],@@ -56,8 +80,14 @@ def threshold(Convention:The comparison is strict (input > thresh). thresh and maxval broadcast- over input after being converted to its dtype and device. Threshold is- the module wrapper; ThresholdType supplies the fixed-mode values.+ over input on its device. maxval is converted to the input's dtype, and+ so is thresh on a floating-point input. On an integer input, thresh is+ not cast: as in OpenCV, an element passes when it is greater than+ floor(thresh), so a thresh below the dtype's range passes every element+ and one at or above its maximum passes none. THRESH_TRUNC then writes+ floor(thresh), or the dtype's minimum for a thresh below its range.+ Threshold is the module wrapper; ThresholdType supplies the fixed-mode+ values.Implements OpenCV-like behavior for the following threshold types:- THRESH_BINARY@@ -93,11 +123,15 @@ def threshold()# Make thresh/maxval tensors on same device/dtype for safe broadcasting- thresh_t = thresh- if not isinstance(thresh_t, Tensor):- thresh_t = torch.tensor(thresh_t, device=input.device, dtype=input.dtype)+ if input.is_floating_point() or input.is_complex():+ thresh_t = thresh+ if not isinstance(thresh_t, Tensor):+ thresh_t = torch.tensor(thresh_t, device=input.device, dtype=input.dtype)+ else:+ thresh_t = thresh_t.to(device=input.device, dtype=input.dtype)+ mask = input > thresh_telse:- thresh_t = thresh_t.to(device=input.device, dtype=input.dtype)+ mask, thresh_t = _integer_threshold(input, thresh)maxval_t = maxvalif not isinstance(maxval_t, Tensor):@@ -105,7 +139,6 @@ def threshold(else:maxval_t = maxval_t.to(device=input.device, dtype=input.dtype)- mask = input > thresh_tzeros = torch.zeros_like(input)if t == int(ThresholdType.THRESH_BINARY):@@ -115,7 +148,9 @@ def threshold(return torch.where(mask, zeros, maxval_t)if t == int(ThresholdType.THRESH_TRUNC):- return torch.minimum(input, thresh_t)+ if input.is_floating_point() or input.is_complex():+ return torch.minimum(input, thresh_t)+ return torch.where(mask, thresh_t, input)if t == int(ThresholdType.THRESH_TOZERO):return torch.where(mask, input, zeros)diff --git a/tests/enhance/test_threshold.py b/tests/enhance/test_threshold.pyindex 8d21f5c6e..0537fedf2 100644--- a/tests/enhance/test_threshold.py+++ b/tests/enhance/test_threshold.py@@ -75,3 +75,37 @@ class TestThreshold:x = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)with pytest.raises(NotImplementedError):threshold(x, thresh=0.0, maxval=1.0, type=ThresholdType.THRESH_OTSU)++ @pytest.mark.parametrize(+ "image_dtype, values, thresh, ttype, expected",+ [+ # A threshold below the range passes every element instead of wrapping to 255 or raising.+ (torch.uint8, [0, 100, 255], -1, ThresholdType.THRESH_BINARY, [9, 9, 9]),+ (torch.uint8, [0, 100, 255], -0.5, ThresholdType.THRESH_BINARY, [9, 9, 9]),+ (torch.uint8, [0, 100, 255], -1, ThresholdType.THRESH_TRUNC, [0, 0, 0]),+ # A threshold above the range passes no element instead of raising.+ (torch.uint8, [0, 100, 255], 300, ThresholdType.THRESH_BINARY_INV, [9, 9, 9]),+ (torch.uint8, [0, 100, 255], 255.5, ThresholdType.THRESH_TOZERO, [0, 0, 0]),+ # A negative fraction is rounded down, not truncated toward zero.+ (torch.int16, [-2, -1, 0, 1], -0.5, ThresholdType.THRESH_BINARY, [0, 0, 9, 9]),+ (torch.int16, [-2, -1, 0, 1], -1.5, ThresholdType.THRESH_TRUNC, [-2, -2, -2, -2]),+ (torch.int16, [-2, -1, 0, 1], -1.5, ThresholdType.THRESH_TOZERO_INV, [-2, 0, 0, 0]),+ (torch.uint8, [100, 101], 100.7, ThresholdType.THRESH_BINARY, [0, 9]),+ (torch.int16, [-1, 0, 1], float("nan"), ThresholdType.THRESH_TOZERO, [0, 0, 0]),+ (torch.int64, [2**60, 2**60 + 1, 2**60 + 2], 2**60 + 1, ThresholdType.THRESH_BINARY, [0, 0, 9]),+ # A threshold at the dtype's minimum is in range: every element but the minimum passes.+ (torch.uint8, [0, 1, 255], 0, ThresholdType.THRESH_BINARY, [0, 9, 9]),+ # Rounded down below the range, a signed threshold truncates to the dtype's minimum, not to 0.+ (torch.int8, [-128, 0, 127], -128.5, ThresholdType.THRESH_TRUNC, [-128, -128, -128]),+ ],+ )+ @pytest.mark.parametrize("tensor_thresh", [False, True])+ def test_integer_input_compares_against_the_threshold_as_given(+ self, image_dtype, values, thresh, ttype, expected, tensor_thresh, device+ ):+ x = torch.tensor(values, device=device, dtype=image_dtype)+ if tensor_thresh:+ thresh = torch.tensor(thresh, device=device)+ out = threshold(x, thresh=thresh, maxval=9, type=ttype)+ assert out.dtype == image_dtype+ assert out.tolist() == expected