diff --git a/crates/algo/src/segment/mod.rs b/crates/algo/src/segment/mod.rs index 5c190e643a..b30ce909b7 100644 --- a/crates/algo/src/segment/mod.rs +++ b/crates/algo/src/segment/mod.rs @@ -448,6 +448,51 @@ pub fn clean_mask(mask: &[bool], w: usize, h: usize, frac: f32, hole_frac: f32) out } +/// Fills the holes of `mask` (4-connected background areas not touching the border) by what +/// they look like: a hole up to `speck_frac` of the mask's area always fills; a larger one, up +/// to `hole_frac`, only when its pixels fit the foreground model `fg` better than `bg` on +/// average, so an enclosed patch of backdrop stays open. +pub fn fill_holes_by_model(mask: &[bool], img: &RgbImage, fg: &Gmm, bg: &Gmm, speck_frac: f32, hole_frac: f32) -> Vec { + let (w, h) = (img.w, img.h); + let mut out = mask.to_vec(); + let area = out.iter().filter(|v| **v).count(); + let max_speck = (area as f32 * speck_frac) as usize; + let max_hole = (area as f32 * hole_frac) as usize; + let inv: Vec = out.iter().map(|v| !v).collect(); + let (hl, hs) = components4(&inv, w, h); + let mut touches = vec![false; hs.len()]; + for x in 0..w { + touches[hl[x] as usize] = true; + touches[hl[(h - 1) * w + x] as usize] = true; + } + for y in 0..h { + touches[hl[y * w] as usize] = true; + touches[hl[y * w + w - 1] as usize] = true; + } + // Summed data costs per hole; only holes small enough to be candidates are evaluated. + let mut cost = vec![(0.0f64, 0.0f64); hs.len()]; + for (i, l) in hl.iter().enumerate() { + let l = *l as usize; + if l == 0 || touches[l] || hs[l] > max_hole || hs[l] <= max_speck { + continue; + } + if let Some(p) = img.px.get(i) { + cost[l].0 += f64::from(fg.neg_log(*p)); + cost[l].1 += f64::from(bg.neg_log(*p)); + } + } + for (o, l) in out.iter_mut().zip(&hl) { + let l = *l as usize; + if l == 0 || touches[l] || hs[l] > max_hole { + continue; + } + if hs[l] <= max_speck || cost[l].0 <= cost[l].1 { + *o = true; + } + } + out +} + fn components4(mask: &[bool], w: usize, h: usize) -> (Vec, Vec) { let mut lab = vec![0u32; w * h]; let mut sizes = vec![0usize]; diff --git a/crates/algo/src/segment/subject.rs b/crates/algo/src/segment/subject.rs index b117bb5ef6..75a1a47a56 100644 --- a/crates/algo/src/segment/subject.rs +++ b/crates/algo/src/segment/subject.rs @@ -13,8 +13,17 @@ //! S. Süsstrunk, "Frequency-tuned Salient Region Detection", CVPR 2009): distance of the //! lightly blurred CIELAB image from its mean colour. //! 4. Otsu's threshold on the saliency map seeds a GrabCut trimap (low-saliency border pixels -//! are definite background); the result is cleaned (small islands dropped, small holes -//! filled) and re-cut at full resolution. +//! are definite background); the result is cleaned (small islands dropped). +//! 5. A second GrabCut whose background model only knows the backdrop: a colour model fitted +//! to the image's frame marks every pixel it explains as probable background, and the rest +//! (the blob, plus whatever the backdrop cannot account for) starts as probable foreground. +//! Parts of the subject whose colour is close to the backdrop (a cream shirt on a near-white +//! wall) have low saliency and in step 4 land in the background model, which then explains +//! them away; here they start as foreground and the cut keeps them (#2788). Only what +//! touches the first pass's result survives, so the pass cannot pull in unrelated things. +//! 6. Holes are filled only when their colour fits the foreground model better than the +//! background's, so a patch of backdrop enclosed by the subject (between an arm and the +//! torso) stays open; specks still fill. Then the mask is re-cut at full resolution. //! //! Works well for a distinct object on a comparatively plain background; it is not a semantic //! segmenter. @@ -25,6 +34,7 @@ use std::collections::BinaryHeap; use photocraft_geom::Rect; use photocraft_raster::{Cancelled, Interrupt}; +use super::gmm::Gmm; use super::grabcut::{self, BG, PR_BG, PR_FG}; use super::slic::{rgb_to_lab, slic_lab}; use super::{Region, Sampler}; @@ -72,13 +82,65 @@ pub fn select_subject_with(sampler: &dyn Sampler, canvas: Rect, ctl: &Interrupt) } let Some((fg, bg)) = grabcut::grabcut_with(&img, &mut trimap, 6, ctl)? else { return Ok(None) }; let low: Vec = trimap.iter().map(|v| *v == PR_FG || *v == grabcut::FG).collect(); - let low = super::clean_mask(&low, w, h, 0.2, 0.05); + let low = super::clean_mask(&low, w, h, 0.2, 0.0); if !low.iter().any(|v| *v) { return Ok(None); } + let (low, fg, bg) = backdrop_pass(&img, &low, ctl)?.unwrap_or((low, fg, bg)); + ctl.check()?; + let low = super::fill_holes_by_model(&low, &img, &fg, &bg, 0.002, 0.05); super::finish_region_with(sampler, canvas, step, &low, w, h, Some((&fg, &bg)), ctl) } +/// Step 5: GrabCut again with a background model that only knows the backdrop. A colour model +/// is fitted to the image's frame (the outer pixels, minus a margin around `blob` in case the +/// subject runs out of the picture); the frame is definite background, every other pixel it +/// explains well is probable background, and the rest (the blob, and anything the backdrop +/// cannot account for, such as a cream shirt on a near-white wall) starts as probable +/// foreground. `Ok(None)` when the frame cannot be modelled or the cut keeps nothing that +/// touches the blob; `Err(Cancelled)` once `ctl` is cancelled, as in the first pass. +fn backdrop_pass(img: &super::RgbImage, blob: &[bool], ctl: &Interrupt) -> Result, Gmm, Gmm)>, Cancelled> { + let (w, h) = (img.w, img.h); + let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0usize, 0usize); + for (i, on) in blob.iter().enumerate() { + if *on { + let (x, y) = (i % w, i / w); + (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y)); + } + } + if x1 < x0 || y1 < y0 { + return Ok(None); + } + let margin = (((x1 - x0 + 1).max(y1 - y0 + 1) as f32 * 0.15).ceil() as usize).max(4); + let (bx0, by0) = (x0.saturating_sub(margin), y0.saturating_sub(margin)); + let (bx1, by1) = ((x1 + margin).min(w - 1), (y1 + margin).min(h - 1)); + let frame = ((w.min(h) as f32 * 0.06).round() as usize).max(2); + let in_frame = |x: usize, y: usize| x < frame || y < frame || x + frame >= w || y + frame >= h; + let near_blob = |x: usize, y: usize| (bx0..=bx1).contains(&x) && (by0..=by1).contains(&y); + let samples: Vec<[f32; 3]> = (0..w * h).filter(|i| in_frame(i % w, i / w) && !near_blob(i % w, i / w)).map(|i| img.px[i]).collect(); + let Some(backdrop) = Gmm::fit(&super::subsample(&samples, 40_000), grabcut::K, super::gmm::DEFAULT_REG) else { return Ok(None) }; + // What the frame itself costs under its own model bounds "explained well". + let mut frame_costs: Vec = samples.iter().map(|p| backdrop.neg_log(*p)).collect(); + frame_costs.sort_by(|a, b| a.total_cmp(b)); + let Some(limit) = frame_costs.get(frame_costs.len() * 99 / 100).map(|c| c + 4.0) else { return Ok(None) }; + let mut trimap: Vec = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + if in_frame(x, y) && !near_blob(x, y) { + BG + } else if blob[i] || backdrop.neg_log(img.px[i]) > limit { + PR_FG + } else { + PR_BG + } + }) + .collect(); + let Some((fg, bg)) = grabcut::grabcut_with(img, &mut trimap, 4, ctl)? else { return Ok(None) }; + let cut: Vec = trimap.iter().map(|v| *v == PR_FG || *v == grabcut::FG).collect(); + let low = super::keep_seeded(&cut, blob, w, h); + Ok(low.iter().any(|v| *v).then_some((low, fg, bg))) +} + /// Per-pixel saliency in `0..=1` (see the module docs). pub fn saliency(img: &super::RgbImage) -> Vec { let (w, h) = (img.w, img.h); diff --git a/crates/algo/src/segment/tests.rs b/crates/algo/src/segment/tests.rs index 55ddc6cafd..743c3dc460 100644 --- a/crates/algo/src/segment/tests.rs +++ b/crates/algo/src/segment/tests.rs @@ -761,3 +761,154 @@ fn object_at_on_the_background_or_off_canvas_finds_nothing() { assert!(grabcut::object_at(&s, canvas, f32::NAN, 10.0, 20_000).is_none()); assert!(grabcut::object_at(&s, canvas, 400.0, 10.0, 0).is_none()); } + +// ---------- Select Subject on the cases reported in #2788 ---------- + +/// A figure whose upper part is close to the background colour (a cream shirt on a near-white +/// backdrop): the whole figure is the subject. Returns (image, truth, the low-contrast part). +pub(crate) fn low_contrast_figure(seed: u64) -> (RgbImage, Vec, Vec) { + let (w, h) = (240usize, 200usize); + let mut rng = Rng::new(seed); + let mut img = RgbImage::new(w, h); + let mut truth = vec![false; w * h]; + let mut cream = vec![false; w * h]; + for y in 0..h { + for x in 0..w { + let body = (90..150).contains(&x) && (70..190).contains(&y); + let shoulders = (80..160).contains(&x) && (40..70).contains(&y); + let print = (105..135).contains(&x) && (100..130).contains(&y); + let n = 0.012 * rng.normal(); + let i = y * w + x; + truth[i] = body || shoulders; + cream[i] = shoulders; + img.px[i] = if print { + [0.9 + n, 0.15 + n, 0.1 + n] + } else if body { + [0.12 + n, 0.2 + n, 0.45 + n] + } else if shoulders { + // Cream, a few levels off the backdrop. + [0.90 + n, 0.88 + n, 0.80 + n] + } else { + [0.96 + n, 0.96 + n, 0.95 + n] + } + .map(|v| v.clamp(0.0, 1.0)); + } + } + (img, truth, cream) +} + +fn coverage(region: &Region, part: &[bool], w: usize, h: usize) -> f32 { + let (mut hit, mut n) = (0usize, 0usize); + for y in 0..h { + for x in 0..w { + if part[y * w + x] { + n += 1; + hit += (region.at(x as i32, y as i32) >= 0.5) as usize; + } + } + } + hit as f32 / n.max(1) as f32 +} + +#[test] +fn select_subject_keeps_parts_close_to_the_background_colour() { + let (img, truth, cream) = low_contrast_figure(7); + let s = ImageSampler { img: &img, origin: (0, 0) }; + let reg = subject::select_subject(&s, Rect::new(0, 0, 240, 200)).unwrap(); + let v = iou(®, &truth, 240, 200); + let c = coverage(®, &cream, 240, 200); + assert!(c > 0.85, "the cream shoulders are part of the subject: covered {c}"); + assert!(v > 0.9, "IoU {v}"); +} + +#[test] +fn select_subject_leaves_a_background_coloured_gap_open() { + // A dark ring (arms on hips) around a patch of plain backdrop: the patch is not the subject. + let (w, h) = (220usize, 200usize); + let mut rng = Rng::new(11); + let mut img = RgbImage::new(w, h); + let mut truth = vec![false; w * h]; + let mut gap = vec![false; w * h]; + for y in 0..h { + for x in 0..w { + let d = (x as f32 - 110.0).hypot(y as f32 - 100.0); + let ring = (17.0..80.0).contains(&d); + let hole = d < 17.0; + let n = 0.012 * rng.normal(); + let i = y * w + x; + truth[i] = ring; + gap[i] = hole; + img.px[i] = if ring { [0.2 + n, 0.15 + n, 0.35 + n] } else { [0.95 + n, 0.94 + n, 0.92 + n] }.map(|v| v.clamp(0.0, 1.0)); + } + } + let s = ImageSampler { img: &img, origin: (0, 0) }; + let reg = subject::select_subject(&s, Rect::new(0, 0, w as i32, h as i32)).unwrap(); + let g = coverage(®, &gap, w, h); + assert!(g < 0.1, "the backdrop inside the ring stays unselected: covered {g}"); + let v = iou(®, &truth, w, h); + assert!(v > 0.9, "IoU {v}"); +} + +/// Timing on a 6 MP figure, for before/after numbers (`cargo test --release -- --ignored select_subject_timing --nocapture`). +#[test] +#[ignore = "timing only"] +fn select_subject_timing() { + let (w, h) = (3000usize, 2000usize); + let img = RgbImage::from_fn(w, h, |x, y| { + let body = (1100..1900).contains(&x) && (700..1900).contains(&y); + let shoulders = (1000..2000).contains(&x) && (400..700).contains(&y); + let t = ((x * 7 + y * 13) % 17) as f32 / 1700.0; + if body { + [0.12 + t, 0.2, 0.45] + } else if shoulders { + [0.90, 0.88 + t, 0.80] + } else { + [0.96, 0.96 + t, 0.95] + } + }); + let s = ImageSampler { img: &img, origin: (0, 0) }; + for _ in 0..2 { + let t0 = std::time::Instant::now(); + let reg = subject::select_subject(&s, Rect::new(0, 0, w as i32, h as i32)).unwrap(); + eprintln!("select_subject 6 MP: {:?} bbox {:?}", t0.elapsed(), reg.bbox); + } +} + +/// Writes the #2788 scenes and the Select Subject mask over them as PPM files into +/// `$SUBJECT_DUMP` (for the PR's before/after pictures). +#[test] +#[ignore = "writes pictures"] +fn select_subject_dump_pictures() { + let Ok(dir) = std::env::var("SUBJECT_DUMP") else { return }; + let write = |name: &str, img: &RgbImage, reg: Option<&Region>| { + let mut out = format!("P6\n{} {}\n255\n", img.w, img.h).into_bytes(); + for y in 0..img.h { + for x in 0..img.w { + let mut c = img.at(x, y); + if let Some(r) = reg + && r.at(x as i32, y as i32) >= 0.5 + { + c = [c[0] * 0.5 + 0.5, c[1] * 0.5, c[2] * 0.5 + 0.5]; + } + out.extend(c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)); + } + } + std::fs::write(format!("{dir}/{name}.ppm"), out).unwrap(); + }; + let (img, _, _) = low_contrast_figure(7); + let s = ImageSampler { img: &img, origin: (0, 0) }; + let reg = subject::select_subject(&s, Rect::new(0, 0, 240, 200)); + write("figure", &img, None); + write("figure-selected", &img, reg.as_ref()); + let (w, h) = (220usize, 200usize); + let mut rng = Rng::new(11); + let img = RgbImage::from_fn(w, h, |x, y| { + let d = (x as f32 - 110.0).hypot(y as f32 - 100.0); + let n = 0.012 * rng.normal(); + if (17.0..80.0).contains(&d) { [0.2 + n, 0.15 + n, 0.35 + n] } else { [0.95 + n, 0.94 + n, 0.92 + n] }.map(|v| v.clamp(0.0, 1.0)) + }); + let s = ImageSampler { img: &img, origin: (0, 0) }; + let reg = subject::select_subject(&s, Rect::new(0, 0, w as i32, h as i32)); + write("ring", &img, None); + write("ring-selected", &img, reg.as_ref()); +}