From c7d9ade95b71db8e1433fe2d088ec015bfd0486a Mon Sep 17 00:00:00 2001 From: Diego Chagas Date: Thu, 15 Oct 2026 01:40:46 -0300 Subject: [PATCH] Select Subject: keep subject parts coloured like the backdrop, leave enclosed gaps open (#4462) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Raw: measure the Nikon D90 image area (4288x2848 at (10, 10)) Aligning the decoded D90 sensor plane with the camera's own JPEG puts the image at (10, 10) in the 4352x2868 sensor plane, giving the camera's 4288x2848 frame (10-pixel margins; the right border reads the camera's flat 255 from column 4310). Add the measured ImageArea so a D90 NEF opens on the camera's frame instead of the uncropped plane, and make a measured profile leave a file that carries its own colour calibration (a DNG) untouched. * Codecs: open Cineon (.cin) film frames read-only Cineon is the 10-bit logarithmic film-scan format DPX grew from. Read it from the same Kodak header family: the generic header (big-endian, orientation at 192, channel count at 193, the channel-1 bits/dimensions), one or three channels, three 10-bit samples packed into each 32-bit word on a word boundary. The 10-bit code values open as U16 (round(c x 65535 / 1023)); the file's log black/white points are a display choice and are not applied. A depth other than 10 bits or a channel count other than 1/3 is Unsupported; truncation errors rather than panicking. Read-only (no Cineon writer), so .cin joins the open filters and Cineon read closes part of #1049's G10 gap. * PSD: write tiff blocks without copies, inflate merged ZIP once - ImageSourceData::to_bytes writes the global mask and global blocks straight from the model with 4-byte alignment instead of cloning each block (data included) to set its padding. Same bytes. - The tiff transcoder's nested regions and blocks write into the parent's buffer (taken and handed back, error or not) instead of building their own output and copying it up per nesting level. Bodies that fail or are not transcoded are truncated before being copied as stored or dropped. Same bytes. - PsdFile::from_bytes_and_merged decodes the merged image with the parse when asked: a ZIP stream is inflated once (the decode's stream check is the parse's); the parse-only check runs only when the decode fails, to keep from_bytes' errors. PSD import uses it with merged_needed. - PsdBuilder::composite documents that Gray/CMYK composites stay straight. Co-Authored-By: Claude Opus 5.5 * Content-Aware Fill: measure a thin hole by its thickness, not its bounds (#1366) Removing long, thin objects (coiled guitar strings, wires) left their outline as darker and lighter blotches and copied pieces of other strings into the fill. The pyramid shrank until the hole's bounding box was four patches across: for a string across the image that is a level where the hole has swallowed its surroundings, so the matches found there copy whatever looks like the blur, and the finer levels (refine-only for wide bounds) keep them. A hole at most a quarter as thick as its bounds are long now counts as thin: the pyramid stops while it is still about two patches thick, and that level starts from a membrane across it (over a few pixels, the surroundings themselves) instead of the onion peel, whose exhaustive search is what made a shallow pyramid unaffordable. Compact holes are unchanged bit for bit. Refs #1366 * Content-Aware Fill: every part of a thin selection keeps its surroundings (#1366) Two more causes of ghosts when removing strings and the small knobs selected with them: * Auto sampling summarises the selection's surroundings by a few clusters. Around a long selection those come from the strings' surroundings, so a small part elsewhere (a tuning knob in a differently coloured corner) lost its own surroundings and was filled from far away in another colour. Around a thin selection the Auto area now always reaches as far as the selection is thick. * The membrane that starts a thin hole now starts a patch radius out, past the anti-aliased fringe or halo that a selection drawn close to the object leaves outside it. Refs #1366 * Content-Aware Fill: peel a thin hole where that stays affordable (#1366) Starting every thin hole from a membrane smoothed Spot Healing on film grain (spot_healing_keeps_film_grain_through_overlapping_strokes: grain 9.0 against 12.1 around). The onion peel copies the grain; it was only given up because its exhaustive search is too slow on the big level a long thin hole stops at. It now starts the thin hole whenever hole cells times sources stay within 2^28 comparisons, and the membrane only beyond. Refs #1366 * Select Subject: keep subject parts coloured like the backdrop, leave enclosed gaps open Users on #2788 reported Select Subject dropping clothes that are close in colour to a plain wall and bridging the gap between an arm and the torso. Both come from the same place: the saliency pass labels low-contrast parts of the subject as background, the background colour model then learns them and explains them away, and the final blind hole fill closes every enclosed gap up to 5 % of the mask. Two changes in crates/algo: - A second GrabCut pass whose background model only knows the backdrop. A colour model fitted to the image frame (minus a margin around the salient blob, in case the subject runs out of the picture) marks every pixel it explains as probable background; the blob and whatever the backdrop cannot account for start as probable foreground. Only components that touch the first pass's result survive. - Hole filling that consults the colour models: specks (<= 0.2 % of the mask) always fill, larger holes up to 5 % fill only when their pixels fit the foreground model better than the background's. Tests: two regressions (a cream-shouldered figure on a near-white wall keeps its shoulders; a ring keeps its backdrop-coloured hole open), plus ignored timing and picture-dump helpers. The 6 MP first run goes from about 100 ms to about 200 ms on one core; the P29 repeat path is untouched. * Keyboard shortcut sets: Set menu, New Set, Save, Delete, .kys Export and Summarize (K2) Edit › Keyboard Shortcuts gets Photoshop's set management. A set is a saved copy of the bindings (Preferences.shortcutSets, the one in use in shortcutSet; "" is PhotoCraft Defaults), and the Set menu shows "(modified)" when the bindings differ from it. New Set…, Save and Delete wait for OK like the rest of the dialog. Export… writes the dialog's bindings as a .kys file (commands then tools, Photoshop's macOS key spelling), each row carrying our id as pc-id so PhotoCraft imports its own sets back exactly, whatever the label; Summarize… writes Photoshop's HTML list of every bound command by menu. edit.keyboardShortcuts takes useSet (before the call's edits), saveSet, deleteSet, sets and activeSet (after them), exportKys and summarize; every reply reports the sets, the set in use and whether it is modified. Bad names, keys or counts are errors that change nothing. * .kys import: tool keys and sets saved on Windows (K3) Photoshop's rows now import: each matches our tool by name (our tool names are Photoshop's) or by pc-id in sets PhotoCraft exported, and a letter other than the tool's own becomes its override, while its own letter keeps the tool cycling with the others (#5036). A set saved on Windows spells the primary modifier Ctrl where a Mac set writes Cmd and keeps Control for the Control key. A set with no Cmd or Opt anywhere but some Ctrl is read as a Windows set, its Ctrl as our Cmd: Ctrl+L is the Cmd+L default, not a Control-key override that would also mean Control on a Mac. The import reports `windows`. * cargo fmt the extension lists Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Vikram Bhaskaran Co-authored-by: vangel76 Co-authored-by: Claude Opus 5.5 Co-authored-by: Gert Pellin Co-authored-by: Brandon Thomas Co-authored-by: Tanish Manku --- crates/algo/src/segment/mod.rs | 45 +++++++++ crates/algo/src/segment/subject.rs | 68 ++++++++++++- crates/algo/src/segment/tests.rs | 151 +++++++++++++++++++++++++++++ 3 files changed, 261 insertions(+), 3 deletions(-) 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()); +}