π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
(feature): Added Open-CV style thresholding operations to the `enhance/threshold` module (#3515)
Keshav Singhe49a1438cb81
diff --git a/kornia/enhance/__init__.py b/kornia/enhance/__init__.pyindex d3b96c945..a2492775a 100644--- a/kornia/enhance/__init__.py+++ b/kornia/enhance/__init__.py@@ -59,6 +59,7 @@ from .jpeg import JPEGCodecDifferentiable, jpeg_codec_differentiablefrom .normalize import Denormalize, Normalize, denormalize, normalize, normalize_min_maxfrom .rescale import Rescalefrom .shift_rgb import shift_rgb+from .threshold import Threshold, ThresholdType, thresholdfrom .zca import ZCAWhitening, linear_transform, zca_mean, zca_whiten__all__ = [@@ -81,6 +82,8 @@ __all__ = ["JPEGCodecDifferentiable","Normalize","Rescale",+ "Threshold",+ "ThresholdType","ZCAWhitening","add_weighted","adjust_brightness",@@ -113,6 +116,7 @@ __all__ = ["sharpness","shift_rgb","solarize",+ "threshold","zca_mean","zca_whiten",]diff --git a/kornia/enhance/threshold.py b/kornia/enhance/threshold.pynew file mode 100644index 000000000..e9a9922bf--- /dev/null+++ b/kornia/enhance/threshold.py@@ -0,0 +1,137 @@+# 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.+#++from __future__ import annotations++from enum import IntEnum+from typing import Union++import torch+from torch import Tensor+from torch.nn import Module++from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR+++class ThresholdType(IntEnum):+ """Threshold types compatible with OpenCV fixed thresholding types.++ Note: THRESH_OTSU is intentionally not supported in this PR.+ """++ THRESH_BINARY = 0+ THRESH_BINARY_INV = 1+ THRESH_TRUNC = 2+ THRESH_TOZERO = 3+ THRESH_TOZERO_INV = 4++ # OpenCV uses 8 for OTSU, reserved for follow-up PR.+ THRESH_OTSU = 8+++def threshold(+ input: Tensor,+ thresh: Union[float, Tensor],+ maxval: Union[float, Tensor] = 255.0,+ type: Union[int, ThresholdType] = ThresholdType.THRESH_BINARY,+) -> Tensor:+ """Apply a fixed-level threshold to each element in the input tensor.++ Implements OpenCV-like behavior for the following threshold types:+ - THRESH_BINARY+ - THRESH_BINARY_INV+ - THRESH_TRUNC+ - THRESH_TOZERO+ - THRESH_TOZERO_INV++ Args:+ input: Image tensor of shape (..., H, W). Typically (B, C, H, W).+ thresh: Threshold value (scalar or tensor broadcastable to input).+ maxval: Maximum value used with binary thresholding types.+ type: Threshold type.++ Returns:+ Thresholded tensor with same shape/dtype/device as `input`.++ Raises:+ NotImplementedError: if THRESH_OTSU flag is passed.+ ValueError: if type is not supported.+ """+ KORNIA_CHECK_IS_TENSOR(input)++ t = int(type)++ # Detect if OTSU flag is present (opencv allows OR-ing)+ if t & int(ThresholdType.THRESH_OTSU):+ raise NotImplementedError("THRESH_OTSU is not implemented yet. Please use a fixed threshold type.")++ KORNIA_CHECK(+ t in {int(x) for x in ThresholdType if x != ThresholdType.THRESH_OTSU},+ f"Unsupported threshold type: {type}. Supported: BINARY, BINARY_INV, TRUNC, TOZERO, TOZERO_INV.",+ )++ # 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)+ else:+ thresh_t = thresh_t.to(device=input.device, dtype=input.dtype)++ maxval_t = maxval+ if not isinstance(maxval_t, Tensor):+ maxval_t = torch.tensor(maxval_t, device=input.device, dtype=input.dtype)+ else:+ maxval_t = maxval_t.to(device=input.device, dtype=input.dtype)++ mask = input > thresh_t+ zeros = torch.zeros_like(input)++ if t == int(ThresholdType.THRESH_BINARY):+ return torch.where(mask, maxval_t, zeros)++ if t == int(ThresholdType.THRESH_BINARY_INV):+ return torch.where(mask, zeros, maxval_t)++ if t == int(ThresholdType.THRESH_TRUNC):+ return torch.minimum(input, thresh_t)++ if t == int(ThresholdType.THRESH_TOZERO):+ return torch.where(mask, input, zeros)++ if t == int(ThresholdType.THRESH_TOZERO_INV):+ return torch.where(mask, zeros, input)++ # Should never reach here due to KORNIA_CHECK above+ raise ValueError(f"Unsupported threshold type: {type}")+++class Threshold(Module):+ """Module wrapper for `kornia.enhance.threshold`."""++ def __init__(+ self,+ thresh: float,+ maxval: float = 255.0,+ type: Union[int, ThresholdType] = ThresholdType.THRESH_BINARY,+ ) -> None:+ super().__init__()+ self.thresh = float(thresh)+ self.maxval = float(maxval)+ self.type = int(type)++ def forward(self, input: Tensor) -> Tensor:+ return threshold(input, self.thresh, self.maxval, self.type)diff --git a/tests/enhance/test_threshold.py b/tests/enhance/test_threshold.pynew file mode 100644index 000000000..8d21f5c6e--- /dev/null+++ b/tests/enhance/test_threshold.py@@ -0,0 +1,77 @@+# 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.enhance.threshold import ThresholdType, threshold+++class TestThreshold:+ @pytest.mark.parametrize(+ "ttype",+ [+ ThresholdType.THRESH_BINARY,+ ThresholdType.THRESH_BINARY_INV,+ ThresholdType.THRESH_TRUNC,+ ThresholdType.THRESH_TOZERO,+ ThresholdType.THRESH_TOZERO_INV,+ ],+ )+ @pytest.mark.parametrize("shape", [(1, 1, 5, 7), (2, 3, 11, 9)])+ def test_output_properties(self, ttype, shape, device, dtype):+ x = torch.rand(shape, device=device, dtype=dtype)+ out = threshold(x, thresh=0.5, maxval=1.0, type=ttype)++ assert out.shape == x.shape+ assert out.dtype == x.dtype+ assert out.device == x.device++ def test_binary_rule_strict_greater(self, device, dtype):+ x = torch.tensor([0.2, 0.5, 0.7], device=device, dtype=dtype)+ out = threshold(x, thresh=0.5, maxval=9.0, type=ThresholdType.THRESH_BINARY)+ expected = torch.tensor([0.0, 0.0, 9.0], device=device, dtype=dtype)+ assert torch.allclose(out, expected)++ def test_binary_inv_rule_strict_greater(self, device, dtype):+ x = torch.tensor([0.2, 0.5, 0.7], device=device, dtype=dtype)+ out = threshold(x, thresh=0.5, maxval=9.0, type=ThresholdType.THRESH_BINARY_INV)+ expected = torch.tensor([9.0, 9.0, 0.0], device=device, dtype=dtype)+ assert torch.allclose(out, expected)++ def test_trunc(self, device, dtype):+ x = torch.tensor([0.2, 0.5, 0.7], device=device, dtype=dtype)+ out = threshold(x, thresh=0.5, maxval=9.0, type=ThresholdType.THRESH_TRUNC)+ expected = torch.tensor([0.2, 0.5, 0.5], device=device, dtype=dtype)+ assert torch.allclose(out, expected)++ def test_tozero(self, device, dtype):+ x = torch.tensor([0.2, 0.5, 0.7], device=device, dtype=dtype)+ out = threshold(x, thresh=0.5, maxval=9.0, type=ThresholdType.THRESH_TOZERO)+ expected = torch.tensor([0.0, 0.0, 0.7], device=device, dtype=dtype)+ assert torch.allclose(out, expected)++ def test_tozero_inv(self, device, dtype):+ x = torch.tensor([0.2, 0.5, 0.7], device=device, dtype=dtype)+ out = threshold(x, thresh=0.5, maxval=9.0, type=ThresholdType.THRESH_TOZERO_INV)+ expected = torch.tensor([0.2, 0.5, 0.0], device=device, dtype=dtype)+ assert torch.allclose(out, expected)++ def test_otsu_raises(self, device, dtype):+ 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)