Skip to content

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

fix(segment): let Remove Background's cancel stop Select Subject's min cuts (#4878)

LloydNicholson25a82978b21e
diff --git a/crates/algo/src/segment/grabcut.rs b/crates/algo/src/segment/grabcut.rs
index ae1a586c1..573c09079 100644
--- a/crates/algo/src/segment/grabcut.rs
+++ b/crates/algo/src/segment/grabcut.rs
@@ -7,9 +7,10 @@
//! `γ e^{−β‖z_m − z_n‖²} / dist(m, n)` (γ = 50, β from the mean squared neighbour difference).
use photocraft_geom::Rect;
+use photocraft_raster::{Cancelled, Interrupt};
use super::gmm::{DEFAULT_REG, Gmm};
-use super::{FREE, HARD_BG, HARD_FG, Region, RgbImage, Sampler, contrast_beta, data_costs, grid_cut, subsample};
+use super::{FREE, HARD_BG, HARD_FG, Region, RgbImage, Sampler, contrast_beta, data_costs, grid_cut_cancellable, subsample};
/// Definite background.
pub const BG: u8 = 0;
@@ -33,6 +34,13 @@ fn is_fg(t: u8) -> bool {
/// Runs `iters` GrabCut iterations, updating the probable labels of `trimap` in place. Returns
/// the final (foreground, background) models, or `None` if either side has no pixels.
pub fn grabcut(img: &RgbImage, trimap: &mut [u8], iters: usize) -> Option<(Gmm, Gmm)> {
+ grabcut_with(img, trimap, iters, &Interrupt::NONE).unwrap_or_default()
+}
+
+/// [`grabcut`] that stops with `Err(Cancelled)` once `ctl` is cancelled, asked each iteration
+/// and inside its min cut. `trimap` is then partly updated.
+pub fn grabcut_with(img: &RgbImage, trimap: &mut [u8], iters: usize, ctl: &Interrupt) -> Result<Option<(Gmm, Gmm)>, Cancelled> {
+ let cancel = || ctl.cancelled();
let beta = contrast_beta(img);
let fixed: Vec<u8> = trimap
.iter()
@@ -44,17 +52,22 @@ pub fn grabcut(img: &RgbImage, trimap: &mut [u8], iters: usize) -> Option<(Gmm,
.collect();
let mut models: Option<(Gmm, Gmm)> = None;
for _ in 0..iters.max(1) {
+ ctl.check()?;
let (mut fs, mut bs) = (Vec::new(), Vec::new());
for (p, t) in img.px.iter().zip(trimap.iter()) {
if is_fg(*t) { fs.push(*p) } else { bs.push(*p) }
}
let (fs, bs) = (subsample(&fs, MAX_SAMPLES), subsample(&bs, MAX_SAMPLES));
let (fg, bg) = match &models {
- None => (Gmm::fit(&fs, K, DEFAULT_REG)?, Gmm::fit(&bs, K, DEFAULT_REG)?),
+ None => match (Gmm::fit(&fs, K, DEFAULT_REG), Gmm::fit(&bs, K, DEFAULT_REG)) {
+ (Some(f), Some(b)) => (f, b),
+ _ => return Ok(None),
+ },
Some((f, b)) => (f.refit(&fs).unwrap_or_else(|| f.clone()), b.refit(&bs).unwrap_or_else(|| b.clone())),
};
let (cf, cb) = data_costs(img, &fg, &bg);
- let cut = grid_cut(img, &cf, &cb, &fixed, GAMMA, beta);
+ // `grid_cut`'s weight, with the cut stopping on cancel.
+ let cut = grid_cut_cancellable(img, &cf, &cb, &fixed, |d2| GAMMA * (-beta * d2).exp(), &cancel).ok_or(Cancelled)?;
let mut changed = 0usize;
for (t, fgnd) in trimap.iter_mut().zip(&cut) {
if *t == PR_BG || *t == PR_FG {
@@ -68,7 +81,7 @@ pub fn grabcut(img: &RgbImage, trimap: &mut [u8], iters: usize) -> Option<(Gmm,
break;
}
}
- models
+ Ok(models)
}
/// Object Selection (rectangle mode): GrabCut initialised from `rect` (outside = background,
diff --git a/crates/algo/src/segment/mod.rs b/crates/algo/src/segment/mod.rs
index 90cc2f502..5c190e643 100644
--- a/crates/algo/src/segment/mod.rs
+++ b/crates/algo/src/segment/mod.rs
@@ -35,7 +35,7 @@ pub mod slic;
pub mod subject;
use photocraft_geom::Rect;
-use photocraft_raster::Surface;
+use photocraft_raster::{Cancelled, Interrupt, Surface};
pub use crate::selection::Region;
use gmm::Gmm;
@@ -545,6 +545,22 @@ pub fn trim_region(r: Region) -> Option<Region> {
/// pixels wide around the upsampled boundary, using the given colour models, tile by tile.
/// The result is anti-aliased by one pixel.
pub fn finish_region(sampler: &dyn Sampler, window: Rect, step: usize, low: &[bool], lw: usize, lh: usize, models: Option<(&Gmm, &Gmm)>) -> Option<Region> {
+ finish_region_with(sampler, window, step, low, lw, lh, models, &Interrupt::NONE).unwrap_or_default()
+}
+
+/// [`finish_region`] that stops with `Err(Cancelled)` once `ctl` is cancelled, asked before each
+/// band tile and inside its min cut.
+#[allow(clippy::too_many_arguments)]
+pub fn finish_region_with(
+ sampler: &dyn Sampler,
+ window: Rect,
+ step: usize,
+ low: &[bool],
+ lw: usize,
+ lh: usize,
+ models: Option<(&Gmm, &Gmm)>,
+ ctl: &Interrupt,
+) -> Result<Option<Region>, Cancelled> {
let (w, h) = (window.width() as usize, window.height() as usize);
let mut mask = vec![0u8; w * h];
if step <= 1 {
@@ -582,16 +598,28 @@ pub fn finish_region(sampler: &dyn Sampler, window: Rect, step: usize, low: &[bo
#[cfg(target_arch = "wasm32")]
mask.chunks_mut(w).enumerate().for_each(|(y, r)| fill(y, r));
if let Some((fg, bg)) = models {
- refine_band(sampler, window, step, low, &band, lw, lh, fg, bg, &mut mask);
+ refine_band(sampler, window, step, low, &band, lw, lh, fg, bg, &mut mask, ctl)?;
}
}
antialias_u8(&mut mask, w, h);
- trim_region(Region { bbox: window, mask })
+ Ok(trim_region(Region { bbox: window, mask }))
}
/// Full-resolution graph cut restricted to the band blocks (see [`finish_region`]).
#[allow(clippy::too_many_arguments)]
-fn refine_band(sampler: &dyn Sampler, window: Rect, step: usize, low: &[bool], band: &[bool], lw: usize, lh: usize, fg: &Gmm, bg: &Gmm, mask: &mut [u8]) {
+fn refine_band(
+ sampler: &dyn Sampler,
+ window: Rect,
+ step: usize,
+ low: &[bool],
+ band: &[bool],
+ lw: usize,
+ lh: usize,
+ fg: &Gmm,
+ bg: &Gmm,
+ mask: &mut [u8],
+ ctl: &Interrupt,
+) -> Result<(), Cancelled> {
const T: i32 = 192;
const HALO: i32 = 12;
let w = window.width() as usize;
@@ -612,7 +640,9 @@ fn refine_band(sampler: &dyn Sampler, window: Rect, step: usize, low: &[bool], b
}
ty += T;
}
- let run = |t: &Rect| -> (Rect, Vec<bool>) {
+ let cancel = || ctl.cancelled();
+ let run = |t: &Rect| -> Result<(Rect, Vec<bool>), Cancelled> {
+ ctl.check()?;
let r = t.inflate(HALO).intersect(&window);
let img = sampler.rgb(r);
let (rw, rh) = (r.width() as usize, r.height() as usize);
@@ -635,7 +665,8 @@ fn refine_band(sampler: &dyn Sampler, window: Rect, step: usize, low: &[bool], b
}
}
let beta = contrast_beta(&img);
- let cut = grid_cut(&img, &cfg, &cbg, &fixed, 50.0, beta);
+ // `grid_cut`'s weight, with the cut stopping on cancel.
+ let cut = grid_cut_cancellable(&img, &cfg, &cbg, &fixed, |d2| 50.0 * (-beta * d2).exp(), &cancel).ok_or(Cancelled)?;
let (cw, ch) = (t.width() as usize, t.height() as usize);
let mut core = Vec::with_capacity(cw * ch);
for yy in 0..ch {
@@ -643,15 +674,16 @@ fn refine_band(sampler: &dyn Sampler, window: Rect, step: usize, low: &[bool], b
let sx = (t.x0 - r.x0) as usize;
core.extend_from_slice(&cut[sy * rw + sx..sy * rw + sx + cw]);
}
- (*t, core)
+ Ok((*t, core))
};
+ // A cancelled tile ends the collect; tiles not yet started see `ctl` and return at once.
#[cfg(not(target_arch = "wasm32"))]
let results: Vec<(Rect, Vec<bool>)> = {
use rayon::prelude::*;
- tiles.par_iter().map(run).collect()
+ tiles.par_iter().map(run).collect::<Result<_, _>>()?
};
#[cfg(target_arch = "wasm32")]
- let results: Vec<(Rect, Vec<bool>)> = tiles.iter().map(run).collect();
+ let results: Vec<(Rect, Vec<bool>)> = tiles.iter().map(run).collect::<Result<_, _>>()?;
for (t, core) in results {
let cw = t.width() as usize;
for (yy, row) in core.chunks_exact(cw).enumerate() {
@@ -661,6 +693,7 @@ fn refine_band(sampler: &dyn Sampler, window: Rect, step: usize, low: &[bool], b
}
}
}
+ Ok(())
}
/// Deterministic pseudo-random numbers (xorshift) for sampling and tests.
diff --git a/crates/algo/src/segment/subject.rs b/crates/algo/src/segment/subject.rs
index 6002672ad..b117bb5ef 100644
--- a/crates/algo/src/segment/subject.rs
+++ b/crates/algo/src/segment/subject.rs
@@ -23,6 +23,7 @@ use std::cmp::Ordering;
use std::collections::BinaryHeap;
use photocraft_geom::Rect;
+use photocraft_raster::{Cancelled, Interrupt};
use super::grabcut::{self, BG, PR_BG, PR_FG};
use super::slic::{rgb_to_lab, slic_lab};
@@ -35,13 +36,20 @@ const SIGMA_SPA: f32 = 0.25;
/// Selects the most salient object on the canvas.
pub fn select_subject(sampler: &dyn Sampler, canvas: Rect) -> Option<Region> {
+ select_subject_with(sampler, canvas, &Interrupt::NONE).unwrap_or_default()
+}
+
+/// [`select_subject`] that stops with `Err(Cancelled)` once `ctl` is cancelled, asked between
+/// stages and inside every min cut (the GrabCut iterations and the full-resolution re-cut).
+pub fn select_subject_with(sampler: &dyn Sampler, canvas: Rect, ctl: &Interrupt) -> Result<Option<Region>, Cancelled> {
if canvas.width() < 4 || canvas.height() < 4 {
- return None;
+ return Ok(None);
}
let step = super::scale_for(canvas, WORK_PX);
let img = sampler.rgb_scaled(canvas, step);
let (w, h) = (img.w, img.h);
let sal = saliency(&img);
+ ctl.check()?;
let t = otsu(&sal).clamp(0.15, 0.85);
let mut trimap = vec![PR_BG; w * h];
let mut any_fg = false;
@@ -60,15 +68,15 @@ pub fn select_subject(sampler: &dyn Sampler, canvas: Rect) -> Option<Region> {
}
}
if !any_fg {
- return None;
+ return Ok(None);
}
- let (fg, bg) = grabcut::grabcut(&img, &mut trimap, 6)?;
+ let Some((fg, bg)) = grabcut::grabcut_with(&img, &mut trimap, 6, ctl)? else { return Ok(None) };
let low: Vec<bool> = trimap.iter().map(|v| *v == PR_FG || *v == grabcut::FG).collect();
let low = super::clean_mask(&low, w, h, 0.2, 0.05);
if !low.iter().any(|v| *v) {
- return None;
+ return Ok(None);
}
- super::finish_region(sampler, canvas, step, &low, w, h, Some((&fg, &bg)))
+ super::finish_region_with(sampler, canvas, step, &low, w, h, Some((&fg, &bg)), ctl)
}
/// Per-pixel saliency in `0..=1` (see the module docs).
diff --git a/crates/algo/src/segment/tests.rs b/crates/algo/src/segment/tests.rs
index 869f3c671..55ddc6caf 100644
--- a/crates/algo/src/segment/tests.rs
+++ b/crates/algo/src/segment/tests.rs
@@ -565,6 +565,87 @@ fn select_subject_finds_centred_object() {
assert!(v > 0.9, "IoU {v}");
}
+/// Counts full-resolution reads; the working copy goes through `rgb_scaled` uncounted, so each
+/// read is one band tile of the full-resolution re-cut.
+struct TileReads<'a>(ImageSampler<'a>, std::sync::atomic::AtomicUsize);
+
+impl Sampler for TileReads<'_> {
+ fn rgba(&self, r: Rect) -> Vec<[f32; 4]> {
+ self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ self.0.rgba(r)
+ }
+ fn rgb_scaled(&self, r: Rect, step: usize) -> RgbImage {
+ self.0.rgb_scaled(r, step)
+ }
+}
+
+#[test]
+fn finish_region_cancel_stops_inside_the_band_cut() {
+ use photocraft_raster::{Cancelled, Interrupt};
+ use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
+ // One 180-pixel window is one band tile, and nothing asks after the band re-cut, so a cancel
+ // seen after the tile's own check can only have been seen inside its min cut.
+ let (n, step) = (180, 3);
+ let (img, truth) = disc_scene(n, n, 90.0, 90.0, 55.0, 4);
+ let s = ImageSampler { img: &img, origin: (0, 0) };
+ let ln = n / step;
+ let low: Vec<bool> = (0..ln * ln).map(|i| truth[((i / ln) * step + 1) * n + (i % ln) * step + 1]).collect();
+ let (fs, bs): (Vec<_>, Vec<_>) = img.px.iter().zip(&truth).partition(|(_, t)| **t);
+ let fit = |v: Vec<(&[f32; 3], &bool)>| Gmm::fit(&v.iter().map(|(p, _)| **p).collect::<Vec<_>>(), 5, gmm::DEFAULT_REG).unwrap();
+ let (fg, bg) = (fit(fs), fit(bs));
+ let window = Rect::new(0, 0, n as i32, n as i32);
+ let polls = AtomicUsize::new(0);
+ let finish = |cancel_from: usize| {
+ polls.store(0, SeqCst);
+ let cancel = || polls.fetch_add(1, SeqCst) + 1 >= cancel_from;
+ finish_region_with(&s, window, step, &low, ln, ln, Some((&fg, &bg)), &Interrupt::cancel_only(&cancel))
+ };
+ let reg = finish(usize::MAX).unwrap().unwrap();
+ assert!(polls.load(SeqCst) >= 2, "the cut polls too ({} polls)", polls.load(SeqCst));
+ assert!(iou(&reg, &truth, n, n) > 0.95);
+ assert_eq!(finish_region(&s, window, step, &low, ln, ln, Some((&fg, &bg))), Some(reg));
+ // Cancelled at the cut's first poll (the second in all): no region.
+ assert_eq!(finish(2), Err(Cancelled));
+ assert_eq!(polls.load(SeqCst), 2);
+ assert_eq!(finish(1), Err(Cancelled), "cancelled before the tile");
+}
+
+#[test]
+fn select_subject_cancelled_in_the_band_recut_reads_no_more_tiles() {
+ use photocraft_raster::{Cancelled, Interrupt};
+ use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
+ let (w, h) = (3000, 2000);
+ let (img, truth) = disc_scene(w, h, 1500.0, 1000.0, 700.0, 6);
+ let canvas = Rect::new(0, 0, w as i32, h as i32);
+ let sampler = || TileReads(ImageSampler { img: &img, origin: (0, 0) }, AtomicUsize::new(0));
+
+ // Not cancelled: the same region as `select_subject`, and the band cuts themselves ask
+ // (more polls once tiles are read than the one check before each tile).
+ let s = sampler();
+ let band_polls = AtomicUsize::new(0);
+ let count = || {
+ if s.1.load(SeqCst) > 0 {
+ band_polls.fetch_add(1, SeqCst);
+ }
+ false
+ };
+ let reg = subject::select_subject_with(&s, canvas, &Interrupt::cancel_only(&count)).unwrap().unwrap();
+ let tiles = s.1.load(SeqCst);
+ assert!(tiles > 4, "{tiles} band tiles");
+ assert!(band_polls.load(SeqCst) > tiles, "{} polls over {tiles} tiles", band_polls.load(SeqCst));
+ assert!(iou(&reg, &truth, w, h) > 0.9);
+ assert_eq!(subject::select_subject(&sampler(), canvas), Some(reg));
+
+ // Cancelled once the first tile is read: the run stops there instead of re-cutting every
+ // tile. One thread, so no other tile is already in flight.
+ let s = sampler();
+ let cancel = || s.1.load(SeqCst) > 0;
+ let pool = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap();
+ let r = pool.install(|| subject::select_subject_with(&s, canvas, &Interrupt::cancel_only(&cancel)));
+ assert_eq!(r, Err(Cancelled));
+ assert_eq!(s.1.load(SeqCst), 1, "tiles read after the cancel");
+}
+
#[test]
fn saliency_highlights_the_object() {
let (img, truth) = disc_scene(120, 90, 60.0, 45.0, 22.0, 8);
diff --git a/crates/engine/src/cutout_cmds.rs b/crates/engine/src/cutout_cmds.rs
index baee260be..d5cc73466 100644
--- a/crates/engine/src/cutout_cmds.rs
+++ b/crates/engine/src/cutout_cmds.rs
@@ -45,8 +45,12 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
s,
"Remove Background",
move |doc, _, ctx| {
- ctx.progress(0.1, "Finding subject");
- let found = with_doc_sampler(doc, Some(id), sample_all, |smp, d| subject::select_subject(smp, d.bounds()));
+ // Cancel reaches the min cuts inside Select Subject, so Esc doesn't wait for them.
+ let found = ctx
+ .stage(0.1, 0.6, "Finding subject", |ctl| {
+ with_doc_sampler(doc, Some(id), sample_all, |smp, d| subject::select_subject_with(smp, d.bounds(), ctl))
+ })
+ .map_err(|_| EngineError::Cancelled)?;
let mut region = found.ok_or_else(|| EngineError::Other("no subject found".into()))?;
if ctx.cancelled() {
return Err(EngineError::Cancelled);
@@ -200,6 +204,24 @@ mod tests {
assert!(l.mask.is_some());
}
+ #[test]
+ fn remove_background_cancelled_while_finding_the_subject_changes_nothing() {
+ let (mut s, _) = disc(8);
+ let id = active_id(&s);
+ let before = s.active().unwrap().revision;
+ // The job's cancel reaches Select Subject, which stops at its first check.
+ let ctx = crate::jobs::JobCtx::new();
+ ctx.cancel();
+ s.set_inline_job_ctx(Some(ctx.clone()));
+ assert!(matches!(s.execute(CMD, json!({})), Err(EngineError::Cancelled)));
+ assert_eq!(ctx.message(), "Finding subject");
+ assert_eq!(s.active().unwrap().revision, before);
+ assert!(layer(&s, id).mask.is_none());
+ s.set_inline_job_ctx(None);
+ s.execute(CMD, json!({})).unwrap();
+ assert!(layer(&s, id).mask.is_some());
+ }
+
#[test]
fn remove_background_without_a_subject_leaves_the_document() {
let mut s = session_with(32, 32, 8, |_, _| [0.5, 0.5, 0.5]);