π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feature] Differentiable image histogram using kernel density estimation. (#1172)
Bulat Suleymanov998f6668b6cc
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.pyindex 456f553c2..b426ae438 100644--- a/kornia/enhance/histogram.py+++ b/kornia/enhance/histogram.py@@ -1,8 +1,9 @@-from typing import Tuple+import math+from typing import Optional, Tupleimport torch-__all__ = ["histogram", "histogram2d"]+__all__ = ["histogram", "histogram2d", "image_histogram2d"]def marginal_pdf(@@ -49,7 +50,7 @@ def marginal_pdf(normalization = torch.sum(pdf, dim=1).unsqueeze(1) + epsilonpdf = pdf / normalization- return (pdf, kernel_values)+ return pdf, kernel_valuesdef joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:@@ -150,3 +151,119 @@ def histogram2d(pdf = joint_pdf(kernel_values1, kernel_values2)return pdf+++def image_histogram2d(+ image: torch.Tensor,+ min: float = 0.0,+ max: float = 255.0,+ n_bins: int = 256,+ bandwidth: Optional[float] = None,+ centers: Optional[torch.Tensor] = None,+ return_pdf: bool = False,+ kernel: str = "triangular",+ eps: float = 1e-10,+) -> Tuple[torch.Tensor, torch.Tensor]:+ """Estimate the histogram of the input image(s).++ The calculation uses triangular kernel density estimation.++ Args:+ image: Input tensor to compute the histogram with shape+ :math:`(H, W)`, :math:`(C, H, W)` or :math:`(B, C, H, W)`.+ min: Lower end of the interval (inclusive).+ max: Upper end of the interval (inclusive). Ignored when+ :attr:`centers` is specified.+ n_bins: The number of histogram bins. Ignored when+ :attr:`centers` is specified.+ bandwidth: Smoothing factor. If not specified or equal to -1,+ :math:`(bandwidth = (max - min) / n_bins)`.+ centers: Centers of the bins with shape :math:`(n_bins,)`.+ If not specified or empty, it is calculated as centers of+ equal width bins of [min, max] range.+ return_pdf: If True, also return probability densities for+ each bin.+ kernel: kernel to perform kernel density estimation+ ``(`triangular`, `gaussian`, `uniform`, `epanechnikov`)``.++ Returns:+ Computed histogram of shape :math:`(bins)`, :math:`(C, bins)`,+ :math:`(B, C, bins)`.+ Computed probability densities of shape :math:`(bins)`, :math:`(C, bins)`,+ :math:`(B, C, bins)`, if return_pdf is ``True``. Tensor of zeros with shape+ of the histogram otherwise.+ """+ 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)}.")++ 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)}.")++ if centers is not None and len(centers.shape) > 0 and centers.dim() != 1:+ raise ValueError(f"Bins' centers must be a torch.Tensor of the shape (n_bins,). Got {centers.shape}.")++ if not isinstance(min, float):+ raise TypeError(f'Type of lower end of the range is not a float. Got {type(min)}.')++ if not isinstance(max, float):+ raise TypeError(f"Type of upper end of the range is not a float. Got {type(min)}.")++ if not isinstance(n_bins, int):+ raise TypeError(f"Type of number of bins is not an int. Got {type(n_bins)}.")++ if bandwidth is not None and not isinstance(bandwidth, float):+ raise TypeError(f"Bandwidth type is not a float. Got {type(bandwidth)}.")++ if not isinstance(return_pdf, bool):+ raise TypeError(f"Return_pdf type is not a bool. Got {type(return_pdf)}.")++ device = image.device++ if image.dim() == 4:+ batch_size, n_channels, height, width = image.size()+ elif image.dim() == 3:+ batch_size = 1+ n_channels, height, width = image.size()+ elif image.dim() == 2:+ height, width = image.size()+ batch_size, n_channels = 1, 1+ else:+ raise ValueError(f"Input values must be a tensor of the shape " f"BxCxHxW, CxHxW or HxW. Got {image.shape}.")++ if bandwidth is None:+ bandwidth = (max - min) / n_bins+ if centers is None:+ centers = min + bandwidth * (torch.arange(n_bins, device=image.device, dtype=image.dtype).float() + 0.5)+ centers = centers.reshape(-1, 1, 1, 1, 1)+ u = torch.abs(image.unsqueeze(0) - centers) / bandwidth+ if kernel == "triangular":+ mask = (u <= 1).to(u.dtype)+ kernel_values = (1 - u) * mask+ elif kernel == "gaussian":+ kernel_values = torch.exp(-0.5 * u ** 2)+ elif kernel == "uniform":+ mask = (u <= 1).to(u.dtype)+ kernel_values = torch.ones_like(u, dtype=u.dtype, device=u.device) * mask+ elif kernel == "epanechnikov":+ mask = (u <= 1).to(u.dtype)+ kernel_values = (1 - u ** 2) * mask+ else:+ raise ValueError(f"Kernel must be 'triangular', 'gaussian', " f"'uniform' or 'epanechnikov'. Got {kernel}.")++ hist = torch.sum(kernel_values, dim=(-2, -1)).permute(1, 2, 0)+ if return_pdf:+ normalization = torch.sum(hist, dim=-1).unsqueeze(0) + eps+ pdf = hist / normalization+ if image.dim() == 2:+ hist = hist.squeeze()+ pdf = pdf.squeeze()+ elif image.dim() == 3:+ hist = hist.squeeze(0)+ pdf = pdf.squeeze(0)+ return hist, pdf++ if image.dim() == 2:+ hist = hist.squeeze()+ elif image.dim() == 3:+ hist = hist.squeeze(0)+ return hist, torch.zeros_like(hist, dtype=hist.dtype, device=device)diff --git a/test/enhance/test_histogram.py b/test/enhance/test_histogram.pyindex bd7594def..3fa4e4309 100644--- a/test/enhance/test_histogram.py+++ b/test/enhance/test_histogram.py@@ -1,108 +1,182 @@+import pytestimport torchfrom torch.autograd import gradcheckimport korniaimport kornia.testing as utils # test utilsfrom kornia.testing import assert_close+from packaging import version+++class TestImageHistogram2d:+ fcn = kornia.enhance.image_histogram2d++ @pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])+ def test_shape(self, device, dtype, kernel):+ input = torch.ones(32, 32, device=device, dtype=dtype)+ hist, pdf = TestImageHistogram2d.fcn(input, 0.0, 1.0, 256, kernel=kernel)+ assert hist.shape == (256,) and pdf.shape == (256,)++ @pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])+ def test_shape_channels(self, device, dtype, kernel):+ input = torch.ones(3, 32, 32, device=device, dtype=dtype)+ hist, pdf = TestImageHistogram2d.fcn(input, 0.0, 1.0, 256, kernel=kernel)+ assert hist.shape == (3, 256) and pdf.shape == (3, 256)++ @pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])+ def test_shape_batch(self, device, dtype, kernel):+ input = torch.ones(8, 3, 32, 32, device=device, dtype=dtype)+ hist, pdf = TestImageHistogram2d.fcn(input, 0.0, 1.0, 256, kernel=kernel)+ assert hist.shape == (8, 3, 256) and pdf.shape == (8, 3, 256)++ @pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])+ def test_gradcheck(self, device, dtype, kernel):+ input = torch.ones(32, 32, device=device, dtype=dtype)+ input = utils.tensor_to_gradcheck_var(input) # to var+ centers = torch.linspace(0, 255, 8, device=device, dtype=dtype)+ centers = utils.tensor_to_gradcheck_var(centers)+ assert gradcheck(+ TestImageHistogram2d.fcn, (input, 0.0, 255.0, 256, None, centers, True, kernel), raise_exception=True+ )++ @pytest.mark.skipif(+ version.parse(torch.__version__) < version.parse("1.9"), reason="Tuple cannot be jitted with PyTorch < v1.9"+ )+ @pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])+ def test_jit(self, device, dtype, kernel):+ input = torch.linspace(0, 255, 10, device=device, dtype=dtype)+ input_x, input_y = torch.meshgrid(input, input)+ inputs = (input_x, 0.0, 255.0, 10, None, None, False, kernel)++ op = TestImageHistogram2d.fcn+ op_script = torch.jit.script(op)+ assert_close(op(*inputs), op_script(*inputs))-class TestHistogram:+ @pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])+ def test_uniform_hist(self, device, dtype, kernel):+ input = torch.linspace(0, 255, 10, device=device, dtype=dtype)+ input_x, input_y = torch.meshgrid(input, input)+ if kernel == "gaussian":+ bandwidth = 2 * 0.4 ** 2+ else:+ bandwidth = None+ hist, pdf = TestImageHistogram2d.fcn(input_x, 0.0, 255.0, 10, bandwidth=bandwidth, centers=input, kernel=kernel)+ ans = 10 * torch.ones_like(hist)+ assert_close(ans, hist)++ @pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])+ def test_uniform_dist(self, device, dtype, kernel):+ input = torch.linspace(0, 255, 10, device=device, dtype=dtype)+ input_x, input_y = torch.meshgrid(input, input)+ if kernel == "gaussian":+ bandwidth = 2 * 0.4 ** 2+ else:+ bandwidth = None+ hist, pdf = TestImageHistogram2d.fcn(+ input_x, 0.0, 255.0, 10, bandwidth=bandwidth, centers=input, kernel=kernel, return_pdf=True+ )+ ans = 0.1 * torch.ones_like(hist)+ assert_close(ans, pdf)- fcn = kornia.enhance.histogram++class TestHistogram2d:++ fcn = kornia.enhance.histogram2ddef test_shape(self, device, dtype):- inp = torch.ones(1, 32, device=device, dtype=dtype)+ inp1 = torch.ones(1, 32, device=device, dtype=dtype)+ inp2 = torch.ones(1, 32, device=device, dtype=dtype)bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)bandwidth = torch.tensor(0.9, device=device, dtype=dtype)- pdf = TestHistogram.fcn(inp, bins, bandwidth)- assert pdf.shape == (1, 128)+ pdf = TestHistogram2d.fcn(inp1, inp2, bins, bandwidth)+ assert pdf.shape == (1, 128, 128)def test_shape_batch(self, device, dtype):- inp = torch.ones(8, 32, device=device, dtype=dtype)+ inp1 = torch.ones(8, 32, device=device, dtype=dtype)+ inp2 = torch.ones(8, 32, device=device, dtype=dtype)bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)bandwidth = torch.tensor(0.9, device=device, dtype=dtype)- pdf = TestHistogram.fcn(inp, bins, bandwidth)- assert pdf.shape == (8, 128)+ pdf = TestHistogram2d.fcn(inp1, inp2, bins, bandwidth)+ assert pdf.shape == (8, 128, 128)def test_gradcheck(self, device, dtype):- inp = torch.ones(1, 8, device=device, dtype=dtype)- inp = utils.tensor_to_gradcheck_var(inp) # to var+ inp1 = torch.ones(1, 8, device=device, dtype=dtype)+ inp2 = torch.ones(1, 8, device=device, dtype=dtype)+ inp1 = utils.tensor_to_gradcheck_var(inp1) # to var+ inp2 = utils.tensor_to_gradcheck_var(inp2) # to varbins = torch.linspace(0, 255, 8, device=device, dtype=dtype)bins = utils.tensor_to_gradcheck_var(bins)bandwidth = torch.tensor(0.9, device=device, dtype=dtype)bandwidth = utils.tensor_to_gradcheck_var(bandwidth)- assert gradcheck(TestHistogram.fcn, (inp, bins, bandwidth), raise_exception=True)+ assert gradcheck(TestHistogram2d.fcn, (inp1, inp2, bins, bandwidth), raise_exception=True)def test_jit(self, device, dtype):input1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)+ input2 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)bins = torch.linspace(0, 255, 10, device=device, dtype=dtype)bandwidth = torch.tensor(2 * 0.4 ** 2, device=device, dtype=dtype)- inputs = (input1, bins, bandwidth)+ inputs = (input1, input2, bins, bandwidth)- op = TestHistogram.fcn+ op = TestHistogram2d.fcnop_script = torch.jit.script(op)assert_close(op(*inputs), op_script(*inputs))def test_uniform_dist(self, device, dtype):input1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)- input2 = torch.linspace(0, 255, 10, device=device, dtype=dtype)+ input2 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)+ bins = torch.linspace(0, 255, 10, device=device, dtype=dtype)bandwidth = torch.tensor(2 * 0.4 ** 2, device=device, dtype=dtype)- pdf = TestHistogram.fcn(input1, input2, bandwidth)- ans = 0.1 * torch.ones(1, 10, device=device, dtype=dtype)+ pdf = TestHistogram2d.fcn(input1, input2, bins, bandwidth)+ ans = 0.1 * kornia.eye_like(10, pdf)assert_close(ans, pdf)-class TestHistogram2d:+class TestHistogram:- fcn = kornia.enhance.histogram2d+ fcn = kornia.enhance.histogramdef test_shape(self, device, dtype):- inp1 = torch.ones(1, 32, device=device, dtype=dtype)- inp2 = torch.ones(1, 32, device=device, dtype=dtype)+ inp = torch.ones(1, 32, device=device, dtype=dtype)bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)bandwidth = torch.tensor(0.9, device=device, dtype=dtype)- pdf = TestHistogram2d.fcn(inp1, inp2, bins, bandwidth)- assert pdf.shape == (1, 128, 128)+ pdf = TestHistogram.fcn(inp, bins, bandwidth)+ assert pdf.shape == (1, 128)def test_shape_batch(self, device, dtype):- inp1 = torch.ones(8, 32, device=device, dtype=dtype)- inp2 = torch.ones(8, 32, device=device, dtype=dtype)+ inp = torch.ones(8, 32, device=device, dtype=dtype)bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)bandwidth = torch.tensor(0.9, device=device, dtype=dtype)- pdf = TestHistogram2d.fcn(inp1, inp2, bins, bandwidth)- assert pdf.shape == (8, 128, 128)+ pdf = TestHistogram.fcn(inp, bins, bandwidth)+ assert pdf.shape == (8, 128)def test_gradcheck(self, device, dtype):- inp1 = torch.ones(1, 8, device=device, dtype=dtype)- inp2 = torch.ones(1, 8, device=device, dtype=dtype)- inp1 = utils.tensor_to_gradcheck_var(inp1) # to var- inp2 = utils.tensor_to_gradcheck_var(inp2) # to var+ inp = torch.ones(1, 8, device=device, dtype=dtype)+ inp = utils.tensor_to_gradcheck_var(inp) # to varbins = torch.linspace(0, 255, 8, device=device, dtype=dtype)bins = utils.tensor_to_gradcheck_var(bins)bandwidth = torch.tensor(0.9, device=device, dtype=dtype)bandwidth = utils.tensor_to_gradcheck_var(bandwidth)- assert gradcheck(TestHistogram2d.fcn, (inp1, inp2, bins, bandwidth), raise_exception=True)+ assert gradcheck(TestHistogram.fcn, (inp, bins, bandwidth), raise_exception=True)def test_jit(self, device, dtype):input1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)- input2 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)bins = torch.linspace(0, 255, 10, device=device, dtype=dtype)bandwidth = torch.tensor(2 * 0.4 ** 2, device=device, dtype=dtype)- inputs = (input1, input2, bins, bandwidth)+ inputs = (input1, bins, bandwidth)- op = TestHistogram2d.fcn+ op = TestHistogram.fcnop_script = torch.jit.script(op)assert_close(op(*inputs), op_script(*inputs))def test_uniform_dist(self, device, dtype):input1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)- input2 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)- bins = torch.linspace(0, 255, 10, device=device, dtype=dtype)+ input2 = torch.linspace(0, 255, 10, device=device, dtype=dtype)bandwidth = torch.tensor(2 * 0.4 ** 2, device=device, dtype=dtype)- pdf = TestHistogram2d.fcn(input1, input2, bins, bandwidth)- ans = 0.1 * kornia.eye_like(10, pdf)+ pdf = TestHistogram.fcn(input1, input2, bandwidth)+ ans = 0.1 * torch.ones(1, 10, device=device, dtype=dtype)assert_close(ans, pdf)