Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Mix filtered selection edges with premultiplied alpha (#3895)

jonathanwxh-cella58b6f3d9ef6
diff --git a/crates/algo/src/blur.rs b/crates/algo/src/blur.rs
index 606ee7dbc..ae8b12f40 100644
--- a/crates/algo/src/blur.rs
+++ b/crates/algo/src/blur.rs
@@ -992,8 +992,9 @@ mod tests {
let mixed = crate::apply_in(&s, &p, canvas, canvas, Some(&half), canvas);
for (x, y) in [(0, 0), (18, 11), (36, 22)] {
let (o, f, m) = (s.pixel(x, y), full.pixel(x, y), mixed.pixel(x, y));
- for c in 0..4 {
- assert!((m[c] - (o[c] + f[c]) / 2.0).abs() < 1e-5, "({x},{y}) channel {c}");
+ assert!((m[3] - (o[3] + f[3]) / 2.0).abs() < 1e-5, "({x},{y}) alpha");
+ for c in 0..3 {
+ assert!((m[c] * m[3] - (o[c] * o[3] + f[c] * f[3]) / 2.0).abs() < 1e-5, "({x},{y}) premultiplied channel {c}");
}
}
let cancel = || true;
diff --git a/crates/algo/src/blur/motion_apply.rs b/crates/algo/src/blur/motion_apply.rs
index cc2f3e84e..166a1da5a 100644
--- a/crates/algo/src/blur/motion_apply.rs
+++ b/crates/algo/src/blur/motion_apply.rs
@@ -169,7 +169,7 @@ fn apply_inner(
return None;
}
if let Some(selection) = selection {
- crate::mix_selection(&mut data, output, selection, &src);
+ crate::mix_selection(&mut data, output, selection, &src, fmt.alpha);
}
if ctl.cancelled() {
return None;
diff --git a/crates/algo/src/blur/motion_fft_tests.rs b/crates/algo/src/blur/motion_fft_tests.rs
index 12271d7bc..fd27434bc 100644
--- a/crates/algo/src/blur/motion_fft_tests.rs
+++ b/crates/algo/src/blur/motion_fft_tests.rs
@@ -280,7 +280,7 @@ fn motion_fft_pipeline_supports_depths_models_edges_selections_and_tile_seams()
for mask in [None, Some(&selection)] {
let mut expected_data = filtered.clone();
if let Some(mask) = mask {
- crate::mix_selection(&mut expected_data, rect, mask, &src);
+ crate::mix_selection(&mut expected_data, rect, mask, &src, alpha);
}
let mut expected = source.clone();
expected.write_region(rect, &expected_data);
@@ -362,7 +362,7 @@ fn motion_fft_production_crosses_real_tile_seams_and_leaves_other_pixels_untouch
let mut expected = source.clone();
let mut data = filtered.clone();
if let Some(mask) = mask {
- crate::mix_selection(&mut data, area, mask, &src);
+ crate::mix_selection(&mut data, area, mask, &src, true);
}
expected.write_region(area, &data);
let expected = Image::read(&expected, check);
diff --git a/crates/algo/src/blur/motion_tests.rs b/crates/algo/src/blur/motion_tests.rs
index 822cbb755..1141dec55 100644
--- a/crates/algo/src/blur/motion_tests.rs
+++ b/crates/algo/src/blur/motion_tests.rs
@@ -69,7 +69,7 @@ fn row_surface(surface: &Surface, params: &FilterParams, area: Rect, bounds: Rec
let ctx = Ctx { bounds, mode: format.mode, alpha: format.alpha };
let mut data = motion_rows(&src, area, &ctx, *angle, *distance);
if let Some(selection) = selection {
- crate::mix_selection(&mut data, area, selection, &src);
+ crate::mix_selection(&mut data, area, selection, &src, format.alpha);
}
let mut result = surface.clone();
result.write_region(area, &data);
diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs
index ded4ad31a..fdbe6dd72 100644
--- a/crates/algo/src/lib.rs
+++ b/crates/algo/src/lib.rs
@@ -1095,7 +1095,7 @@ fn apply_tiled_with_impl(
return (*t, Vec::new());
};
if let Some(sel) = selection {
- mix_selection(&mut data, *t, sel, src);
+ mix_selection(&mut data, *t, sel, src, fmt.alpha);
}
tick();
(*t, data)
@@ -1179,7 +1179,7 @@ fn apply_box_blur(
let write = |(s, v): &mut (Surface, Vec<blur::Strip>)| {
for (t, data) in v.iter_mut() {
if let Some(sel) = selection {
- mix_selection(data, *t, sel, &Image::read(surface, *t));
+ mix_selection(data, *t, sel, &Image::read(surface, *t), fmt.alpha);
}
s.write_region(*t, data);
}
@@ -1202,8 +1202,9 @@ fn apply_box_blur(
}
/// Mixes filtered `data` for `t` back toward the original pixels in `orig` by the selection's
-/// coverage (channel 0 of `sel`).
-fn mix_selection(data: &mut [f32], t: Rect, sel: &Surface, orig: &Image) {
+/// coverage (channel 0 of `sel`). Changing alpha requires premultiplied colour interpolation;
+/// otherwise hidden colours leak into feathered edges and alpha-removing filters darken them.
+fn mix_selection(data: &mut [f32], t: Rect, sel: &Surface, orig: &Image, alpha: bool) {
let w = t.width() as usize;
for (i, px) in data.chunks_exact_mut(orig.ch.max(1)).enumerate() {
let (x, y) = (t.x0 + (i % w) as i32, t.y0 + (i / w) as i32);
@@ -1211,6 +1212,27 @@ fn mix_selection(data: &mut [f32], t: Rect, sel: &Surface, orig: &Image) {
if k >= 1.0 {
continue;
}
+ if k <= 0.0 {
+ for (c, v) in px.iter_mut().enumerate() {
+ *v = orig.get(x, y, c);
+ }
+ continue;
+ }
+ if alpha {
+ let a = px.len() - 1;
+ let original_alpha = orig.get(x, y, a);
+ let filtered_alpha = px[a];
+ if original_alpha != filtered_alpha {
+ let mixed_alpha = original_alpha + (filtered_alpha - original_alpha) * k;
+ let original_weight = original_alpha * (1.0 - k);
+ let filtered_weight = filtered_alpha * k;
+ for (c, v) in px[..a].iter_mut().enumerate() {
+ *v = if mixed_alpha > 0.0 { (orig.get(x, y, c) * original_weight + *v * filtered_weight) / mixed_alpha } else { 0.0 };
+ }
+ px[a] = mixed_alpha;
+ continue;
+ }
+ }
for (c, v) in px.iter_mut().enumerate() {
let o = orig.get(x, y, c);
*v = o + (*v - o) * k;
@@ -1229,6 +1251,9 @@ mod tests_ext;
#[cfg(test)]
mod tests_mosaic;
+#[cfg(test)]
+mod tests_selection_mix;
+
/// The current upstream sampler through the identical source/selection/tile pipeline.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
diff --git a/crates/algo/src/pixelate/tests.rs b/crates/algo/src/pixelate/tests.rs
index 83d89bf30..c82d74732 100644
--- a/crates/algo/src/pixelate/tests.rs
+++ b/crates/algo/src/pixelate/tests.rs
@@ -153,7 +153,7 @@ fn tiled_filters_match_scalar_at_all_depths_with_soft_selection() {
FilterParams::ColorHalftone { max_radius, angles } => reference::halftone(&image, bounds, &ctx, max_radius, angles),
_ => Vec::new(),
};
- crate::mix_selection(&mut expected_data, bounds, &selection, &image);
+ crate::mix_selection(&mut expected_data, bounds, &selection, &image, ctx.alpha);
let mut expected = surface.clone();
expected.write_region(bounds, &expected_data);
for tile in [1, 7, 17, 256] {
diff --git a/crates/algo/src/shape_blur_tests.rs b/crates/algo/src/shape_blur_tests.rs
index 96f8f4c1e..02bdb0b3c 100644
--- a/crates/algo/src/shape_blur_tests.rs
+++ b/crates/algo/src/shape_blur_tests.rs
@@ -129,7 +129,7 @@ fn surfaces_exact_depth_models_alpha_selection_and_tile_boundaries() {
};
let spans = Spans::new(radius, shape_inside(shape));
let mut expected = conv_spans(&src, area, &ctx, &spans);
- crate::mix_selection(&mut expected, area, &selection, &src);
+ crate::mix_selection(&mut expected, area, &selection, &src, alpha);
let mut reference = surface.clone();
reference.write_region(area, &expected);
for tile in [17, 256] {
diff --git a/crates/algo/src/stylize2/tests.rs b/crates/algo/src/stylize2/tests.rs
index cc44558ea..3d7f6b523 100644
--- a/crates/algo/src/stylize2/tests.rs
+++ b/crates/algo/src/stylize2/tests.rs
@@ -167,17 +167,7 @@ fn storage_selection_and_tile_sizes_match_original_kernels() {
FilterParams::Wind { method, from_right, seed } => wind_direct(&src, area, &ctx, method, from_right, seed),
_ => continue,
};
- let original = s.read_region(area);
- for (i, px) in raw.chunks_exact_mut(fmt.channels()).enumerate() {
- let (x, y) = (area.x0 + (i % area.width() as usize) as i32, area.y0 + (i / area.width() as usize) as i32);
- let k = selection.sample_channel(x, y, 0);
- if k >= 1.0 {
- continue;
- }
- for (c, v) in px.iter_mut().enumerate() {
- *v = original[i * fmt.channels() + c] + (*v - original[i * fmt.channels() + c]) * k;
- }
- }
+ crate::mix_selection(&mut raw, area, &selection, &src, fmt.alpha);
let mut want = s.clone();
want.write_region(area, &raw);
for tile in [1, 7, 17, 256] {
diff --git a/crates/algo/src/tests_iris.rs b/crates/algo/src/tests_iris.rs
index 1f930c172..2d54c8f13 100644
--- a/crates/algo/src/tests_iris.rs
+++ b/crates/algo/src/tests_iris.rs
@@ -170,7 +170,7 @@ fn iris_depths_models_selection_tiles_and_cancellation() {
let t = Rect::new(x, y, (x + tile).min(area.x1), (y + tile).min(area.y1));
let src = Image::read_clamped(&surface, t.inflate(radius), bounds);
let mut data = reference::iris(&src, t, &ctx, &pins);
- crate::mix_selection(&mut data, t, &selection, &src);
+ crate::mix_selection(&mut data, t, &selection, &src, alpha);
want.write_region(t, &data);
}
}
diff --git a/crates/algo/src/tests_selection_mix.rs b/crates/algo/src/tests_selection_mix.rs
new file mode 100644
index 000000000..f715a8bbc
--- /dev/null
+++ b/crates/algo/src/tests_selection_mix.rs
@@ -0,0 +1,98 @@
+use super::*;
+use photocraft_color::{PixelFormat, SampleType};
+
+fn selection(coverage: f32) -> Surface {
+ Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[coverage])
+}
+
+#[test]
+fn feathered_color_to_alpha_preserves_appearance_over_the_key() {
+ let r = Rect::new(0, 0, 1, 1);
+ let filter = FilterParams::ColorToAlpha { color: [1.0; 4], transparency_threshold: 0.0, opacity_threshold: 1.0 };
+ for sample in SampleType::ALL {
+ for mode in [ColorMode::Rgb, ColorMode::Grayscale] {
+ for alpha in [0.5, 1.0] {
+ let format = PixelFormat::new(mode, sample, true);
+ let mut s = Surface::new(format);
+ let mut p = vec![0.5; format.channels()];
+ *p.last_mut().unwrap() = alpha;
+ s.write_pixel(0, 0, &p);
+ let original = s.pixel(0, 0);
+ let a = format.channels() - 1;
+ for coverage in [0.0, 0.25, 0.5, 0.75, 1.0] {
+ let out = apply(&s, &filter, r, r, Some(&selection(coverage)));
+ let actual = out.pixel(0, 0);
+ let tolerance = if sample == SampleType::U8 { 2.0 / 255.0 } else { 1e-4 };
+ for c in 0..a {
+ let before = original[c] * original[a] + 1.0 - original[a];
+ let after = actual[c] * actual[a] + 1.0 - actual[a];
+ assert!(
+ (before - after).abs() < tolerance,
+ "{sample:?}/{mode:?}, alpha={alpha}, coverage={coverage}: {original:?} -> {actual:?}, over white {before} -> {after}"
+ );
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn feathered_offset_ignores_hidden_colour_of_the_original_pixel() {
+ let r = Rect::new(0, 0, 2, 1);
+ let filter = FilterParams::Offset { horizontal: 1, vertical: 0, undefined: UndefinedAreas::Wrap };
+ for sample in SampleType::ALL {
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
+ s.write_pixel(0, 0, &[1.0, 0.0, 0.0, 0.0]);
+ s.write_pixel(1, 0, &[0.0, 0.0, 1.0, 1.0]);
+ let out = apply(&s, &filter, r, r, Some(&selection(0.5)));
+ let p = out.pixel(0, 0);
+ assert_eq!(&p[..3], &[0.0, 0.0, 1.0], "{sample:?}: hidden red contaminated the selected blue: {p:?}");
+ assert!((p[3] - 0.5).abs() < 1.0 / 255.0);
+ }
+}
+
+#[test]
+fn feathered_blurs_do_not_reintroduce_hidden_colour() {
+ let r = Rect::new(0, 0, 3, 3);
+ let mut s = Surface::new(PixelFormat::RGBA32F);
+ s.fill_rect(r, &[1.0, 0.0, 0.0, 0.0]);
+ s.write_pixel(1, 1, &[0.0, 0.0, 1.0, 1.0]);
+ for filter in [FilterParams::BoxBlur { radius: 1.0 }, FilterParams::MotionBlur { angle: 0.0, distance: 3.0 }] {
+ let full = apply(&s, &filter, r, r, None);
+ let out = apply(&s, &filter, r, r, Some(&selection(0.5)));
+ let p = out.pixel(0, 1);
+ assert!(p[3] > 0.0, "{filter:?}: expected blur to spread coverage");
+ assert!((p[3] - full.pixel(0, 1)[3] * 0.5).abs() < 1e-6, "{filter:?}: selection should halve the new coverage");
+ assert!(p[0].abs() < 1e-6 && (p[2] - 1.0).abs() < 1e-6, "{filter:?}: hidden red reappeared: {p:?}");
+ }
+}
+
+#[test]
+fn selection_mixing_keeps_hdr_range_and_exact_endpoints() {
+ let r = Rect::new(0, 0, 1, 1);
+ let original = Image { rect: r, ch: 4, data: vec![-2.0, 4.0, 0.5, 0.25] };
+ let filtered = vec![8.0, -4.0, 0.75, 1.0];
+ let mut data = filtered.clone();
+ mix_selection(&mut data, r, &selection(0.5), &original, true);
+ for (&actual, expected) in data.iter().zip([6.0, -2.4, 0.7, 0.625]) {
+ assert!((actual - expected).abs() < 1e-6, "{data:?}");
+ }
+ for coverage in [0.0, 1.0] {
+ let mut data = filtered.clone();
+ mix_selection(&mut data, r, &selection(coverage), &original, true);
+ assert_eq!(data, if coverage == 0.0 { &original.data } else { &filtered }.clone());
+ }
+}
+
+#[test]
+fn selection_mixing_without_alpha_keeps_every_channel_independent() {
+ let r = Rect::new(0, 0, 1, 1);
+ // One channel is a mask; three/four channels can be RGB or CMYK without alpha.
+ for ch in [1, 3, 4] {
+ let original = Image { rect: r, ch, data: vec![0.25; ch] };
+ let mut data = vec![0.75; ch];
+ mix_selection(&mut data, r, &selection(0.25), &original, false);
+ assert_eq!(data, vec![0.375; ch]);
+ }
+}
diff --git a/crates/algo/src/tests_tilt_shift.rs b/crates/algo/src/tests_tilt_shift.rs
index 49a6e79bb..88066ca9d 100644
--- a/crates/algo/src/tests_tilt_shift.rs
+++ b/crates/algo/src/tests_tilt_shift.rs
@@ -177,7 +177,7 @@ fn tilt_shift_depths_models_selection_and_tile_edges_match_reference() {
None => Image::read(&surface, t.inflate(radius)),
};
let mut data = reference::tilt_shift(&src, t, &ctx, 17.0, (0.3, 0.7), 29.0, 0.07, 0.3);
- crate::mix_selection(&mut data, t, &selection, &src);
+ crate::mix_selection(&mut data, t, &selection, &src, alpha);
want.write_region(t, &data);
}
}