π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): image_histogram2d bin centers built at image.dtype (#4360)
tritsysteme8ccef9049e2
diff --git a/changelog.d/4360.fixed.md b/changelog.d/4360.fixed.mdnew file mode 100644index 000000000..31cf726dc--- /dev/null+++ b/changelog.d/4360.fixed.md@@ -0,0 +1 @@+`kornia.enhance.image_histogram2d` no longer collapses distinct bins together on a `float16` or `bfloat16` image. The auto-built bin centers were created at the image dtype, which cannot represent the bin indices exactly: `bfloat16` lost 63 of 256 centers at the default `n_bins`, and `float16` lost 511 of 2048, so those bins came back numerically identical. The centers are now built at `float32` for half-precision images (a `float64` image keeps `float64`), and a floating-point image still gets its own dtype back. Integer images and explicitly passed `centers` behave exactly as before.diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.pyindex eb8bba7a8..debfd2c5d 100644--- a/kornia/enhance/histogram.py+++ b/kornia/enhance/histogram.py@@ -163,6 +163,17 @@ def histogram2d(return pdf+def _restore_float_dtype(hist: torch.Tensor, image: torch.Tensor, auto_centers: bool) -> torch.Tensor:+ """Hand back the image's own dtype after wider bin centers promoted the result.++ Only for auto-built centers on a floating-point image: an integer image or explicit ``centers`` keep the promoted+ dtype they always had, and casting a KDE result into an integer dtype would truncate it (uint8 wraps modulo 256).+ """+ if auto_centers and image.is_floating_point():+ return hist.to(image.dtype)+ return hist++def image_histogram2d(image: torch.Tensor,min: float = 0.0,@@ -232,8 +243,12 @@ def image_histogram2d(if bandwidth is None:bandwidth = (max - min) / n_bins+ auto_centers = centers is Noneif centers is None:- centers = min + bandwidth * (torch.arange(n_bins, device=image.device, dtype=image.dtype) + 0.5)+ # Build the bin-center grid at a dtype that represents the bin indices exactly: image.dtype alone collapses+ # distinct centers for float16/bfloat16, and a fixed float32 would downgrade a float64 image.+ compute_dtype = torch.promote_types(image.dtype, torch.float32)+ centers = min + bandwidth * (torch.arange(n_bins, device=image.device, dtype=compute_dtype) + 0.5)centers = centers.reshape(-1, 1, 1, 1, 1)u = torch.abs(image.unsqueeze(0) - centers) / bandwidth@@ -253,6 +268,7 @@ def image_histogram2d(raise ValueError(f"Kernel must be 'triangular', 'gaussian', 'uniform' or 'epanechnikov'. Got {kernel}.")hist = torch.sum(kernel_values, dim=(-2, -1)).permute(1, 2, 0)+ hist = _restore_float_dtype(hist, image, auto_centers)if return_pdf:normalization = torch.sum(hist, dim=-1, keepdim=True) + epsdiff --git a/tests/enhance/test_histogram.py b/tests/enhance/test_histogram.pyindex 06caec64a..edea99455 100644--- a/tests/enhance/test_histogram.py+++ b/tests/enhance/test_histogram.py@@ -19,6 +19,7 @@ import pytestimport torchimport kornia+from kornia.core._compat import torch_version_ltfrom testing.base import BaseTester@@ -96,6 +97,96 @@ class TestImageHistogram2d(BaseTester):ans = 0.1 * torch.ones_like(hist)self.assert_close(ans, pdf)+ def test_large_n_bins_float16_centers_not_collapsed(self, device):+ """image_histogram2d built its bin-center arange at image.dtype -- float16 can only+ exactly represent integers up to 2048 (torch.arange(4096, dtype=torch.float16) has only+ 3073 distinct values, not 4096), so with enough bins, DIFFERENT bin indices silently+ collapsed onto the SAME center value, giving those bins numerically IDENTICAL kernel-+ density output regardless of the real underlying data spread.++ Compares the function's own auto-constructed centers against EXPLICITLY-supplied+ float32 centers on the *same* float16 image tensor (the `centers=` argument bypasses+ internal construction entirely) -- this isolates the bug mechanism cleanly, with no+ confound from float16 also quantizing the image's own pixel VALUES (a separate, benign,+ expected precision limit unrelated to how centers are built). float32 is an exact+ reference here: n_bins=4096 is far below float32's 2**24 integer limit (MPS has no+ float64). The tolerance is far below the error the collapse causes."""+ torch.manual_seed(0)+ n_bins = 4096+ image = torch.rand(1, 64, 64, device=device, dtype=torch.float16)++ hist_auto, _ = TestImageHistogram2d.fcn(image, 0.0, 1.0, n_bins, kernel="gaussian")++ explicit_centers = 0.0 + (1.0 / n_bins) * (torch.arange(n_bins, device=device, dtype=torch.float32) + 0.5)+ hist_explicit, _ = TestImageHistogram2d.fcn(+ image, 0.0, 1.0, n_bins, centers=explicit_centers, kernel="gaussian"+ )++ self.assert_close(hist_auto.float(), hist_explicit.float(), atol=1e-3, rtol=1e-3)++ @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])+ @pytest.mark.parametrize("return_pdf", [False, True])+ def test_auto_centers_preserve_input_dtype(self, device, dtype, return_pdf):+ """The float32-centers fix above (test_large_n_bins_float16_centers_not_collapsed)+ must not itself change the function's public return dtype: before that fix, a+ float16/bfloat16 image with centers=None returned float16/bfloat16 hist/pdf. Building+ centers at float32 promotes u/kernel_values through ordinary PyTorch type promotion,+ so hist/pdf must be explicitly cast back to image.dtype at the return boundary."""+ if device.type == "mps" and dtype == torch.bfloat16 and torch_version_lt(2, 14, 0):+ pytest.skip("bfloat16 on MPS is only exercised on torch >= 2.14 (the version of the blocking MPS job)")+ torch.manual_seed(0)+ image = torch.rand(1, 16, 16, device=device, dtype=dtype)++ hist, pdf = TestImageHistogram2d.fcn(image, 0.0, 1.0, 64, kernel="gaussian", return_pdf=return_pdf)++ assert hist.dtype == dtype+ assert pdf.dtype == dtype++ @pytest.mark.parametrize("dtype", [torch.uint8, torch.int32])+ def test_integer_image_is_not_cast_into_an_integer_histogram(self, device, dtype):+ """An integer image has always given a float32 histogram (the bin centers are float and promote the result).+ Casting the KDE result back to the image dtype would truncate it and, for uint8, wrap it modulo 256."""+ torch.manual_seed(3)+ image = (torch.rand(1, 64, 64, device=device) * 255).to(dtype)++ hist, _ = TestImageHistogram2d.fcn(image, 0.0, 255.0, 16)+ reference, _ = TestImageHistogram2d.fcn(image.to(torch.float32), 0.0, 255.0, 16)++ assert hist.dtype == torch.float32+ assert hist.max() > 255, "the bin counts must exceed what uint8 can hold for this input to discriminate"+ self.assert_close(hist, reference, atol=0.0, rtol=0.0)++ def test_float64_image_keeps_float64_bin_centers(self, device):+ """A hard-coded float32 arange would give a float64 image float32-precision centers. With a bandwidth that is+ not a power of two (1 / 1000) the centers differ from the float64 ones by about 1e-8 and the histogram moves+ by ~1e-4, so this discriminates; a power-of-two n_bins would not."""+ if device.type == "mps":+ pytest.skip("MPS has no float64")+ torch.manual_seed(0)+ n_bins = 1000+ image = torch.rand(1, 32, 32, device=device, dtype=torch.float64)++ hist_auto, _ = TestImageHistogram2d.fcn(image, 0.0, 1.0, n_bins, kernel="triangular")+ centers = 0.0 + (1.0 / n_bins) * (torch.arange(n_bins, device=device, dtype=torch.float64) + 0.5)+ hist_explicit, _ = TestImageHistogram2d.fcn(image, 0.0, 1.0, n_bins, centers=centers, kernel="triangular")++ assert hist_auto.dtype == torch.float64+ self.assert_close(hist_auto, hist_explicit, atol=1e-12, rtol=0.0)++ def test_explicit_centers_keep_the_promoted_dtype(self, device):+ """Only the auto-built-centers path is cast back to the image dtype. With explicit float64 centers a float32+ image has always given float64 outputs, and the caller who supplied them to get that precision must keep it."""+ if device.type == "mps":+ pytest.skip("MPS has no float64")+ torch.manual_seed(2)+ image = torch.rand(1, 8, 8, device=device, dtype=torch.float32)+ centers = torch.linspace(0, 1, 16, device=device, dtype=torch.float64)++ hist, pdf = TestImageHistogram2d.fcn(image, 0.0, 1.0, 16, centers=centers, return_pdf=True)++ assert hist.dtype == torch.float64+ assert pdf.dtype == torch.float64+class TestHistogram2d(BaseTester):fcn = kornia.enhance.histogram2d