π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add ``histogram_matching`` functionality (#1395)
Jian Shi99ccab7bbeef
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.pyindex 66245b314..a0cd948d4 100644--- a/kornia/contrib/__init__.py+++ b/kornia/contrib/__init__.py@@ -1,6 +1,7 @@from .classification import ClassificationHeadfrom .connected_components import connected_componentsfrom .extract_patches import combine_tensor_patches, CombineTensorPatches, extract_tensor_patches, ExtractTensorPatches+from .histogram_matching import histogram_matching, interpfrom .image_stitching import ImageStitcherfrom .lambda_module import Lambdafrom .vit import VisionTransformer@@ -12,6 +13,8 @@ __all__ = ["ExtractTensorPatches","combine_tensor_patches","CombineTensorPatches",+ "histogram_matching",+ "interp","VisionTransformer","MobileViT","ClassificationHead",diff --git a/kornia/contrib/histogram_matching.py b/kornia/contrib/histogram_matching.pynew file mode 100644index 000000000..fb0cad1c6--- /dev/null+++ b/kornia/contrib/histogram_matching.py@@ -0,0 +1,69 @@+import torch+++def histogram_matching(source: torch.Tensor, template: torch.Tensor) -> torch.Tensor:+ """Adjust the pixel values of an image to match its histogram towards a target image.++ `Histogram matching <https://en.wikipedia.org/wiki/Histogram_matching>`_ is the transformation+ of an image so that its histogram matches a specified histogram. In this implementation, the+ histogram is computed over the flattened image array. Code referred to+ `here <https://stackoverflow.com/questions/32655686/histogram-matching-of-two-images-in-python-2-x>`_.++ Args:+ source: Image to transform.+ template: Template image. It can have different dimensions to source.++ Returns:+ The transformed output image as the same shape as the source image.++ Note:+ This function does not matches histograms element-wisely if input a batched tensor.+ """++ oldshape = source.shape+ source = source.ravel()+ template = template.ravel()++ # get the set of unique pixel values and their corresponding indices and counts.+ _, bin_idx, s_counts = torch.unique(source, return_inverse=True, return_counts=True)+ t_values, t_counts = torch.unique(template, return_counts=True)++ # take the cumsum of the counts and normalize by the number of pixels to+ # get the empirical cumulative distribution functions for the source and+ # template images (maps pixel value --> quantile)++ s_quantiles = torch.cumsum(s_counts, dim=0, dtype=source.dtype)+ s_quantiles = s_quantiles / s_quantiles[-1]+ t_quantiles = torch.cumsum(t_counts, dim=0, dtype=source.dtype)+ t_quantiles = t_quantiles / t_quantiles[-1]++ # interpolate linearly to find the pixel values in the template image+ # that correspond most closely to the quantiles in the source image+ interp_t_values = interp(s_quantiles, t_quantiles, t_values)++ return interp_t_values[bin_idx].reshape(oldshape)+++def interp(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:+ """Interpolate ``x`` tensor according to ``xp`` and ``fp`` as in ``np.interp``.++ This implementation cannot reproduce numpy results identically, but reasonable.+ Code referred to `here <https://github.com/pytorch/pytorch/issues/1552#issuecomment-926972915>`_.++ Args:+ x: the input tensor that needs to be interpolated.+ xp: the x-coordinates of the referred data points.+ fp: the y-coordinates of the referred data points, same length as ``xp``.++ Returns:+ The interpolated values, same shape as ``x``.+ """+ if x.dim() != xp.dim() != fp.dim() != 1:+ raise ValueError(+ f"Required 1D vector across ``x``, ``xp``, ``fp``. Got {x.dim()}, {xp.dim()}, {fp.dim()}."+ )++ slopes = (fp[1:] - fp[:-1]) / (xp[1:] - xp[:-1])+ locs = torch.searchsorted(xp, x)+ locs = locs.clip(1, len(xp) - 1) - 1+ return slopes[locs] * (x - xp[locs]) + xp[locs]diff --git a/test/test_contrib.py b/test/test_contrib.pyindex ab7ab625e..0b5519064 100644--- a/test/test_contrib.py+++ b/test/test_contrib.py@@ -368,3 +368,36 @@ class TestImageStitcher:stitcher = kornia.contrib.ImageStitcher(matcher).to(device=device, dtype=dtype)with pytest.raises(RuntimeError):stitcher(input1, input2)+++class TestHistMatch:++ def test_interp(self, device, dtype):+ xp = torch.tensor([1, 2, 3], device=device, dtype=dtype)+ fp = torch.tensor([4, 2, 0], device=device, dtype=dtype)+ x = torch.tensor([4, 5, 6], device=device, dtype=dtype)+ x_hat_expected = torch.tensor([-2., -4., -6.], device=device, dtype=dtype)+ x_hat = kornia.contrib.interp(x, xp, fp)+ assert (x_hat_expected == x_hat).all()++ def test_histmatch(self, device, dtype):+ torch.manual_seed(44)+ # generate random value by CPU.+ src = torch.randn(1, 4, 4).to(device=device, dtype=dtype)+ dst = torch.randn(1, 16, 16).to(device=device, dtype=dtype)+ out = kornia.contrib.histogram_matching(src, dst)+ exp = torch.tensor([[+ [0.9356, 0.8270, 1.3687, 0.5640],+ [0.6273, 0.9119, 0.4965, 0.4020],+ [0.4353, 0.1475, 0.3384, 0.2580],+ [0.0606, 0.7531, 0.2139, 0.6932]+ ]], device=device, dtype=dtype)+ assert exp.shape == out.shape+ assert_close(out, exp, rtol=1e-4, atol=1e-4)++ @pytest.mark.skip(reason="not differentiable now.")+ def test_grad(self, device):+ B, C, H, W = 1, 3, 32, 32+ src = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)+ dst = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)+ assert gradcheck(kornia.contrib.histogram_matching, (src, dst,), raise_exception=True)