fix(algo): partly transparent colours keep the per-channel limit (#11995)

The spread was measured on opaque colours only, and the issue keeps
today's behaviour for partly transparent ones, in the match and in the
anti-alias fringe.
This commit is contained in:
Sven Lafebre committed 2026-11-08 22:53:30 +01:00
1 parent e0ca582b97
commit 25d6041ab5
2 files changed
+24 -3

No files matched your search

+4 -3
View File
@@ -305,7 +305,8 @@ pub enum ColorDistance {
/// The largest difference in any one of R, G and B.
LargestChannel,
/// The spread of `{0, dR, dG, dB}`: changes in the same direction count once, opposite
/// changes add up.
/// changes add up. Only opaque colours were measured, so a partly transparent seed or pixel
/// uses [`Self::LargestChannel`].
Spread,
}
@@ -313,8 +314,8 @@ impl ColorDistance {
fn rgb(self, p: [u8; 4], seed: [u8; 4]) -> i32 {
let d = [0, 1, 2].map(|c| p[c] as i32 - seed[c] as i32);
match self {
Self::LargestChannel => d.iter().fold(0, |m, v| m.max(v.abs())),
Self::Spread => d.iter().fold(0, |m, v| m.max(*v)) - d.iter().fold(0, |m, v| m.min(*v)),
Self::Spread if p[3] == 255 && seed[3] == 255 => d.iter().fold(0, |m, v| m.max(*v)) - d.iter().fold(0, |m, v| m.min(*v)),
Self::LargestChannel | Self::Spread => d.iter().fold(0, |m, v| m.max(v.abs())),
}
}
}
@@ -216,3 +216,23 @@ fn the_spread_keeps_the_transparent_and_alpha_handling() {
let region = run(half, 30.0);
assert_eq!((region.at(1, 0), region.at(2, 0)), (0.0, 1.0), "alpha differences stay limited by the Tolerance");
}
/// The spread was measured on opaque colours only: a partly transparent seed or pixel keeps the
/// per-channel limit, in the match and in the anti-alias fringe.
#[test]
fn partly_transparent_colours_keep_the_per_channel_limit() {
let area = Rect::new(0, 0, 3, 1);
let run = |img: &[[u8; 4]; 3], distance, anti_alias| sel::wand_region_by(img, area, (0, 0), 30.0, false, anti_alias, None, distance).unwrap();
let opaque = [[100, 100, 100, 255], [130, 100, 70, 255], [9, 9, 9, 255]];
assert_eq!(run(&opaque, sel::ColorDistance::Spread, false).at(1, 0), 0.0, "opaque colours use the spread");
for img in [
[[100, 100, 100, 128], [130, 100, 70, 128], [160, 100, 40, 128]],
[[100, 100, 100, 255], [130, 100, 70, 250], [160, 100, 40, 250]],
[[100, 100, 100, 250], [130, 100, 70, 255], [160, 100, 40, 255]],
] {
assert_eq!(run(&img, sel::ColorDistance::Spread, false).at(1, 0), 1.0, "{img:?}: every channel is within 30");
assert_eq!(run(&img, sel::ColorDistance::Spread, true), run(&img, sel::ColorDistance::LargestChannel, true), "{img:?}: same fringe");
}
}