Merge pull request #12152 from davidmann4/fix/11904-bg-eraser-find-edges-graded

Background Eraser: Find Edges erases soft edges graded instead of cutting them hard (#11904)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-08 17:00:18 +01:00
commit 535ea2d15c
3 files changed
+339 -14

No files matched your search

+49 -14
View File
@@ -16,8 +16,15 @@ use crate::retouch::{Footprint, Region, alpha_index, apply_dab_stroke};
#[serde(default, rename_all = "camelCase")]
pub struct BgEraseSettings {
pub sampling: Sampling,
/// Which matching pixels are erased. [`Limits::FindEdges`] grades the erase over the Tolerance
/// like [`Limits::Contiguous`] in this tool (#11904), unlike Color Replacement, where it turns
/// the soft falloff off.
pub limits: Limits,
/// 0..1: largest per-channel difference from the sampled colour that is erased.
/// 0..1: how far from the sampled colour a colour is still partly erased. The distance is the
/// largest increase plus the largest decrease over the colour channels (`dist`); an exact
/// match is erased fully, then less the further a colour is, and colours at or beyond the
/// Tolerance are kept (`graded_weight`). Protect Foreground Color still compares the
/// foreground by the largest per-channel difference (`max_channel_dist`).
pub tolerance: f32,
/// Keep pixels that match the foreground colour.
pub protect_foreground: bool,
@@ -40,11 +47,39 @@ impl Default for BgEraseSettings {
}
}
/// Largest per-channel difference over the colour channels.
/// Colour distance of `a` from `b` over the colour channels: the largest increase plus the largest
/// decrease (#11901). Changes in the same direction count like the largest of them; changes in
/// opposite directions add up, as the reference application measures them (a red-to-green edge is
/// about twice as far as one channel alone). One channel (Gray) gives the absolute difference.
fn dist(a: &[f32], b: &[f32]) -> f32 {
let (up, down) = a.iter().zip(b).fold((0.0f32, 0.0f32), |(up, down), (x, y)| {
let diff = x - y;
(up.max(diff), down.max(-diff))
});
up + down
}
/// The largest per-channel difference of `a` from `b`: the distance Protect Foreground Color keeps
/// using (#11901 measured only the sample match; #11903 keeps today's measure for the foreground).
fn max_channel_dist(a: &[f32], b: &[f32]) -> f32 {
a.iter().zip(b).fold(0.0f32, |m, (x, y)| m.max((x - y).abs()))
}
/// The match weight of one dab for a colour `d` away from the sampled colour (#11901): an exact
/// match is erased fully, then the weight falls off linearly over the whole Tolerance `tol` after
/// a short plateau `d0 = min(tol / 20, 8 levels)`, and colours at or beyond the Tolerance are kept.
/// Measured in the reference application with single clicks (one dab) at Tolerance 10 to 100.
fn graded_weight(d: f32, tol: f32) -> f32 {
if !d.is_finite() || d >= tol {
return if d <= 0.0 { 1.0 } else { 0.0 };
}
let d0 = (tol / 20.0).min(8.0 / 255.0);
if d <= d0 {
return 1.0;
}
(1.0 - (d - d0) / (tol - d0)).clamp(0.0, 1.0)
}
/// Erase along `stroke`. The brush opacity is ignored (Photoshop's Background Eraser has none);
/// the selection limits the effect. Returns the damaged rectangle; empty when the surface has no
/// alpha channel.
@@ -70,22 +105,14 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option<i
let a = alpha_index(&fmt)?;
let nc = a;
let tol = if bs.tolerance.is_finite() { bs.tolerance.clamp(0.0, 1.0) } else { 0.0 };
let soft = bs.limits != Limits::FindEdges;
let native = |c: [f32; 4]| -> Vec<f32> { from_rgba(&fmt, [c[0], c[1], c[2], 1.0])[..nc].to_vec() };
let swatch = native(bs.background);
let fg = native(bs.foreground);
let (sampling, limits, protect_foreground) = (bs.sampling, bs.limits, bs.protect_foreground);
let mut once: Option<Option<Vec<f32>>> = None;
let match_w = move |d: f32| -> f32 {
if d > tol {
0.0
} else if soft && tol > 0.0 {
// Soft falloff over the last quarter of the tolerance.
((tol - d) / (tol * 0.25)).clamp(0.0, 1.0)
} else {
1.0
}
};
// Find Edges grades soft edges like Contiguous does instead of cutting them hard (#11904):
// the reference application keeps at least as much of a blurred transition with it.
let match_w = move |d: f32| -> f32 { graded_weight(d, tol) };
let pre = pre.clone();
// The pixels before the stroke under the working copy, read once per working area. Sampling
// and matching read these, so a dab landing on pixels earlier dabs already erased still
@@ -130,7 +157,7 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option<i
continue;
}
let c = &p[..nc];
if protect_foreground && dist(c, &fg) <= tol {
if protect_foreground && max_channel_dist(c, &fg) <= tol {
continue;
}
weight[(y - r.y0) as usize * w + (x - r.x0) as usize] = match_w(dist(c, &sampled));
@@ -191,6 +218,14 @@ fn keep_connected(weight: &mut [f32], w: usize, h: usize, sx: usize, sy: usize)
}
}
#[cfg(test)]
#[path = "bg_erase_graded_alpha_tests.rs"]
mod graded_alpha_tests;
#[cfg(test)]
#[path = "bg_erase_find_edges_tests.rs"]
mod find_edges_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,101 @@
//! Background Eraser Limits Find Edges (#11904): a blurred edge is erased graded, keeping at least
//! as much of the transition as Contiguous does, instead of cut hard at the Tolerance. Expected
//! values are the reference application's measurements from the issue (8-bit RGB, 40 px and 60 px
//! hard round tips, Tolerance 50, Sampling Continuous).
use photocraft_color::PixelFormat;
use photocraft_geom::Rect;
use photocraft_raster::{Surface, from_rgba};
use crate::bg_erase::{BgEraseSettings, apply_background_eraser};
use crate::replace::{Limits, Sampling};
use crate::{BrushSettings, Stroke, StrokePoint};
/// Measured red channel along y 70 from x 185 across the 4 px Gaussian red|green edge at x 200.
const RED: [i32; 30] = [220, 220, 220, 220, 219, 219, 217, 214, 210, 203, 194, 182, 168, 152, 134, 116, 98, 82, 68, 56, 47, 40, 36, 33, 31, 31, 30, 30, 30, 30];
/// Alpha along y 70 from x 185 after a click at 190,70.
const FIND_EDGES: [i32; 15] = [8, 8, 8, 4, 4, 0, 0, 0, 17, 42, 76, 121, 176, 238, 255];
const CONTIGUOUS: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 4, 21, 46, 79, 123, 178, 238, 255];
fn rgb(c: [i32; 3]) -> [f32; 4] {
[c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0]
}
/// The issue's test layer: red | green | blue | pink stripes (y 0-300), a white gap at y 140-160
/// across the red stripe, and the red|green edge blurred over y 0-130. A Gaussian blur mixes every
/// channel with the same weights, so green and blue follow red's mix fraction.
fn layer() -> Surface {
let fmt = PixelFormat::RGBA8;
let mut s = Surface::new(fmt);
for (x0, c) in [(0, [220, 30, 30]), (200, [30, 180, 60]), (400, [40, 60, 220]), (600, [240, 120, 120])] {
s.fill_rect(Rect::new(x0, 0, x0 + 200, 300), &from_rgba(&fmt, rgb(c)));
}
s.fill_rect(Rect::new(0, 140, 200, 160), &from_rgba(&fmt, rgb([255, 255, 255])));
for (i, r) in RED.iter().enumerate() {
let t = (220 - r) as f32 / 190.0;
let c = [*r as f32 / 255.0, (30.0 + 150.0 * t) / 255.0, (30.0 + 30.0 * t) / 255.0, 1.0];
let x = 185 + i as i32;
s.fill_rect(Rect::new(x, 0, x + 1, 130), &from_rgba(&fmt, c));
}
s
}
fn click(at: (f64, f64), size: f32, limits: Limits) -> Surface {
let mut s = layer();
let stroke = Stroke {
brush: BrushSettings { size, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() },
points: vec![StrokePoint::new(at.0, at.1, 1.0)],
};
let bs = BgEraseSettings { sampling: Sampling::Continuous, limits, tolerance: 0.5, ..Default::default() };
apply_background_eraser(&mut s, &stroke, &bs, None);
s
}
fn alpha(s: &Surface, x: i32, y: i32) -> i32 {
(s.rgba(x, y)[3] * 255.0).round() as i32
}
#[test]
fn find_edges_grades_a_blurred_edge_instead_of_cutting_it() {
let fe = click((190.0, 70.0), 40.0, Limits::FindEdges);
let co = click((190.0, 70.0), 40.0, Limits::Contiguous);
for (i, want) in FIND_EDGES.iter().enumerate() {
let x = 185 + i as i32;
let (f, c) = (alpha(&fe, x, 70), alpha(&co, x, 70));
assert!((f - want).abs() <= 10, "x {x}: Find Edges alpha {f}, measured {want}");
assert!(f >= c, "x {x}: Find Edges keeps {f}, less than Contiguous's {c}");
}
// Past the transition nothing is erased (before, Find Edges cut through x 201).
for x in 200..230 {
assert_eq!(alpha(&fe, x, 70), 255, "x {x}");
}
}
#[test]
fn find_edges_on_a_hard_edge_gives_the_contiguous_result() {
// 60 px tip at 100,138 on red just above the white gap: column x 100 erased through y 139, the
// gap and the red below it kept.
let fe = click((100.0, 138.0), 60.0, Limits::FindEdges);
let co = click((100.0, 138.0), 60.0, Limits::Contiguous);
for y in 100..176 {
assert_eq!(alpha(&fe, 100, y), alpha(&co, 100, y), "y {y}");
}
for y in 110..140 {
assert_eq!(alpha(&fe, 100, y), 0, "red above the gap, y {y}");
}
for y in 140..176 {
assert_eq!(alpha(&fe, 100, y), 255, "the gap and the red below it, y {y}");
}
}
#[test]
fn contiguous_and_discontiguous_keep_their_results() {
// This item changes only Find Edges: the other two limits still give the measured row.
for limits in [Limits::Contiguous, Limits::Discontiguous] {
let s = click((190.0, 70.0), 40.0, limits);
for (i, want) in CONTIGUOUS.iter().enumerate() {
let x = 185 + i as i32;
assert!((alpha(&s, x, 70) - want).abs() <= 8, "{limits:?} x {x}: {} against {want}", alpha(&s, x, 70));
}
}
}
@@ -0,0 +1,189 @@
//! Background Eraser graded alpha (#11901): one dab erases a colour less the further it is from the
//! sampled colour, over the whole Tolerance, not fully up to the Tolerance. Expected values are the
//! reference application's single-click measurements from the issue (8-bit RGB, 40 px hard round
//! tip, Sampling Background Swatch with background (200,40,40), alpha at the patch centre).
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_geom::Rect;
use photocraft_raster::{Surface, from_rgba};
use crate::bg_erase::{BgEraseSettings, apply_background_eraser};
use crate::replace::{Limits, Sampling};
use crate::{BrushSettings, Stroke, StrokePoint};
/// The sampled colour of every measurement: (200,40,40).
const SAMPLE: [i32; 3] = [200, 40, 40];
/// Allowed deviation from the measured alpha ("within 8 levels").
const LEVELS: i32 = 8;
fn rgb(c: [i32; 3]) -> [f32; 4] {
[c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0]
}
fn click(at: (f64, f64)) -> Stroke {
Stroke {
brush: BrushSettings { size: 40.0, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() },
points: vec![StrokePoint::new(at.0, at.1, 1.0)],
}
}
fn swatch(tolerance_percent: f32, background: [f32; 4]) -> BgEraseSettings {
BgEraseSettings {
sampling: Sampling::BackgroundSwatch,
limits: Limits::Discontiguous,
tolerance: tolerance_percent / 100.0,
background,
..Default::default()
}
}
/// One click in the centre of a 100 px patch of `colour` (straight RGBA) in `fmt`; alpha 0-255 at
/// the centre.
fn one_click(fmt: PixelFormat, colour: [f32; 4], bs: &BgEraseSettings) -> i32 {
let mut s = Surface::new(fmt);
s.fill_rect(Rect::new(0, 0, 100, 100), &from_rgba(&fmt, colour));
apply_background_eraser(&mut s, &click((50.0, 50.0)), bs, None);
(s.rgba(50, 50)[3] * 255.0).round() as i32
}
/// The measured single-click table: (Tolerance, [(green difference d, alpha)]).
fn single_click_table() -> Vec<(f32, Vec<(i32, i32)>)> {
vec![
(10.0, vec![(10, 92), (20, 194), (30, 255), (40, 255)]),
(30.0, vec![(10, 21), (20, 56), (30, 91), (40, 126), (50, 161), (60, 196), (80, 255), (100, 255)]),
(50.0, vec![(10, 8), (20, 29), (30, 50), (40, 71), (50, 92), (60, 113), (80, 155), (100, 196), (120, 238), (140, 255)]),
(70.0, vec![(10, 3), (20, 18), (30, 33), (40, 48), (50, 63), (60, 78), (80, 107), (100, 137), (120, 167), (140, 197), (160, 227)]),
(100.0, vec![(10, 2), (20, 12), (30, 23), (40, 33), (50, 43), (60, 54), (80, 74), (100, 95), (120, 116), (140, 136), (160, 157)]),
]
}
fn assert_near(got: i32, want: i32, what: &str) {
assert!((got - want).abs() <= LEVELS, "{what}: got alpha {got}, measured {want}");
}
#[test]
fn one_click_falls_off_over_the_whole_tolerance() {
let bs = |tol| swatch(tol, rgb(SAMPLE));
for (tol, row) in single_click_table() {
for (d, want) in row {
let got = one_click(PixelFormat::RGBA8, rgb([SAMPLE[0], SAMPLE[1] + d, SAMPLE[2]]), &bs(tol));
assert_near(got, want, &format!("Tolerance {tol}, green +{d}"));
}
}
}
#[test]
fn same_sign_differences_count_once_and_opposite_signs_add_up() {
// Measured at Tolerance 50, single clicks, sample (200,40,40): (difference per channel, alpha).
let rows: [([i32; 3], i32); 15] = [
([0, 20, 0], 29),
([-20, 0, 0], 29),
([0, 0, 20], 29),
([0, 20, 20], 29),
([0, 40, 20], 71),
([0, 20, 40], 71),
([0, 60, 20], 113),
([-20, 20, 0], 71),
([-40, 40, 0], 155),
([-60, 60, 0], 238),
([10, 10, 10], 8),
([20, 20, 20], 29),
([40, 40, 40], 71),
([-10, -10, -10], 8),
([-40, -40, -40], 71),
];
let bs = swatch(50.0, rgb(SAMPLE));
for (diff, want) in rows {
let colour = [SAMPLE[0] + diff[0], SAMPLE[1] + diff[1], SAMPLE[2] + diff[2]];
assert_near(one_click(PixelFormat::RGBA8, rgb(colour), &bs), want, &format!("difference {diff:?}"));
}
}
#[test]
fn a_blurred_edge_keeps_its_transition_graded() {
// Red (220,30,30) | green (30,180,60) at x 200, blurred with a 4 px Gaussian; the measured red
// channel along y 70 from x 185. A Gaussian blur mixes every channel with the same weights, so
// green and blue follow red's mix fraction.
const RED: [i32; 30] =
[220, 220, 220, 220, 219, 219, 217, 214, 210, 203, 194, 182, 168, 152, 134, 116, 98, 82, 68, 56, 47, 40, 36, 33, 31, 31, 30, 30, 30, 30];
const ALPHA: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 4, 21, 46, 79, 123, 178, 238, 255];
let fmt = PixelFormat::RGBA8;
let mut s = Surface::new(fmt);
s.fill_rect(Rect::new(0, 0, 185, 140), &from_rgba(&fmt, rgb([220, 30, 30])));
s.fill_rect(Rect::new(215, 0, 400, 140), &from_rgba(&fmt, rgb([30, 180, 60])));
for (i, r) in RED.iter().enumerate() {
let t = (220 - r) as f32 / 190.0;
let c = [*r as f32 / 255.0, (30.0 + 150.0 * t) / 255.0, (30.0 + 30.0 * t) / 255.0, 1.0];
let x = 185 + i as i32;
s.fill_rect(Rect::new(x, 0, x + 1, 140), &from_rgba(&fmt, c));
}
for limits in [Limits::Contiguous, Limits::Discontiguous] {
let mut t = s.clone();
let bs = BgEraseSettings { sampling: Sampling::Once, limits, tolerance: 0.5, ..Default::default() };
apply_background_eraser(&mut t, &click((190.0, 70.0)), &bs, None);
for (i, want) in ALPHA.iter().enumerate() {
let x = 185 + i as i32;
let got = (t.rgba(x, 70)[3] * 255.0).round() as i32;
assert_near(got, *want, &format!("{limits:?} x {x}"));
}
for x in 200..215 {
assert_eq!(t.rgba(x, 70)[3], 1.0, "{limits:?} x {x} beyond the Tolerance kept");
}
}
}
#[test]
fn an_exact_match_is_erased_and_far_colours_are_kept_at_every_tolerance() {
for tol in [0.0, 1.0, 10.0, 30.0, 50.0, 70.0, 100.0] {
let bs = swatch(tol, rgb(SAMPLE));
assert_eq!(one_click(PixelFormat::RGBA8, rgb(SAMPLE), &bs), 0, "Tolerance {tol}: the sample itself");
if tol < 100.0 {
// Opposite-sign differences of 255 + 215: beyond every Tolerance below 100 %.
assert_eq!(one_click(PixelFormat::RGBA8, rgb([0, 255, 40]), &bs), 255, "Tolerance {tol}: a far colour");
}
}
// Tolerance 0 erases nothing but the exact colour.
assert_eq!(one_click(PixelFormat::RGBA8, rgb([200, 41, 40]), &swatch(0.0, rgb(SAMPLE))), 255);
}
#[test]
fn the_distance_is_measured_in_the_documents_own_channels() {
// 16-bit RGB: the same single-click table as 8-bit.
let rgb16 = PixelFormat::new(ColorMode::Rgb, SampleType::U16, true);
for (tol, row) in single_click_table() {
for (d, want) in row {
let got = one_click(rgb16, rgb([SAMPLE[0], SAMPLE[1] + d, SAMPLE[2]]), &swatch(tol, rgb(SAMPLE)));
assert_near(got, want, &format!("16-bit Tolerance {tol}, green +{d}"));
}
}
// Gray (8 and 16 bit): the distance is the absolute difference of the gray levels, so a gray
// patch d levels from the swatch erases like a one-channel difference of d in RGB, either way.
for sample in [SampleType::U8, SampleType::U16] {
let gray = PixelFormat::new(ColorMode::Grayscale, sample, true);
let level = |v: i32| [v as f32 / 255.0, v as f32 / 255.0, v as f32 / 255.0, 1.0];
for (tol, row) in single_click_table() {
for (d, want) in row {
let bs = swatch(tol, level(60));
if 60 + d <= 255 {
assert_near(one_click(gray, level(60 + d), &bs), want, &format!("{sample:?} gray Tolerance {tol}, +{d}"));
}
if d <= 60 {
assert_near(one_click(gray, level(60 - d), &bs), want, &format!("{sample:?} gray Tolerance {tol}, -{d}"));
}
}
}
}
}
#[test]
fn protect_foreground_keeps_todays_distance_to_the_foreground() {
// #11903 measured the foreground only one channel away and keeps today's measure otherwise:
// the largest per-channel difference. This foreground is 100 levels off in red and in green
// (opposite signs): within Tolerance 50 by that measure, though the sample-match distance of
// #11901 adds the two to 200. The pixel is the sampled colour, so only the protection keeps it.
let bs = BgEraseSettings { protect_foreground: true, foreground: rgb([100, 140, 40]), ..swatch(50.0, rgb(SAMPLE)) };
assert_eq!(one_click(PixelFormat::RGBA8, rgb(SAMPLE), &bs), 255);
// Protection off: the same click erases the sample fully.
assert_eq!(one_click(PixelFormat::RGBA8, rgb(SAMPLE), &BgEraseSettings { protect_foreground: false, ..bs }), 0);
}