π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): reject undocumented image ranks in image_histogram2d (#5320)
msparsh13edfc2563637e
diff --git a/changelog.d/5320.breaking.md b/changelog.d/5320.breaking.mdnew file mode 100644index 000000000..3403e7804--- /dev/null+++ b/changelog.d/5320.breaking.md@@ -0,0 +1 @@+`image_histogram2d` now raises `ShapeError` (a `ValueError`) for an image that is not `(H, W)`, `(C, H, W)` or `(B, C, H, W)`. A rank-0 or rank-1 image used to return a histogram with spurious batch and channel axes, of shape `(1, 1, n_bins)`, and a rank-5 or higher image raised a `RuntimeError` from inside `permute`.diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.pyindex bcb4e5043..07d812ca7 100644--- a/kornia/enhance/histogram.py+++ b/kornia/enhance/histogram.py@@ -19,6 +19,8 @@ from typing import Optional, Tupleimport torch+from kornia.core.exceptions import ShapeError+def marginal_pdf(values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor, epsilon: float = 1e-10@@ -159,6 +161,12 @@ def histogram2d(return joint_pdf(kernel_values1, kernel_values2)+def _check_image_rank(image: torch.Tensor) -> None:+ """Reject the ranks that image_histogram2d does not document instead of failing inside the computation."""+ if image.dim() < 2 or image.dim() > 4:+ raise ShapeError(f"Input image must have shape (H, W), (C, H, W) or (B, C, H, W). Got {image.shape}.")++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.@@ -215,6 +223,8 @@ def image_histogram2d(if image is not None and not isinstance(image, torch.Tensor):raise TypeError(f"Input image type is not a torch.Tensor. Got {type(image)}.")+ _check_image_rank(image)+if centers is not None and not isinstance(centers, torch.Tensor):raise TypeError(f"Bins' centers type is not a torch.Tensor. Got {type(centers)}.")diff --git a/tests/enhance/test_histogram.py b/tests/enhance/test_histogram.pyindex edea99455..61a3f902f 100644--- a/tests/enhance/test_histogram.py+++ b/tests/enhance/test_histogram.py@@ -20,6 +20,7 @@ import torchimport korniafrom kornia.core._compat import torch_version_lt+from kornia.core.exceptions import ShapeErrorfrom testing.base import BaseTester@@ -48,6 +49,13 @@ class TestImageHistogram2d(BaseTester):assert hist.shape == (4, 3, 32)assert pdf.shape == (4, 3, 32)+ @pytest.mark.parametrize("shape", [(), (4,), (1, 1, 1, 2, 3)])+ def test_rejects_unsupported_rank(self, device, dtype, shape):+ # Rank 0 and 1 used to return spurious (1, 1, n_bins) batch and channel axes; rank 5 failed inside permute.+ image = torch.zeros(shape, device=device, dtype=dtype)+ with pytest.raises(ShapeError, match=r"Input image must have shape \(H, W\), \(C, H, W\) or \(B, C, H, W\)"):+ TestImageHistogram2d.fcn(image, n_bins=2)+@pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])def test_gradcheck(self, device, kernel):sample = torch.ones(8, 8, device=device, dtype=torch.float64)