Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(contrib): sum histogram_matching counts in int64, not the input dtype (#5878)

Saksham Sharma63ffe1605d98
diff --git a/changelog.d/5878.breaking.md b/changelog.d/5878.breaking.md
new file mode 100644
index 000000000..77e72439a
--- /dev/null
+++ b/changelog.d/5878.breaking.md
@@ -0,0 +1,5 @@
+`kornia.contrib.histogram_matching` returns the source dtype for a floating source and `float32` for an
+integer source, whatever the template dtype. The output dtype used to depend on the template too: a
+`float32` source with a `float64` template returned `float64` (now `float32`), a `float16` source with a
+`float32` template returned `float32` (now `float16`), and a `uint8` source with a `float64` template
+returned `float64` (now `float32`). Pairs of the same dtype return the same dtype as before.
diff --git a/changelog.d/5878.fixed.md b/changelog.d/5878.fixed.md
new file mode 100644
index 000000000..f49a63249
--- /dev/null
+++ b/changelog.d/5878.fixed.md
@@ -0,0 +1,7 @@
+`kornia.contrib.histogram_matching` sums the histogram counts in `int64` and computes the quantiles in
+`float32` (`float64` for a `float64` source) instead of in the input dtype. A `uint8` sum wrapped past 255
+and an `int16` sum past 32767, so a 50x50 `uint8` image mapped to values above 255 and a 64x64 one to NaN
+everywhere; `float16` and `bfloat16` sums stopped being exact past 2048 and 256 pixels, and about half of
+random image pairs at those sizes returned NaN pixels. `kornia.contrib.interp` returns the right endpoint
+on a zero-width last segment instead of NaN, which a template of more than 2**24 pixels could produce in
+`float32`.
diff --git a/kornia/contrib/histogram_matching.py b/kornia/contrib/histogram_matching.py
index 82aeae05f..adacd566d 100644
--- a/kornia/contrib/histogram_matching.py
+++ b/kornia/contrib/histogram_matching.py
@@ -31,7 +31,10 @@ def histogram_matching(source: torch.Tensor, template: torch.Tensor) -> torch.Te
template: Template image. It can have different dimensions to source.
Returns:
- The transformed output image as the same shape as the source image.
+ The transformed output image as the same shape as the source image. A floating source keeps its dtype; an
+ integer source returns ``float32``. The values come from the template, on its scale. The quantiles are
+ computed in ``float32`` (``float64`` for a ``float64`` source), so ``uint8``, ``float16`` and ``bfloat16``
+ images of any size work.
Note:
This function does not matches histograms element-wisely if input a batched tensor.
@@ -47,12 +50,15 @@ def histogram_matching(source: torch.Tensor, template: torch.Tensor) -> torch.Te
# 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)
+ # template images (maps pixel value --> quantile). The counts are summed in int64 and the quantiles computed
+ # in float32 (float64 for float64 input): a uint8 sum wraps past 255, and float16/bfloat16 sums stop being exact
+ # past 2048/256, which repeats quantiles and makes interp divide by zero.
+ compute_dtype = torch.float64 if source.dtype == torch.float64 else torch.float32
+ s_quantiles = torch.cumsum(s_counts, dim=0).to(compute_dtype)
s_quantiles = s_quantiles / s_quantiles[-1]
- t_quantiles = torch.cumsum(t_counts, dim=0, dtype=source.dtype)
+ t_quantiles = torch.cumsum(t_counts, dim=0).to(compute_dtype)
t_quantiles = t_quantiles / t_quantiles[-1]
+ t_values = t_values.to(compute_dtype)
# interpolate linearly to find the pixel values in the template image
# that correspond most closely to the quantiles in the source image.
@@ -62,7 +68,9 @@ def histogram_matching(source: torch.Tensor, template: torch.Tensor) -> torch.Te
t_values = torch.cat([t_values[:1], t_values])
interp_t_values = interp(s_quantiles, t_quantiles, t_values)
- return interp_t_values[bin_idx].reshape(oldshape)
+ # A floating source keeps its dtype; an integer source returns float32.
+ out_dtype = source.dtype if source.is_floating_point() else compute_dtype
+ return interp_t_values[bin_idx].reshape(oldshape).to(out_dtype)
def interp(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
@@ -86,4 +94,11 @@ def interp(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
"""
i = torch.clip(torch.searchsorted(xp, x, right=True), 1, len(xp) - 1)
- return (fp[i - 1] * (xp[i] - x) + fp[i] * (x - xp[i - 1])) / (xp[i] - xp[i - 1])
+ # A zero-width segment (repeated xp) is selected only at a clipped end: x >= xp[-1] when the last xp repeats, or
+ # x < xp[0] when the first one does. Dividing by its width gave NaN, e.g. when float32 rounds the last cumulative
+ # counts of a 2**24-pixel template to the same quantile. Divide by a safe width there and return fp[i], which at
+ # the upper end is fp[-1], as np.interp gives for x >= xp[-1].
+ dx = xp[i] - xp[i - 1]
+ zero_width = dx == 0
+ out = (fp[i - 1] * (xp[i] - x) + fp[i] * (x - xp[i - 1])) / torch.where(zero_width, torch.ones_like(dx), dx)
+ return torch.where(zero_width, fp[i], out)
diff --git a/tests/contrib/test_hist_match.py b/tests/contrib/test_hist_match.py
index 2698dcb07..8c1644237 100644
--- a/tests/contrib/test_hist_match.py
+++ b/tests/contrib/test_hist_match.py
@@ -32,6 +32,24 @@ class TestHistMatch(BaseTester):
x_hat = kornia.contrib.interp(x, xp, fp)
self.assert_close(x_hat_expected, x_hat)
+ def test_interp_zero_width_last_segment(self, device, dtype):
+ # A 2**24 + 1 pixel template with one pixel in its last bin has its last two float32 quantiles both round to 1.
+ # A source quantile of 1 selects that zero-width segment, which divided by zero and gave NaN.
+ xp = torch.tensor([0.0, 1.0, 1.0], device=device, dtype=dtype)
+ fp = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype)
+ x = torch.tensor([0.5, 1.0], device=device, dtype=dtype)
+ x_hat = kornia.contrib.interp(x, xp, fp)
+ self.assert_close(x_hat, torch.tensor([0.0, 1.0], device=device, dtype=dtype))
+
+ def test_interp_zero_width_last_segment_gradient(self, device, dtype):
+ # torch.where differentiates the discarded quotient too: dividing by the raw zero width gave NaN gradients.
+ xp = torch.tensor([0.0, 1.0, 1.0], device=device, dtype=dtype)
+ fp = torch.tensor([0.0, 0.0, 1.0], device=device, dtype=dtype, requires_grad=True)
+ x = torch.tensor([0.5, 1.0], device=device, dtype=dtype, requires_grad=True)
+ kornia.contrib.interp(x, xp, fp).sum().backward()
+ self.assert_close(fp.grad, torch.tensor([0.5, 0.5, 1.0], device=device, dtype=dtype))
+ self.assert_close(x.grad, torch.zeros(2, device=device, dtype=dtype))
+
def test_histmatch(self, device, dtype):
torch.manual_seed(44)
# generate random value by CPU.
@@ -82,6 +100,40 @@ class TestHistMatch(BaseTester):
assert out.min() == 0
assert int((out == 0).sum()) == 60
+ def test_histmatch_large_image(self, device, dtype):
+ # 64x64 is past the exact-integer range of float16 (2048) and bfloat16 (256), where summing the counts in the
+ # input dtype repeated quantiles and gave NaN. The result must match the float64 computation on the same values.
+ # Seed 5 is one of the pairs that gave NaN in both float16 and bfloat16.
+ g = torch.Generator().manual_seed(5)
+ src = torch.rand(64, 64, generator=g).to(device=device, dtype=dtype)
+ dst = torch.rand(64, 64, generator=g).to(device=device, dtype=dtype)
+ out = kornia.contrib.histogram_matching(src, dst)
+ exp = kornia.contrib.histogram_matching(src.cpu().double(), dst.cpu().double()).to(device=device, dtype=dtype)
+ assert out.dtype == dtype
+ assert out.isfinite().all()
+ self.assert_close(out, exp)
+
+ def test_histmatch_float64_keeps_template_values(self, device, dtype):
+ # A float64 source is matched in float64: float32 would round the template value 1 + 2**-40 to 1.
+ if dtype != torch.float64:
+ pytest.skip("float64 only")
+ src = torch.tensor([0.0, 1.0], device=device, dtype=dtype)
+ dst = torch.tensor([1.0, 1.0 + 2**-40], device=device, dtype=dtype)
+ assert torch.equal(kornia.contrib.histogram_matching(src, dst), dst)
+
+ @pytest.mark.parametrize("size", [50, 64])
+ def test_histmatch_uint8(self, device, size):
+ # A uint8 count sum wraps past 255: 50x50 mapped to values up to 266, and 64x64 (4096 = 0 mod 256) to NaN.
+ g = torch.Generator().manual_seed(0)
+ src = (torch.rand(size, size, generator=g) * 255).round().to(device=device, dtype=torch.uint8)
+ dst = (torch.rand(size, size, generator=g) * 255).round().to(device=device, dtype=torch.uint8)
+ out = kornia.contrib.histogram_matching(src, dst)
+ assert out.dtype == torch.float32
+ assert out.isfinite().all()
+ assert out.min() >= dst.min()
+ assert out.max() <= dst.max()
+ self.assert_close(out, kornia.contrib.histogram_matching(src.float(), dst.float()))
+
@pytest.mark.skip(reason="not differentiable now.")
def test_grad(self, device):
B, C, H, W = 1, 3, 32, 32