Skip to content

fix: use inverse CDF for histogram matching - #808

Open
teddytennant wants to merge 1 commit into
image-rs:mainfrom
teddytennant:fix/match-histogram-783
Open

fix: use inverse CDF for histogram matching#808
teddytennant wants to merge 1 commit into
image-rs:mainfrom
teddytennant:fix/match-histogram-783

Conversation

@teddytennant

Copy link
Copy Markdown
Contributor

Problem

match_histogram_mut produced suboptimal mappings for simple cases such as the one in #783:

let mut input_image = gray_image!(type: u8, 0, 1, 2, 3, 4, 5, 6, 7);
let target_image = gray_image!(type: u8, 30, 130, 30, 130);
match_histogram_mut(&mut input_image, &target_image);
// was: 29, 30, 30, 30, 129, 130, 130, 130
// want: 30, 30, 30, 30, 130, 130, 130, 130

The old result invents gray levels (29, 129) that never appear in the target, so the matched histogram is farther from the target than necessary.

Root cause

histogram_lut chose, for each source level, the target level whose cumulative fraction was nearest in absolute distance. When the target CDF jumps (for example from 0 at level 29 to 0.5 at level 30), source fractions just above 0 are closer to the pre-jump empty bin than to the level where mass actually appears.

Fix

Use the standard discrete inverse CDF:

lut[i] = min { y | target_cdf[y] >= source_cdf[i] }

Comparisons are done with integer cross-multiplication to avoid floating point. Empty source or target images leave the LUT as zeros.

Tests

  • Updated test_histogram_lut_gradient_to_step_contrast for inverse-CDF expectations (maps onto 30/130 rather than 29/129).
  • Added test_match_histogram_mut_maps_to_target_levels from the issue example.
  • Regenerated tests/data/truth/elephant_matched.png for the regression suite.
cargo +nightly test --lib histogram
cargo +nightly test --test regression test_match_histograms

Fixes #783

@teddytennant
teddytennant force-pushed the fix/match-histogram-783 branch from 12b76ed to 9344646 Compare August 8, 2026 17:08
match_histogram_mut previously mapped each source level to the target
level with nearest cumulative fraction. That could land in empty bins
just before CDF jumps (for example 29 instead of 30), so the matched
image histogram did not align with the target.

Use the discrete inverse CDF instead: map source level i to the smallest
target level y with target_cdf[y] >= source_cdf[i]. This matches the
standard construction and fixes the example from issue image-rs#783.

Update the gradient-to-step unit test expectations, add a regression
test from the issue, and regenerate the elephant_matched truth image.

Fixes image-rs#783
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Error in match_histogram_mut()

1 participant