From 1ebc72122f6d5658fc6228f377d6fdf4bb2ff604 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:09:33 +0100 Subject: [PATCH] Auto-Align Vignette Removal: fit CMYK light, keep the reference in one frame (#14197) - The estimate read CMYK samples as they are stored, as ink, which grows towards darkened corners, so it fitted ink growth and then brightened the light. It now reads the red, green and blue light the inks let through. The correction brightens the light of C, M and Y only: K's light multiplies theirs, so brightening it too would brighten twice. - With Geometric Distortion fitting a nonzero k1, the reference's placement carries that k1 but its pixels stay as they are. The estimate now reads the reference warped by its placement, as it reads the layers that moved, and its correction measures radii with k1 = 0, in its own pixels. New test: shifted_vignetted_cmyk_layers_come_out_flatter_with_their_corners_brightened. --- crates/engine-core/src/cmd/photo_cmds.rs | 14 +++-- crates/engine-vector/src/cmd/align_cmds.rs | 14 ++++- .../align_cmds/auto_align_vignette_tests.rs | 59 +++++++++++++++---- 3 files changed, 70 insertions(+), 17 deletions(-) diff --git a/crates/engine-core/src/cmd/photo_cmds.rs b/crates/engine-core/src/cmd/photo_cmds.rs index b8745ba258..d231d0dbca 100644 --- a/crates/engine-core/src/cmd/photo_cmds.rs +++ b/crates/engine-core/src/cmd/photo_cmds.rs @@ -662,10 +662,12 @@ fn scale_sample(v: f32, f: f32, fmt: PixelFormat) -> f32 { /// [`panorama::photometric`] samples about 40 000 points of the overlaps anyway. const VIGNETTE_SIDE: usize = 1024; -/// The colour channels and coverage of `surf`'s content, box-averaged over `k × k` pixels on a grid aligned to the origin. +/// The light in `surf`'s colour channels and its coverage, box-averaged over `k × k` pixels on a grid aligned to the +/// origin. CMYK reads as the red, green and blue light its inks let through, since the estimate fits light, not ink. fn roi_downsampled(surf: &Surface, k: usize) -> Result { let fmt = surf.format(); - let (n, cc) = (fmt.channels(), fmt.mode.color_channels()); + let cmyk = fmt.mode == ColorMode::Cmyk; + let (n, cc) = (fmt.channels(), if cmyk { 3 } else { fmt.mode.color_channels() }); let b = surf.content_bounds(); if b.is_empty() { return Ok(RoiImage { x0: 0, y0: 0, w: 0, h: 0, ch: cc, px: Vec::new(), alpha: Vec::new() }); @@ -689,7 +691,8 @@ fn roi_downsampled(surf: &Surface, k: usize) -> Result { let a = if fmt.alpha { q[n - 1] } else { 1.0 }; alpha[cell] += a; for c in 0..cc { - px[cell * cc + c] += q[c] * a; + let light = if cmyk { (1.0 - q[c]) * (1.0 - q[3]) } else { q[c] }; + px[cell * cc + c] += light * a; } } } @@ -723,7 +726,8 @@ pub fn estimate_vignette(layers: &[(&Surface, &Placement)], size: (usize, usize) } /// `surf`, warped into canvas coordinates by `pl` from a `size` frame, with the falloff `vignette` -/// ([`estimate_vignette`]) divided out of its colour channels. +/// ([`estimate_vignette`]) divided out of its colour channels. CMYK brightens the light of C, M and Y; K's light +/// multiplies theirs, so brightening it as well would brighten twice. pub fn remove_vignette(surf: &Surface, pl: &Placement, size: (usize, usize), vignette: [f64; 2]) -> Surface { let fmt = surf.format(); let (n, cc) = (fmt.channels(), fmt.mode.color_channels()); @@ -736,7 +740,7 @@ pub fn remove_vignette(surf: &Surface, pl: &Placement, size: (usize, usize), vig surf.read_region_into(line, &mut row); for (x, q) in (b.x0..).zip(row.chunks_exact_mut(n)) { let f = photo.factor(0, 0, source_r2(pl, size, x as f64 + 0.5, y as f64 + 0.5)); - for v in &mut q[..cc] { + for v in &mut q[..if fmt.mode == ColorMode::Cmyk { 3 } else { cc }] { *v = scale_sample(*v, f, fmt); } } diff --git a/crates/engine-vector/src/cmd/align_cmds.rs b/crates/engine-vector/src/cmd/align_cmds.rs index 1c3ce12df3..3e1b39879d 100644 --- a/crates/engine-vector/src/cmd/align_cmds.rs +++ b/crates/engine-vector/src/cmd/align_cmds.rs @@ -167,8 +167,18 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { let mut reference_px = None; let mut warnings: Vec = Vec::new(); if vignette { + // The reference keeps its own pixels, but its placement carries the lens distortion `k1` that Geometric + // Distortion may fit: the estimate reads it warped by that placement, as it reads the layers that moved, and its + // correction measures radii in its own pixels, with no distortion. + let still_warped = match still { + Some((i, pl)) if pl.k1 != 0.0 => { + let b = surfs[i].content_bounds(); + Some(if b.is_empty() { surfs[i].clone() } else { warp_placed(surfs[i], b, (0.0, 0.0), pl, (0.0, 0.0), interp)? }) + } + _ => None, + }; let mut layers: Vec<(&Surface, &Placement)> = warped.iter().zip(&moves).filter_map(|((_, px, _), &i)| Some((px, al.placements[i].as_ref()?))).collect(); - layers.extend(still.map(|(i, pl)| (surfs[i], pl))); + layers.extend(still.map(|(i, pl)| (still_warped.as_ref().unwrap_or(surfs[i]), pl))); let v = estimate_vignette(&layers, size)?; if negligible(v) { warnings.push(NO_VIGNETTE.to_owned()); @@ -184,7 +194,7 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { warnings .push(format!("Vignette Removal left the locked reference layer \"{}\" as it was", doc.layer(ids[i]).map_or("", |l| l.name.as_str()))); } else { - reference_px = Some((ids[i], remove_vignette(surfs[i], pl, size, v))); + reference_px = Some((ids[i], remove_vignette(surfs[i], &Placement { k1: 0.0, ..pl.clone() }, size, v))); } } } diff --git a/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs b/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs index a3e845b6a7..5fed7bd397 100644 --- a/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs +++ b/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs @@ -1,6 +1,8 @@ //! Auto-Align's Vignette Removal (#14197): one falloff estimated from the layers' overlaps, as Photomerge does, and //! divided out of every aligned layer; off, and under Collage or Reposition, the layers come out as before. +use photocraft_color::{ColorMode, PixelFormat}; + use super::*; const W: i32 = 400; @@ -29,21 +31,31 @@ fn scene() -> Vec<[f32; 3]> { px } +/// The CMYK test layers' black ink, everywhere. +const BLACK_INK: f32 = 0.1; + /// A canvas-sized layer: the scene seen from (`ox`, `oy`), darkened towards the corners by `exp(falloff · r²)` -/// (r = 1 at a corner), as a lens does. +/// (r = 1 at a corner), as a lens does. In CMYK the scene's light is printed in C, M and Y over [`BLACK_INK`]. fn photo_layer(s: &mut Session, name: &str, ox: i32, oy: i32, falloff: f32) -> LayerId { let px = scene(); s.execute("layer.new.layer", json!({"name": name})).unwrap(); let id = s.active().unwrap().active_layer.unwrap(); s.edit("photo", |doc, _| { let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); - let mut row = vec![0.0f32; W as usize * 4]; + let fmt = surf.format(); + let n = fmt.channels(); + let mut row = vec![0.0f32; W as usize * n]; for y in 0..H { for x in 0..W { let (dx, dy) = (x as f32 + 0.5 - W as f32 / 2.0, y as f32 + 0.5 - H as f32 / 2.0); let v = (falloff * (dx * dx + dy * dy) / ((W * W + H * H) as f32 / 4.0)).exp(); let c = px[((y + oy) * (W + 120) + x + ox) as usize]; - row[x as usize * 4..x as usize * 4 + 4].copy_from_slice(&[c[0] * v, c[1] * v, c[2] * v, 1.0]); + let q = &mut row[x as usize * n..(x as usize + 1) * n]; + if fmt.mode == ColorMode::Cmyk { + q.copy_from_slice(&[1.0 - c[0] * v, 1.0 - c[1] * v, 1.0 - c[2] * v, BLACK_INK, 1.0]); + } else { + q.copy_from_slice(&[c[0] * v, c[1] * v, c[2] * v, 1.0]); + } } surf.write_region(Rect::new(0, y, W, y + 1), &row); } @@ -53,10 +65,15 @@ fn photo_layer(s: &mut Session, name: &str, ox: i32, oy: i32, falloff: f32) -> L id } -/// Two vignetted photos of one scene, 60 x 40 px apart, both selected. +/// Two vignetted photos of one scene, `shift` apart, both selected. fn pair(falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) { + pair_in("rgb", falloff, shift) +} + +/// [`pair`] in a document of colour mode `mode`. +fn pair_in(mode: &str, falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) { let mut s = crate::session(); - s.execute("file.new", json!({"width": W, "height": H, "background": "transparent"})).unwrap(); + s.execute("file.new", json!({"width": W, "height": H, "mode": mode, "background": "transparent"})).unwrap(); let a = photo_layer(&mut s, "A", 0, 0, falloff); let b = photo_layer(&mut s, "B", shift.0, shift.1, falloff); s.execute("layer.select", json!({"layer": a.0})).unwrap(); @@ -68,14 +85,24 @@ fn pixels(s: &Session, id: LayerId) -> Vec { s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().read_region(Rect::new(-200, -200, W + 200, H + 200)) } +/// The red, green and blue light of pixel `q` summed: what CMYK's inks let through. +fn light(mode: ColorMode, q: &[f32]) -> f32 { + if mode == ColorMode::Cmyk { q[..3].iter().map(|c| (1.0 - c) * (1.0 - q[3])).sum() } else { q[..3].iter().sum() } +} + +fn format(s: &Session) -> PixelFormat { + s.active().unwrap().doc.pixel_format() +} + /// How far apart the two aligned layers are where both are opaque: the mean |log| of their luminance ratio. The scene is /// the same in both, so what's left is each one's vignetting at a different place in the frame. fn mismatch(s: &Session, [a, b]: [LayerId; 2]) -> f64 { let (pa, pb) = (pixels(s, a), pixels(s, b)); + let (mode, ch) = (format(s).mode, format(s).channels()); let (mut sum, mut n) = (0.0, 0usize); - for (qa, qb) in pa.as_chunks::<4>().0.iter().zip(pb.as_chunks::<4>().0) { - if qa[3] > 0.999 && qb[3] > 0.999 { - let (la, lb) = (qa[..3].iter().sum::(), qb[..3].iter().sum::()); + for (qa, qb) in pa.chunks_exact(ch).zip(pb.chunks_exact(ch)) { + if qa[ch - 1] > 0.999 && qb[ch - 1] > 0.999 { + let (la, lb) = (light(mode, qa), light(mode, qb)); sum += f64::from((la / lb).ln().abs()); n += 1; } @@ -88,9 +115,10 @@ fn mismatch(s: &Session, [a, b]: [LayerId; 2]) -> f64 { fn corners(s: &Session, id: LayerId) -> f32 { let surf = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap(); let b = surf.content_bounds(); + let (mode, ch) = (format(s).mode, format(s).channels()); let mut sum = 0.0; for (x, y) in [(b.x0 + 4, b.y0 + 4), (b.x1 - 34, b.y0 + 4), (b.x0 + 4, b.y1 - 34), (b.x1 - 34, b.y1 - 34)] { - sum += surf.read_region(Rect::new(x, y, x + 30, y + 30)).as_chunks::<4>().0.iter().map(|q| q[..3].iter().sum::()).sum::(); + sum += surf.read_region(Rect::new(x, y, x + 30, y + 30)).chunks_exact(ch).map(|q| light(mode, q)).sum::(); } sum / (4.0 * 900.0 * 3.0) } @@ -103,7 +131,18 @@ fn align(s: &mut Session, params: Value) -> Value { #[test] fn shifted_vignetted_layers_come_out_flatter_with_their_corners_brightened() { - let (mut s, ids) = pair(-0.5, (60, 40)); + shifted_layers_come_out_flatter("rgb"); +} + +/// CMYK samples are ink, which grows towards darkened corners: the falloff is fitted to their light, and the light of +/// C, M and Y is brightened once, not again through K's. +#[test] +fn shifted_vignetted_cmyk_layers_come_out_flatter_with_their_corners_brightened() { + shifted_layers_come_out_flatter("cmyk"); +} + +fn shifted_layers_come_out_flatter(mode: &str) { + let (mut s, ids) = pair_in(mode, -0.5, (60, 40)); let r = align(&mut s, json!({"projection": "auto"})); assert_eq!(r["vignette"], Value::Null, "off by default: {r}"); let (before, plain) = (mismatch(&s, ids), ids.map(|id| pixels(&s, id)));