π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): use per-plane Otsu histogram ranges and correct bin edges (#5402)
hoobnn6b59e0fa3175
diff --git a/changelog.d/5402.breaking.md b/changelog.d/5402.breaking.mdnew file mode 100644index 000000000..ea62487fe--- /dev/null+++ b/changelog.d/5402.breaking.md@@ -0,0 +1,9 @@+`otsu_threshold` and `OtsuThreshold` now histogram each image/channel plane over its own range, so a plane's threshold+no longer depends on the other images and channels in the call (#5172). Previously one range was shared by the whole+input. The default histogram path now returns the upper edge of the selected bin, `min + (t + 1)Β·(max β min)/nbins`.+Previously it read `linspace(min, max, nbins)`, a threshold up to one bin above the split, which at `nbins=2` was+always the maximum, so nothing was kept. For an integer input the threshold is now the largest integer below that+edge. Previously it was truncated toward zero, so a negative edge rounded up and an edge on an integer stayed put,+and the level just above the split was dropped from the foreground. A constant plane now uses its own value as the+threshold, so none of its pixels is foreground. Previously its threshold was 0. The `slow_and_differentiable=True`+path also uses each plane's own range and the same integer rounding.diff --git a/kornia/filters/otsu_thresholding.py b/kornia/filters/otsu_thresholding.pyindex c862e70e0..0894005ab 100644--- a/kornia/filters/otsu_thresholding.py+++ b/kornia/filters/otsu_thresholding.py@@ -50,25 +50,31 @@ class OtsuThreshold(torch.nn.Module):if xs.dtype in [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]:xs = xs.to(torch.float32)- min_val = xs.min()- max_val = xs.max()-+ min_values = xs.amin(dim=1)+ max_values = xs.amax(dim=1)histograms = []- bin_edges = torch.linspace(min_val.item(), max_val.item(), bins, device=xs.device)+ bin_edges = []+ # histc divides [min, max] into `bins` intervals. The KDE path instead samples `bins` locations.+ edge_count = bins if diff else bins + 1+ edge_dtype = torch.float64 if xs.dtype == torch.float64 else torch.float32for i in range(xs.shape[0]):- if diff:- hist = diff_histogram(xs[i].view(1, -1), bin_edges, torch.tensor(0.001)).squeeze()+ min_val = min_values[i].item()+ max_val = max_values[i].item()+ edges = torch.linspace(min_val, max_val, edge_count, device=xs.device, dtype=edge_dtype)+ if min_val == max_val:+ # No split exists; avoid histc's automatic range expansion for large constant values.+ hist = torch.zeros(bins, device=xs.device, dtype=edge_dtype)+ hist[0] = 1+ elif diff:+ hist = diff_histogram(xs[i].view(1, -1), edges, torch.tensor(0.001, device=xs.device)).squeeze()else:- # Use torch.histc for non-differentiable histogram- # Note: torch.histogram is in PyTorch 1.10+, and should replace histc in future versions when- # no longer supporting older pytorch versions.- hist = _torch_histc_cast(xs[i], bins=bins, min=min_val.item(), max=max_val.item())+ hist = _torch_histc_cast(xs[i], bins=bins, min=min_val, max=max_val)- # Normalize and append the histogramhistograms.append(hist / hist.sum())+ bin_edges.append(edges)- return torch.stack(histograms), bin_edges+ return torch.stack(histograms), torch.stack(bin_edges)def transform_input(self, x: torch.Tensor, original_shape: Optional[torch.Size] = None@@ -101,7 +107,9 @@ class OtsuThreshold(torch.nn.Module):def forward(self, x: torch.Tensor, nbins: int = 256, slow_and_differentiable: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:- """Apply Otsu thresholding to the input x.+ """Apply Otsu thresholding independently to each image/channel plane of x.++ A constant plane uses its constant value as the threshold, so all its pixels are background.Args:x (torch.Tensor): Image or batch of images to threshold.@@ -114,7 +122,6 @@ class OtsuThreshold(torch.nn.Module):"""# Flatten input and store original shapex_flattened, orig_shape = self.transform_input(x)- nchannel = x_flattened.shape[0]# Check tensor type compatibilityKORNIA_CHECK(@@ -136,9 +143,6 @@ class OtsuThreshold(torch.nn.Module):# Compute histogram and bin edgeshistograms, bin_edges = self.__histogram(x_flattened, bins=nbins, diff=slow_and_differentiable)- # Initialize thresholds- best_thresholds = torch.zeros(nchannel, device=x.device, dtype=x.dtype)-# Vectorized computation of optimal thresholdsbin_values = torch.arange(nbins, device=histograms.device, dtype=torch.float32)total_weight = torch.sum(histograms, dim=1) # Shape: (nchannel,)@@ -165,9 +169,18 @@ class OtsuThreshold(torch.nn.Module):# Find the maximum inter-class variance and corresponding thresholdt_max = torch.argmax(inter_class_var, dim=1) # Shape: (nchannel,)max_var = inter_class_var.gather(1, t_max[:, None]).squeeze(1) # Shape: (nchannel,)- best_thresholds = torch.where(- max_var > 0, bin_edges[t_max + 1], torch.tensor(0.0, device=histograms.device)- ).to(x.dtype)+ upper_edges = bin_edges.gather(1, (t_max + 1)[:, None]).squeeze(1)+ if not x.is_floating_point():+ # An integer pixel on or above the upper edge is counted in the foreground, so the integer threshold is+ # the largest integer below that edge. Truncating toward zero would round a negative edge up, and keep+ # an integer edge, and drop the level just above the split from the foreground.+ upper_edges = upper_edges.ceil() - 1+ best_thresholds = torch.where(max_var > 0, upper_edges, bin_edges[:, 0]).to(x.dtype)++ # Preserve a constant plane's exact input value, including integers outside floating-point precision.+ plane_min = x_flattened.amin(dim=1).detach()+ plane_max = x_flattened.amax(dim=1).detach()+ best_thresholds = torch.where(plane_min == plane_max, plane_min, best_thresholds)# Apply thresholding: keep values strictly greater than the thresholdthresholded = (x_flattened > best_thresholds[:, None]).to(x.dtype) * x_flattened@@ -184,6 +197,10 @@ def otsu_threshold() -> Tuple[torch.Tensor, torch.Tensor]:r"""Apply automatic image thresholding using Otsu algorithm to the input tensor.+ Each image/channel plane uses its own histogram range. On the default path, the threshold is the upper edge+ of the selected histogram bin. For an integer input it is the largest integer below that value, so+ ``x > threshold`` keeps every pixel on or above it. A constant plane uses its constant value as the threshold.+Args:x (Tensor): Input tensor (image or batch of images).nbins (int): Number of bins for histogram computation, default is 256.diff --git a/tests/filters/test_otsu_thresholding.py b/tests/filters/test_otsu_thresholding.pyindex f1e43de27..f13ac21c2 100644--- a/tests/filters/test_otsu_thresholding.py+++ b/tests/filters/test_otsu_thresholding.py@@ -128,9 +128,7 @@ class TestOtsuThreshold(BaseTester):[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]], device=device, dtype=dtype)- expected = torch.tensor(- [[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]], device=device, dtype=dtype- )+ expected = torch.zeros_like(input)op = OtsuThreshold()thresh_result, _thresh_value = op(input)@@ -153,6 +151,82 @@ class TestOtsuThreshold(BaseTester):atol = 1 / 256 if dtype == torch.float64 else 0.0self.assert_close(threshold, expected.to(dtype), rtol=0.0, atol=atol)+ def test_two_bins_uses_histogram_split_5172(self, device, dtype):+ image = torch.tensor([[0.0, 0.1, 0.2, 0.55, 0.9, 1.0]], device=device, dtype=dtype)+ mask, threshold = otsu_threshold(image, nbins=2, return_mask=True)+ # The two histc bins split [0, 1] at 0.5. The previous nbins-point linspace returned 1 instead.+ self.assert_close(threshold, image.new_tensor([0.5]), rtol=0, atol=0)+ assert mask.tolist() == [[False, False, False, True, True, True]]++ def test_uint8_pixel_above_selected_bin_5172(self, device):+ image = torch.cat([torch.arange(256), torch.full((300,), 60), torch.full((300,), 190)])+ image = image.to(device=device, dtype=torch.uint8).view(1, 1, 8, 107)+ mask, threshold = otsu_threshold(image, return_mask=True)+ assert threshold.item() == 125+ assert mask.flatten()[126]++ @pytest.mark.parametrize(+ "input_dtype,sign,offset,nbins,expected,kept,dropped",+ [+ (torch.int16, 1, -128, 256, -3, 126, 125),+ (torch.int16, -1, 0, 256, -126, 125, 126),+ (torch.uint8, 1, 0, 255, 125, 126, 125),+ ],+ ids=["shifted_below_zero", "mirrored", "edge_on_an_integer"],+ )+ def test_integer_threshold_is_the_largest_integer_below_the_edge_5172(+ self, input_dtype, sign, offset, nbins, expected, kept, dropped, device+ ):+ # The image above, shifted below zero, mirrored, or with 255 bins, whose selected upper edge is 126 exactly.+ # Truncating the edge toward zero rounds a negative edge up and keeps an integer edge, so the level just+ # above the split (scikit-image and OpenCV keep it) was dropped from the foreground.+ values = torch.cat([torch.arange(256), torch.full((300,), 60), torch.full((300,), 190)])+ image = (sign * values + offset).to(device=device, dtype=input_dtype).view(1, 1, 8, 107)+ mask, threshold = otsu_threshold(image, nbins=nbins, return_mask=True)+ assert threshold.item() == expected+ assert mask.flatten()[kept]+ assert not mask.flatten()[dropped]++ def test_float64_threshold_uses_float64_edges_5172(self, device):+ if device.type == "mps":+ pytest.skip("MPS has no float64")+ # The single split of two bins is the midpoint 0.5 + 2**-31, which float32 rounds to 0.5.+ image = torch.tensor([[0.0, 0.1, 0.2, 0.55, 0.9, 1.0 + 2**-30]], device=device, dtype=torch.float64)+ _, threshold = otsu_threshold(image, nbins=2)+ assert threshold.item() == 0.5 + 2**-31++ @pytest.mark.parametrize("shape", [(2, 6, 10), (2, 1, 6, 10), (1, 2, 6, 10), (1, 2, 1, 6, 10)])+ @pytest.mark.parametrize("slow_and_differentiable", [False, True])+ def test_planes_use_independent_ranges_5172(self, shape, slow_and_differentiable, device, dtype):+ first = torch.linspace(0, 1, 60, device=device, dtype=dtype).square().view(6, 10)+ second = torch.linspace(0.6, 4.3, 60, device=device, dtype=dtype).view(6, 10)+ image = torch.stack([first, second]).reshape(shape)+ expected = [otsu_threshold(plane, slow_and_differentiable=slow_and_differentiable) for plane in [first, second]]+ result, threshold = otsu_threshold(image, slow_and_differentiable=slow_and_differentiable)+ self.assert_close(threshold, torch.cat([item[1] for item in expected]), rtol=0, atol=0)+ self.assert_close(result, torch.stack([item[0] for item in expected]).reshape(shape), rtol=0, atol=0)++ @pytest.mark.parametrize("value", [-0.4, 0.0, 0.4])+ @pytest.mark.parametrize("slow_and_differentiable", [False, True])+ def test_constant_threshold_is_plane_value_5172(self, value, slow_and_differentiable, device, dtype):+ image = torch.full((1, 1, 4, 5), value, device=device, dtype=dtype)+ mask, threshold = otsu_threshold(image, slow_and_differentiable=slow_and_differentiable, return_mask=True)+ self.assert_close(threshold, image.flatten()[:1], rtol=0, atol=0)+ assert not mask.any()++ @pytest.mark.parametrize("slow_and_differentiable", [False, True])+ @pytest.mark.parametrize(+ "input_dtype,value", [(torch.int32, 2**24 + 1), (torch.int64, 2**24 + 1), (torch.int64, 2**53 + 1)]+ )+ @pytest.mark.parametrize("sign", [-1, 1])+ def test_constant_integer_preserves_exact_value_5172(+ self, input_dtype, value, sign, slow_and_differentiable, device+ ):+ image = torch.full((2, 3), sign * value, dtype=input_dtype, device=device)+ mask, threshold = otsu_threshold(image, slow_and_differentiable=slow_and_differentiable, return_mask=True)+ assert torch.equal(threshold, image.flatten()[:1])+ assert not mask.any()+def test_mask(device, dtype):input = torch.tensor([[10, 20, 30], [40, 50, 60], [70, 80, 90]], device=device, dtype=dtype)