LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
LR-MERGE-HDR: keep the reference's clipped highlights where other frames moved; deghost catches ghosts in dark skies
dev-null-undefineda142179f2028
diff --git a/crates/merge/src/hdr.rs b/crates/merge/src/hdr.rsindex 59aa5286c..95750ba0b 100644--- a/crates/merge/src/hdr.rs+++ b/crates/merge/src/hdr.rs@@ -12,9 +12,11 @@//! 4. **Weights.** `wᵢ = kᵢ · (1 − smoothstep(0.80·clip, 0.96·clip, max channel))`: longer//! exposures get more weight (shot-noise optimal for a linear sensor), saturated pixels none//! (all channels together, so a clipped channel never shifts colour). The darkest frame keeps a-//! tiny weight so fully saturated pixels still get a value.-//! 5. **Deghost** (None/Low/Medium/High): on a ≤ 1024 px version, a per-pixel consistency test-//! against the reference: the reference radiance (or, where the reference is clipped/too dark,+//! tiny weight so fully saturated pixels still get a value. Where the reference is at or near its clip, the scene is+//! at least that bright: a frame reading far darker there saw something that moved (a star, the moon, a light) and is+//! left out, so a clipped highlight of the reference is never replaced by content from another moment.+//! 5. **Deghost** (None/Low/Medium/High): on a ≤ 2048 px version, a per-pixel consistency test+//! against the reference: the reference radiance (or, where the reference is clipped or black,//! the nearest well-exposed frame's) predicts what each frame should have recorded; frames that//! disagree by more than a threshold (in log units, with a noise floor) are masked there. Masks//! are dilated and feathered (Gaussian), upsampled, and remove the frame's weight. Their union@@ -87,6 +89,10 @@ pub struct HdrResult {pub lens: Vec<lightcraft_raw::Opcode>,}+/// Long edge (at most) of the frames the deghost test compares: small moving things (a star at 200 mm) still span a few+/// pixels there.+const DEGHOST_EDGE: usize = 2048;+#[inline]fn smoothstep(a: f32, b: f32, x: f32) -> f32 {let t = ((x - a) / (b - a)).clamp(0.0, 1.0);@@ -161,15 +167,9 @@ pub fn merge_hdr(mut frames: Vec<Frame>, opts: &HdrOptions, progress: &Progress)alignments[i] = a;}check(progress, 0.35, "Resampling")?;- let warped: Vec<(usize, Rgb32f, Vec<bool>)> = (0..n)- .into_par_iter()- .filter(|&i| i != reference && alignments[i].model != "identity")- .map(|i| {- let (img, v) = align::warp(&frames[i].image, &alignments[i].h);- (i, img, v)- })- .collect();- for (i, img, v) in warped {+ // one frame at a time (the warp is parallel inside): each warped copy replaces its frame before the next is made+ for i in (0..n).filter(|&i| i != reference && alignments[i].model != "identity") {+ let (img, v) = align::warp(&frames[i].image, &alignments[i].h);frames[i].image = img;valid[i] = Some(v);}@@ -215,6 +215,9 @@ pub fn merge_hdr(mut frames: Vec<Frame>, opts: &HdrOptions, progress: &Progress)let i_px = y * w + x;let mut acc = [0f64; 3];let mut ws = 0f64;+ // the reference at or near its clip: the radiance is at least this+ let mr = maxc(fr[reference].image.data[i_px]);+ let bound = if mr >= 0.80 * clips[reference] { mr / k[reference] } else { 0.0 };for i in 0..n {if vd[i].as_ref().is_some_and(|v| !v[i_px]) {continue;@@ -227,6 +230,9 @@ pub fn merge_hdr(mut frames: Vec<Frame>, opts: &HdrOptions, progress: &Progress)}if i == reference {wt += 1e-9;+ } else if bound > 0.0 {+ // a frame far darker than that saw something that moved there+ wt *= smoothstep(0.35, 0.6, m / k[i] / bound);}if i != reference&& let Some((maps, fac)) = gs@@ -362,35 +368,40 @@ fn deghost_maps() -> (Vec<Plane>, usize) {let n = frames.len();let (w, h) = (frames[0].width(), frames[0].height());- let fac = w.max(h).div_ceil(1024).max(1);+ let fac = w.max(h).div_ceil(DEGHOST_EDGE).max(1);+ // the dilation/feather radius was chosen for a 1024 px map: keep it the same share of the picture+ let r = (r as f32 * (w.max(h) as f32 / fac as f32 / 1024.0).max(1.0)).round() as usize;let small: Vec<(Rgb32f, Vec<f32>)> = (0..n).into_par_iter().map(|i| shrink(&frames[i].image, valid[i].as_deref(), fac)).collect();let (sw, sh) = (small[0].0.width, small[0].0.height);let rpos = order.iter().position(|&i| i == reference).unwrap_or(0);- let good = |i: usize, p: usize| -> bool {+ // `dark`: the share of the clip below which a frame's (averaged) pixel is too noisy to predict from+ let good = |i: usize, p: usize, dark: f32| -> bool {let f = &frames[i];let m = maxc(small[i].0.data[p]);- let dark = if f.raw { 0.01 } else { 0.04 };small[i].1[p] > 0.99 && m < 0.8 * f.clip && m > dark * f.clip};+ let dark = |i: usize| if frames[i].raw { 0.01 } else { 0.04 };// predicted reference radiance per pixellet pred: Vec<[f32; 3]> = (0..sw * sh).into_par_iter().map(|p| {let rad = |i: usize| small[i].0.data[p].map(|v| v / k[i]);- if good(reference, p) {+ // the reference predicts down to a tenth of the other frames' floor (the map's averaging tames its noise): in a+ // dark sky the brighter frames must not predict themselves, or their ghosts would look consistent+ if good(reference, p, dark(reference) * 0.1) {return rad(reference);}let bright = maxc(small[reference].0.data[p]) >= 0.8 * frames[reference].clip;if bright {for q in (0..rpos).rev() {- if good(order[q], p) {+ if good(order[q], p, dark(order[q])) {return rad(order[q]);}}rad(order[0])} else {for &i in &order[rpos + 1..] {- if good(i, p) {+ if good(i, p, dark(i)) {return rad(i);}}diff --git a/crates/merge/tests/hdr.rs b/crates/merge/tests/hdr.rsindex 68b9ba4b9..7368e56a3 100644--- a/crates/merge/tests/hdr.rs+++ b/crates/merge/tests/hdr.rs@@ -161,3 +161,48 @@ fn deghost_removes_a_moving_object() {let mean = high.ghost.data.iter().sum::<f32>() / high.ghost.data.len() as f32;assert!(mean < 0.08, "the overlay is local (mean {mean})");}++/// A dark night sky (≈ 0.3 % of the reference's white) with a soft star of peak `peak` (Gaussian, σ = 3 px) at (cx, cy)+/// in truth coordinates.+fn night_with_star(cx: f32, cy: f32, peak: f32) -> Rgb32f {+ Rgb32f::from_fn(W + 2 * M, H + 2 * M, |x, y| {+ let sky = 0.003 * (1.0 + 0.3 * (x as f32 / (W + 2 * M) as f32));+ let d2 = (x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2);+ [sky + peak * (-d2 / 18.0).exp(); 3]+ })+}++/// Night brackets of a star that moves between the frames (the sky turns during a tripod bracket): its core clips in the+/// reference and in the brighter frame, not in the darkest one.+fn moving_star_frames(xs: [f32; 3]) -> Vec<Frame> {+ let ks = [0.0625f32, 1.0, 8.0];+ (0..3).map(|i| shoot(&night_with_star(xs[i], 210.0 + M as f32, 10.0), ks[i], 0.0, 0.0, 30 + i as u64)).collect()+}++#[test]+fn a_clipped_star_of_the_reference_is_not_erased_by_frames_where_it_moved() {+ let xs = [280.0 + M as f32, 320.0 + M as f32, 360.0 + M as f32];+ let r = merge_hdr(moving_star_frames(xs), &HdrOptions { align: false, deghost: Deghost::None }, &no_progress).unwrap();+ assert_eq!(r.reference, 1);+ // the reference saw the star clipped here, so the scene is at least that bright; the frames where the star had moved+ // read the dark sky there and must not replace it (which left a black hole in real night brackets)+ let core = r.radiance.get(320, 210);+ let m = core[0].max(core[1]).max(core[2]);+ assert!(m > 0.9, "the reference's clipped star core was erased: {core:?}");+}++#[test]+fn deghost_removes_a_bright_frames_ghost_in_a_dark_sky() {+ let xs = [280.0 + M as f32, 320.0 + M as f32, 360.0 + M as f32];+ let r = merge_hdr(moving_star_frames(xs), &HdrOptions { align: false, deghost: Deghost::High }, &no_progress).unwrap();+ // where only the brightest frame had the star, the sky is what the reference saw: no ring of its unclipped halo+ let mut worst = 0f32;+ for y in 196..224 {+ for x in 346..374 {+ let p = r.radiance.get(x, y);+ worst = worst.max(p[1]);+ }+ }+ assert!(worst < 0.02, "the brightest frame's star is left as a ghost (peak {worst})");+ assert!(r.ghost.get(360, 210) > 0.5, "the overlay marks the ghost");+}diff --git a/docs/merge.md b/docs/merge.mdindex 7c298cb10..537ab0f2c 100644--- a/docs/merge.md+++ b/docs/merge.md@@ -25,8 +25,11 @@ reference. Auto Align: features on exposure-normalised luminance, RANSAC translahomography (the simplest model that explains ≥ 97 % of the matches). Exposure ratios are measured(median log ratio of well-exposed pixels between brightness neighbours), EXIF is the fallback.Radiance is a weighted mean in linear light, weight `k · (1 − smoothstep(0.8·clip, 0.96·clip, max-channel))`. Deghost: a per-pixel consistency test against the reference radiance (with a noise-floor), dilated and feathered masks; the union is the deghost overlay. Output: 16-bit float DNG.+channel))`. Where the reference is at or near its clip the scene is at least that bright, so a frame that reads far+darker there (an object moved: a star, the moon, a passing light) is left out and the clipped highlight stays (always+on: a moving star otherwise left a black hole). Deghost: a per-pixel consistency test on ≤ 2048 px versions against the+reference radiance (with a noise floor; the reference predicts down to 0.1 % of its clip, so a brighter frame's ghost in+a night sky is caught), dilated and feathered masks; the union is the deghost overlay. Output: 16-bit float DNG.Lens corrections: frames are merged uncorrected, and the DNG's `OpcodeList3` carries the reference frame's(`WarpRectilinear`, `WarpRectilinear2`, `FixVignetteRadial`: a DNG's own, or a camera's correction a raw readerconverts, e.g. Sony, Panasonic), re-expressed for its default crop (`Opcode::cropped`). So Optics ▸ Enable Lens@@ -52,7 +55,10 @@ scale in `BaselineExposure`; raw sources keep their DNG colour tags (camera RGB)- HDR, 3 brackets ±2 EV with 14-bit noise and handheld shifts: alignment error < 0.3 px, exposureerror < 0.02 EV, radiance median log error < 0.03 (noise-limited, bias < 0.01), recovered- highlights < 0.05; moving object: ghost error 0.2–2.0 without deghosting, < 0.06 with High.+ highlights < 0.05; moving object: ghost error 0.2–2.0 without deghosting, < 0.06 with High; a star that moves+ across a night sky keeps its clipped core and, with High, leaves no ghost of the brightest frame.+- Real brackets (Sony A7R VI, 67 MP, 2026-10-14): frames agree with the merged radiance within ~1 % from 3 to 90 % of+ their clip in all three channels; measured exposure steps match EXIF within 0.03 EV.- Panorama, 5 views over 182° with a 1.3× exposure drift: relative rotations < 0.1°, focal < 1 %,BA RMS ≈ 0.35 px; median log error vs ground truth < 0.02; no seam steps.