Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] implements histogram2d (#530)

Connor Lee9b130926ed79
diff --git a/docs/source/color.rst b/docs/source/color.rst
index 155e2d406..b4cb7038a 100644
--- a/docs/source/color.rst
+++ b/docs/source/color.rst
@@ -31,6 +31,8 @@ The functions in this section perform various color space conversions.
.. autofunction:: adjust_hue
.. autofunction:: adjust_gamma
.. autofunction:: add_weighted
+.. autofunction:: histogram
+.. autofunction:: histogram2d
.. autoclass:: AddWeighted
.. autoclass:: RgbToGrayscale
diff --git a/kornia/color/__init__.py b/kornia/color/__init__.py
index 9bfc800f2..aeb4743d5 100644
--- a/kornia/color/__init__.py
+++ b/kornia/color/__init__.py
@@ -17,6 +17,7 @@ from .xyz import RgbToXyz, XyzToRgb, rgb_to_xyz, xyz_to_rgb
from .luv import RgbToLuv, LuvToRgb, rgb_to_luv, luv_to_rgb
from .normalize import Normalize, normalize, Denormalize, denormalize
from .core import add_weighted, AddWeighted
+from .histogram import histogram, histogram2d
from .adjust import (
AdjustBrightness, AdjustContrast, AdjustGamma, AdjustHue, AdjustSaturation,
)
@@ -44,6 +45,8 @@ __all__ = [
"xyz_to_rgb",
"normalize",
"denormalize",
+ "histogram",
+ "histogram2d",
"adjust_brightness",
"adjust_contrast",
"adjust_gamma",
diff --git a/kornia/color/histogram.py b/kornia/color/histogram.py
new file mode 100644
index 000000000..646830459
--- /dev/null
+++ b/kornia/color/histogram.py
@@ -0,0 +1,125 @@
+from typing import Tuple, List
+import torch
+import torch.nn as nn
+
+
+def marginal_pdf(values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor,
+ epsilon: float = 1e-10) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Function that calculates the marginal probability distribution function of the input tensor based on the number
+ of histogram bins.
+ Args:
+ values: (torch.Tensor), shape [BxNx1]
+ bins: (torch.Tensor), shape [NUM_BINS]
+ sigma: (torch.Tensor), shape [1], gaussian smoothing factor
+ epsilon: (float), scalar, for numerical stability
+ Returns:
+ pdf: (torch.Tensor), shape [BxN]
+ kernel_values: (torch.Tensor), shape [BxNxNUM_BINS]"""
+
+ if not torch.is_tensor(values):
+ raise TypeError("Input values type is not a torch.Tensor. Got {}"
+ .format(type(values)))
+ if not torch.is_tensor(bins):
+ raise TypeError("Input bins type is not a torch.Tensor. Got {}"
+ .format(type(bins)))
+ if not torch.is_tensor(sigma):
+ raise TypeError("Input sigma type is not a torch.Tensor. Got {}"
+ .format(type(sigma)))
+
+ if not values.dim() == 3:
+ raise ValueError("Input values must be a of the shape BxNx1."
+ " Got {}".format(values.shape))
+ if not bins.dim() == 1:
+ raise ValueError("Input bins must be a of the shape NUM_BINS"
+ " Got {}".format(bins.shape))
+ if not sigma.dim() == 0:
+ raise ValueError("Input sigma must be a of the shape 1"
+ " Got {}".format(sigma.shape))
+
+ residuals = values - bins.unsqueeze(0).unsqueeze(0)
+ kernel_values = torch.exp(-0.5 * (residuals / sigma).pow(2))
+
+ pdf = torch.mean(kernel_values, dim=1)
+ normalization = torch.sum(pdf, dim=1).unsqueeze(1) + epsilon
+ pdf = pdf / normalization
+
+ return (pdf, kernel_values)
+
+
+def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:
+ """
+ Function that calculates the joint probability distribution function of the input tensors based on the number
+ of histogram bins.
+ Args:
+ kernel_values1: (torch.Tensor), shape [BxNxNUM_BINS]
+ kernel_values2: (torch.Tensor), shape [BxNxNUM_BINS]
+ epsilon: (float), scalar, for numerical stability
+ Returns:
+ pdf: (torch.Tensor), shape [BxNUM_BINSxNUM_BINS]"""
+
+ if not torch.is_tensor(kernel_values1):
+ raise TypeError("Input kernel_values1 type is not a torch.Tensor. Got {}"
+ .format(type(kernel_values1)))
+ if not torch.is_tensor(kernel_values2):
+ raise TypeError("Input kernel_values2 type is not a torch.Tensor. Got {}"
+ .format(type(kernel_values2)))
+
+ if not kernel_values1.dim() == 3:
+ raise ValueError("Input kernel_values1 must be a of the shape BxN."
+ " Got {}".format(kernel_values1.shape))
+ if not kernel_values2.dim() == 3:
+ raise ValueError("Input kernel_values2 must be a of the shape BxN."
+ " Got {}".format(kernel_values2.shape))
+ if kernel_values1.shape != kernel_values2.shape:
+ raise ValueError("Inputs kernel_values1 and kernel_values2 must have the same shape."
+ " Got {} and {}".format(kernel_values1.shape, kernel_values2.shape))
+
+ joint_kernel_values = torch.matmul(kernel_values1.transpose(1, 2), kernel_values2)
+ normalization = torch.sum(joint_kernel_values, dim=(1, 2)).view(-1, 1, 1) + epsilon
+ pdf = joint_kernel_values / normalization
+
+ return pdf
+
+
+def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:
+ """
+ Function that estimates the histogram of the input tensor. The calculation uses kernel
+ density estimation which requires a bandwidth (smoothing) parameter.
+ Args:
+ x: (torch.Tensor), shape [BxN]
+ bins: (torch.Tensor), shape [NUM_BINS]
+ bandwidth: (torch.Tensor), shape [1], gaussian smoothing factor
+ epsilon: (float), scalar, for numerical stability
+ Returns:
+ pdf: (torch.Tensor), shape [BxNUM_BINS]"""
+
+ pdf, _ = marginal_pdf(x.unsqueeze(2), bins, bandwidth, epsilon)
+
+ return pdf
+
+
+def histogram2d(
+ x1: torch.Tensor,
+ x2: torch.Tensor,
+ bins: torch.Tensor,
+ bandwidth: torch.Tensor,
+ epsilon: float = 1e-10) -> torch.Tensor:
+ """
+ Function that estimates the histogram of the input tensor. The calculation uses kernel
+ density estimation which requires a bandwidth (smoothing) parameter.
+ Args:
+ x1: (torch.Tensor), shape [BxN1]
+ x2: (torch.Tensor), shape [BxN2]
+ bins: (torch.Tensor), shape [NUM_BINS]
+ bandwidth: (torch.Tensor), scalar, gaussian smoothing factor
+ epsilon: (float), scalar, for numerical stability
+ Returns:
+ pdf: (torch.Tensor), shape [BxNUM_BINSxNUM_BINS]"""
+
+ pdf1, kernel_values1 = marginal_pdf(x1.unsqueeze(2), bins, bandwidth, epsilon)
+ pdf2, kernel_values2 = marginal_pdf(x2.unsqueeze(2), bins, bandwidth, epsilon)
+
+ pdf = joint_pdf(kernel_values1, kernel_values2)
+
+ return pdf
diff --git a/test/color/test_histogram.py b/test/color/test_histogram.py
new file mode 100644
index 000000000..b2e1d49a1
--- /dev/null
+++ b/test/color/test_histogram.py
@@ -0,0 +1,83 @@
+import pytest
+from test.common import device
+import numpy as np
+import torch
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+from kornia.color import histogram, histogram2d
+import kornia.testing as utils # test utils
+
+
+class TestHistogram:
+ def test_shape(self, device):
+ inp = torch.ones(1, 32, device=device)
+ bins = torch.linspace(0, 255, 128).to(device)
+ bandwidth = torch.Tensor(np.array(0.9)).to(device)
+ pdf = histogram(inp, bins, bandwidth)
+ assert pdf.shape == (1, 128)
+
+ def test_shape_batch(self, device):
+ inp = torch.ones(8, 32, device=device)
+ bins = torch.linspace(0, 255, 128).to(device)
+ bandwidth = torch.Tensor(np.array(0.9)).to(device)
+ pdf = histogram(inp, bins, bandwidth)
+ assert pdf.shape == (8, 128)
+
+ def test_gradcheck(self, device):
+ inp = torch.ones(8, 32, device=device)
+ inp = utils.tensor_to_gradcheck_var(inp) # to var
+ bins = torch.linspace(0, 255, 128).to(device)
+ bins = utils.tensor_to_gradcheck_var(bins)
+ bandwidth = torch.Tensor(np.array(0.9)).to(device)
+ bandwidth = utils.tensor_to_gradcheck_var(bandwidth)
+ assert gradcheck(histogram, (inp, bins, bandwidth), raise_exception=True)
+
+ def test_uniform_dist(self, device):
+ input1 = torch.linspace(0, 255, 10).unsqueeze(0).to(device)
+
+ pdf = histogram(input1, torch.linspace(0, 255, 10).to(device), torch.Tensor(np.array(2 * 0.4**2)))
+ ans = torch.ones((1, 10)) * 0.1
+ assert((ans.cpu() - pdf.cpu()).sum() < 1e-6)
+
+
+class TestHistogram2d:
+ def test_shape(self, device):
+ inp1 = torch.ones(1, 32, device=device)
+ inp2 = torch.ones(1, 32, device=device)
+ bins = torch.linspace(0, 255, 128).to(device)
+ bandwidth = torch.Tensor(np.array(0.9)).to(device)
+ pdf = histogram2d(inp1, inp2, bins, bandwidth)
+ assert pdf.shape == (1, 128, 128)
+
+ def test_shape_batch(self, device):
+ inp1 = torch.ones(8, 32, device=device)
+ inp2 = torch.ones(8, 32, device=device)
+ bins = torch.linspace(0, 255, 128).to(device)
+ bandwidth = torch.Tensor(np.array(0.9)).to(device)
+ pdf = histogram2d(inp1, inp2, bins, bandwidth)
+ assert pdf.shape == (8, 128, 128)
+
+ def test_gradcheck(self, device):
+ inp1 = torch.ones(3, 16, device=device)
+ inp2 = torch.ones(3, 16, device=device)
+ inp1 = utils.tensor_to_gradcheck_var(inp1) # to var
+ inp2 = utils.tensor_to_gradcheck_var(inp2) # to var
+ bins = torch.linspace(0, 255, 64).to(device)
+ bins = utils.tensor_to_gradcheck_var(bins)
+ bandwidth = torch.Tensor(np.array(0.9)).to(device)
+ bandwidth = utils.tensor_to_gradcheck_var(bandwidth)
+ assert gradcheck(histogram2d, (inp1, inp2, bins, bandwidth), raise_exception=True)
+
+ def test_uniform_dist(self, device):
+ input1 = torch.linspace(0, 255, 10).unsqueeze(0).to(device)
+ input2 = torch.linspace(0, 255, 10).unsqueeze(0).to(device)
+
+ joint_pdf = histogram2d(
+ input1,
+ input2,
+ torch.linspace(0, 255, 10).to(device),
+ torch.Tensor(np.array(2 * 0.4**2)))
+
+ ans = torch.eye(10).unsqueeze(0) * 0.1
+ assert((ans.cpu() - joint_pdf.cpu()).sum() < 1e-6)