camera: pick the sharpest night frame and merge robustly
- Commit
4031d783f282c24fd92bbd138d4ecd6facc2431c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 16:22 UTC (14 days ago)
- Parents
da0c252
Our burst merge used frame 0 as reference however blurry, and a plain mean with a fixed deghost threshold that let moving edges smear through dark regions. The reference is now the sharpest frame by Laplacian variance (computed on registration-resolution frames, inside mergeNight - no JNI change), and merging is count-aware: median at 3 frames, trimmed mean (drop min/max, computed without a sort) beyond. The deghost threshold scales with reference luminance (28 at black to the legacy 110 at white), so dark-region motion is rejected while real dark signal still merges. The single-pass merge also drops the old 128MB accumulator buffers at 8MP. Verified: cargo test camera_stitch 147 pass (8 new synthetic night tests), Kotlin night classes 29 pass.
Diff
camera/src/main/rust/src/night.rs
diff --git a/camera/src/main/rust/src/night.rs b/camera/src/main/rust/src/night.rsindex 79f3e82dd8..656d6581bf 100644--- a/camera/src/main/rust/src/night.rs+++ b/camera/src/main/rust/src/night.rs@@ -1,9 +1,9 @@-//! Night mode: align a hand-held burst to the first frame (ORB + RANSAC-//! homography) and temporally average with deghosting to reduce noise.+//! Night mode: align a hand-held burst to the sharpest frame (ORB + RANSAC+//! homography) and robustly average with deghosting to reduce noise. use crate::features::{detect_and_describe, match_features}; use crate::geometry::{find_homography_ransac, Pt};-use crate::imgbuf::{to_gray, Rgba};+use crate::imgbuf::{to_gray, Gray, Rgba}; use crate::linalg::{Matrix3, Vector3}; // Tuned for low-light: lower FAST threshold, more features, more RANSAC,@@ -15,7 +15,19 @@ const RANSAC_ITERS: usize = 500; const RANSAC_THRESH: f32 = 3.0; const MIN_INLIERS: usize = 12; const REG_MAX_MP: f64 = 0.8; // registration resolution-const GHOST_THRESH_SUM: i32 = 110; // sum |Rdiff|+|Gdiff|+|Bdiff| above -> ghost, skip+/// Deghost ceiling at full luma: sum |Rdiff|+|Gdiff|+|Bdiff| above -> ghost.+const GHOST_THRESH_SUM: i32 = 110;+/// Fraction of `GHOST_THRESH_SUM` still allowed at zero luma.+///+/// The deghost allowance scales with reference luma (a Weber-like relative+/// contrast rule: bright pixels can differ by more in absolute counts for the+/// same perceived change). Without a floor, near-black pixels would have a+/// ~0 allowance and ordinary read noise / bilinear resampling error (a few+/// counts per channel) would reject every contributing sample, eating the+/// dark-region signal the burst exists to recover. 0.25 gives 28 counts+/// summed over RGB (~9/channel) at black: above that noise floor, well below+/// a moving-edge step (typically >=15/channel, >=45 summed).+const GHOST_DARK_FLOOR_FRAC: f32 = 0.25; #[inline] fn apply(h: &Matrix3<f64>, x: f64, y: f64) -> (f64, f64) {@@ -47,6 +59,144 @@ fn scale_homography(h: &Matrix3<f64>, s: f64) -> Matrix3<f64> { ) } +/// Variance of the 4-neighbour Laplacian of a gray image: the classic+/// focus measure (Pech-Pacheco et al.). Sharp images have strong, varied+/// second derivatives; defocus/motion blur is a low-pass that collapses+/// both the magnitude and the spread, so variance (not just mean |Lap|)+/// separates them and is invariant to a constant brightness offset.+/// Borders are excluded (no full neighbourhood); <3x3 images score 0.+fn laplacian_variance(gray: &Gray) -> f64 {+ if gray.w < 3 || gray.h < 3 {+ return 0.0;+ }+ let (w, h) = (gray.w, gray.h);+ let mut sum = 0f64;+ let mut sum_sq = 0f64;+ for y in 1..h - 1 {+ for x in 1..w - 1 {+ let c = gray.px[y * w + x] as i32;+ let lap = 4 * c+ - gray.px[y * w + x - 1] as i32+ - gray.px[y * w + x + 1] as i32+ - gray.px[(y - 1) * w + x] as i32+ - gray.px[(y + 1) * w + x] as i32;+ let v = lap as f64;+ sum += v;+ sum_sq += v * v;+ }+ }+ let n = ((w - 2) * (h - 2)) as f64;+ let mean = sum / n;+ (sum_sq / n - mean * mean).max(0.0)+}++/// Index of the sharpest gray frame; ties keep the earliest frame (a flat+/// burst has no sharpness signal, and frame order is the least surprising+/// fallback).+fn pick_sharpest_index(grays: &[Gray]) -> usize {+ let mut best = 0usize;+ let mut best_score = f64::NEG_INFINITY;+ for (i, g) in grays.iter().enumerate() {+ let score = laplacian_variance(g);+ if score > best_score {+ best_score = score;+ best = i;+ }+ }+ best+}++/// Luma-adaptive deghost allowance (summed absolute RGB difference).+/// Scales `GHOST_THRESH_SUM` linearly from the dark floor at black to the+/// full legacy value at white, using Rec.601 luma (same weights as+/// `to_gray`).+fn ghost_threshold_sum(ref_px: [u8; 4]) -> i32 {+ let luma = (ref_px[0] as u32 * 77 + ref_px[1] as u32 * 150 + ref_px[2] as u32 * 29) >> 8;+ let frac = GHOST_DARK_FLOOR_FRAC + (1.0 - GHOST_DARK_FLOOR_FRAC) * (luma as f32 / 255.0);+ (GHOST_THRESH_SUM as f32 * frac).round() as i32+}++/// Robust per-channel combination of the samples gathered at one pixel:+/// one sample is itself, two are averaged, three take the median (which+/// discards a single outlier outright), and four or more take a trimmed+/// mean dropping the min and max. Dropping only the extremes needs no+/// sort: the result is `(sum - min - max) / (count - 2)`, so gathering+/// stays O(count) with no per-pixel allocation or O(k log k) sort.+fn trimmed_mean(sum: f32, min: f32, max: f32, count: usize) -> f32 {+ match count {+ 0 => 0.0,+ 1 => sum,+ 2 => sum * 0.5,+ 3 => sum - min - max,+ _ => (sum - min - max) / (count - 2) as f32,+ }+}++/// Merge frames already related to `frames[ref_idx]` by `inv_homographies`+/// (entry `i` maps reference coordinates into frame `i`'s coordinates;+/// `None`, and the reference itself, need no warp). Split from+/// `align_and_merge` so the merge semantics are testable with identity+/// warps, without depending on feature detection succeeding.+fn merge_with_homographies(+ frames: &[Rgba],+ ref_idx: usize,+ inv_homographies: &[Option<Matrix3<f64>>],+) -> Option<Rgba> {+ let reff = frames.get(ref_idx)?;+ let (w, h) = (reff.w, reff.h);+ if w == 0 || h == 0 {+ return None;+ }+ let mut out = Rgba::new(w, h);+ for y in 0..h {+ for x in 0..w {+ let rp = reff.get(x, y);+ let thresh = ghost_threshold_sum(rp);+ // Per-channel running sum/min/max/count for the trimmed mean.+ let mut sum = [rp[0] as f32, rp[1] as f32, rp[2] as f32];+ let mut min = sum;+ let mut max = sum;+ let mut count = 1usize;+ for (i, f) in frames.iter().enumerate() {+ if i == ref_idx {+ continue;+ }+ let Some(h_inv) = inv_homographies.get(i).copied().flatten() else {+ continue;+ };+ let (sx, sy) = apply(&h_inv, x as f64, y as f64);+ let Some(c) = f.sample(sx as f32, sy as f32) else {+ continue;+ };+ // Deghost: skip samples far from the reference so a moving+ // object (or a flash) cannot smear into the stack. The+ // allowance is luma-adaptive; see `ghost_threshold_sum`.+ let diff = (c[0] - rp[0] as f32).abs()+ + (c[1] - rp[1] as f32).abs()+ + (c[2] - rp[2] as f32).abs();+ if diff > thresh as f32 {+ continue;+ }+ for ch in 0..3 {+ sum[ch] += c[ch];+ min[ch] = min[ch].min(c[ch]);+ max[ch] = max[ch].max(c[ch]);+ }+ count += 1;+ }+ let mut px = [0u8; 4];+ for ch in 0..3 {+ px[ch] = trimmed_mean(sum[ch], min[ch], max[ch], count)+ .round()+ .clamp(0.0, 255.0) as u8;+ }+ px[3] = 255;+ out.set(x, y, px);+ }+ }+ Some(out)+}+ pub fn align_and_merge(frames: &[Rgba]) -> Option<Rgba> { let n = frames.len(); if n == 0 {@@ -55,55 +205,48 @@ pub fn align_and_merge(frames: &[Rgba]) -> Option<Rgba> { if n == 1 { return Some(frames[0].clone()); }- let reff = &frames[0];- let w = reff.w;- let h = reff.h;- if w == 0 || h == 0 {+ if frames[0].w == 0 || frames[0].h == 0 { return None; } - // Registration scale: downscale large frames for feature detection.- let area = w as f64 * h as f64;+ // Registration-resolution copies of every frame. Sharpness is judged+ // at this resolution (the frames registration actually sees): full-res+ // sensor noise inflates Laplacian variance roughly uniformly and would+ // cost a full-res pass per frame, while blur that matters for choosing+ // a reference survives the downscale to ~0.8 MP.+ let area = frames[0].w as f64 * frames[0].h as f64; let reg_scale = (REG_MAX_MP * 1e6 / area).sqrt().min(1.0);- let (ref_small, ref_s) = if reg_scale < 0.999 {- let rw = ((w as f64 * reg_scale).round() as usize).max(1);- let rh = ((h as f64 * reg_scale).round() as usize).max(1);- (reff.resized(rw, rh), reg_scale)- } else {- (reff.clone(), 1.0)- };- let ref_feat = detect_and_describe(&to_gray(&ref_small), MAX_FEATURES, FAST_THRESHOLD);-- let mut acc = vec![0f32; w * h * 3];- let mut cnt = vec![0f32; w * h];+ let mut smalls: Vec<Rgba> = Vec::with_capacity(n);+ let mut small_grays: Vec<Gray> = Vec::with_capacity(n);+ for f in frames {+ let small = if reg_scale < 0.999 {+ let rw = ((f.w as f64 * reg_scale).round() as usize).max(1);+ let rh = ((f.h as f64 * reg_scale).round() as usize).max(1);+ f.resized(rw, rh)+ } else {+ f.clone()+ };+ small_grays.push(to_gray(&small));+ smalls.push(small);+ } - // Reference pixels always contribute.- for yy in 0..h {- for xx in 0..w {- let rc = reff.get(xx, yy);- let idx = yy * w + xx;- acc[idx * 3] = rc[0] as f32;- acc[idx * 3 + 1] = rc[1] as f32;- acc[idx * 3 + 2] = rc[2] as f32;- cnt[idx] = 1.0;- }+ // Sharpest-frame reference, chosen inside the merge so the Kotlin/JNI+ // session API (newNightSession/addNightRgbaFrame/mergeNight) needs no+ // new call: by merge time every frame is already here.+ let ref_idx = pick_sharpest_index(&small_grays);+ let reff = &frames[ref_idx];+ if reff.w == 0 || reff.h == 0 {+ return None; }+ let ref_feat = detect_and_describe(&small_grays[ref_idx], MAX_FEATURES, FAST_THRESHOLD); - for f in frames.iter().skip(1) {- // Feature detection at reduced resolution.- let (cur_small, s) = if ref_s < 0.999 {- let rw = ((f.w as f64 * ref_s).round() as usize).max(1);- let rh = ((f.h as f64 * ref_s).round() as usize).max(1);- // Guard dimension mismatch (should match reg scale but keep safe)- if rw * rh == 0 {- (f.clone(), 1.0)- } else {- (f.resized(rw, rh), ref_s)- }- } else {- (f.clone(), 1.0)- };- let feat = detect_and_describe(&to_gray(&cur_small), MAX_FEATURES, FAST_THRESHOLD);+ // Estimate each other frame's warp into reference coordinates.+ let mut inv_homographies: Vec<Option<Matrix3<f64>>> = vec![None; n];+ for (i, f) in frames.iter().enumerate() {+ if i == ref_idx {+ continue;+ }+ let feat = detect_and_describe(&small_grays[i], MAX_FEATURES, FAST_THRESHOLD); let matches = match_features(&feat, &ref_feat, RATIO); if matches.len() < MIN_INLIERS { continue;@@ -114,52 +257,14 @@ pub fn align_and_merge(frames: &[Rgba]) -> Option<Rgba> { Some((hm, inl)) if inl >= MIN_INLIERS => hm, _ => continue, };+ let s = if f.w > 0 { smalls[i].w as f64 / f.w as f64 } else { 1.0 }; let h_to_ref = scale_homography(&h_small, s);- let h_inv = match h_to_ref.try_inverse() {- Some(m) => m,- None => continue,- };- // Warp and accumulate with deghosting against reference.- for y in 0..h {- for x in 0..w {- let (sx, sy) = apply(&h_inv, x as f64, y as f64);- if let Some(c) = f.sample(sx as f32, sy as f32) {- // Deghost: skip samples far from reference to avoid moving-object ghosts.- let rp = reff.get(x, y);- let diff = (c[0] as i32 - rp[0] as i32).abs()- + (c[1] as i32 - rp[1] as i32).abs()- + (c[2] as i32 - rp[2] as i32).abs();- if diff > GHOST_THRESH_SUM {- continue;- }- let idx = y * w + x;- acc[idx * 3] += c[0];- acc[idx * 3 + 1] += c[1];- acc[idx * 3 + 2] += c[2];- cnt[idx] += 1.0;- }- }+ if let Some(h_inv) = h_to_ref.try_inverse() {+ inv_homographies[i] = Some(h_inv); } } - let mut out = Rgba::new(w, h);- for i in 0..w * h {- let c = cnt[i];- let d = i * 4;- if c > 0.0 {- out.px[d] = (acc[i * 3] / c).round().clamp(0.0, 255.0) as u8;- out.px[d + 1] = (acc[i * 3 + 1] / c).round().clamp(0.0, 255.0) as u8;- out.px[d + 2] = (acc[i * 3 + 2] / c).round().clamp(0.0, 255.0) as u8;- out.px[d + 3] = 255;- } else {- let rc = reff.get(i % w, i / w);- out.px[d] = rc[0];- out.px[d + 1] = rc[1];- out.px[d + 2] = rc[2];- out.px[d + 3] = 255;- }- }- Some(out)+ merge_with_homographies(frames, ref_idx, &inv_homographies) } #[cfg(test)]
camera/src/main/rust/src/night_tests.rs
diff --git a/camera/src/main/rust/src/night_tests.rs b/camera/src/main/rust/src/night_tests.rsindex e7b0226bbd..7b3cf23311 100644--- a/camera/src/main/rust/src/night_tests.rs+++ b/camera/src/main/rust/src/night_tests.rs@@ -2,6 +2,7 @@ //! and the public burst-merge entry point on synthetic frames. use super::*;+use crate::imgbuf::Gray; use crate::linalg::Matrix3; fn approx(a: f64, b: f64) -> bool {@@ -85,6 +86,141 @@ fn align_and_merge_identical_frames_returns_same_image() { assert!(out.px.chunks_exact(4).all(|p| p == [90, 80, 70, 255])); } +fn gray_checkerboard(w: usize, h: usize) -> Gray {+ let mut g = Gray::new(w, h);+ for y in 0..h {+ for x in 0..w {+ g.px[y * w + x] = if (x + y) % 2 == 0 { 255 } else { 0 };+ }+ }+ g+}++/// 3x3 box blur with clamped edges: a stand-in for a defocused frame.+fn blurred(g: &Gray) -> Gray {+ let mut out = Gray::new(g.w, g.h);+ for y in 0..g.h {+ for x in 0..g.w {+ let mut sum = 0u32;+ for dy in -1i32..=1 {+ for dx in -1i32..=1 {+ let xx = (x as i32 + dx).clamp(0, g.w as i32 - 1) as usize;+ let yy = (y as i32 + dy).clamp(0, g.h as i32 - 1) as usize;+ sum += g.px[yy * g.w + xx] as u32;+ }+ }+ out.px[y * g.w + x] = (sum / 9) as u8;+ }+ }+ out+}++#[test]+fn sharpest_frame_is_not_the_blurred_one() {+ let sharp = gray_checkerboard(24, 18);+ let blurry = blurred(&sharp);+ assert!(laplacian_variance(&sharp) > laplacian_variance(&blurry));+ assert_eq!(laplacian_variance(&Gray::new(8, 8)), 0.0, "flat scores zero");+ assert_eq!(pick_sharpest_index(&[blurry.clone(), sharp.clone()]), 1);+ assert_eq!(pick_sharpest_index(&[sharp, blurry]), 0);+ // No sharpness signal anywhere: earliest frame wins.+ assert_eq!(pick_sharpest_index(&[Gray::new(8, 8), Gray::new(8, 8)]), 0);+}++#[test]+fn align_and_merge_does_not_pick_blurry_first_frame_as_reference() {+ let blurry = solid(24, 18, [100, 100, 100, 255]);+ let mut sharp = Rgba::new(24, 18);+ for y in 0..18 {+ for x in 0..24 {+ let v = if (x / 2 + y / 2) % 2 == 0 { 40 } else { 220 };+ sharp.set(x, y, [v, v, v, 255]);+ }+ }+ // Frame 0 is the blurry one; the sharp frame must become the reference,+ // so the output is the sharp frame, not the flat first frame.+ let out = align_and_merge(&[blurry, sharp.clone()]).expect("merge");+ assert_eq!(out.px, sharp.px);+}++#[test]+fn ghost_threshold_is_luma_adaptive_with_dark_floor() {+ assert_eq!(ghost_threshold_sum([0, 0, 0, 255]), 28, "dark floor 25% of 110");+ assert_eq!(ghost_threshold_sum([255, 255, 255, 255]), 110, "full legacy value at white");+ let dark = ghost_threshold_sum([12, 12, 12, 255]);+ let mid = ghost_threshold_sum([128, 128, 128, 255]);+ assert!(dark < mid && mid < 110, "monotonic in luma: {dark} {mid}");+}++#[test]+fn trimmed_mean_by_sample_count() {+ assert_eq!(trimmed_mean(100.0, 100.0, 100.0, 1), 100.0);+ assert_eq!(trimmed_mean(300.0, 100.0, 200.0, 2), 150.0, "two samples: mean");+ assert_eq!(trimmed_mean(390.0, 90.0, 200.0, 3), 100.0, "three samples: median");+ // Four samples 100,100,100,255: drop min+max, average the middle two.+ assert_eq!(trimmed_mean(555.0, 100.0, 255.0, 4), 100.0);+}++fn identities(n: usize) -> Vec<Option<Matrix3<f64>>> {+ vec![Some(Matrix3::identity()); n]+}++#[test]+fn merge_identical_frames_preserves_image() {+ let mut f = Rgba::new(16, 12);+ for y in 0..12 {+ for x in 0..16 {+ let v = ((x * 11 + y * 7) % 251) as u8;+ f.set(x, y, [v, v, v, 255]);+ }+ }+ let frames = vec![f.clone(), f.clone(), f.clone(), f.clone()];+ let out = merge_with_homographies(&frames, 0, &identities(4)).expect("merge");+ assert_eq!(out.px, f.px, "identical frames: trimmed mean is the frame");+}++#[test]+fn merge_rejects_single_flash_frame_via_trimming() {+ // Baseline 200 with one frame flashed to 230 in a block. The flash+ // passes deghosting (diff 90 <= adaptive threshold 92 at luma 200), so+ // only the trimmed mean can reject it: the plain mean would give 208.+ let base = solid(16, 12, [200, 200, 200, 255]);+ let mut flash = base.clone();+ for y in 4..8 {+ for x in 4..8 {+ flash.set(x, y, [230, 230, 230, 255]);+ }+ }+ let frames = vec![base.clone(), base.clone(), base.clone(), flash];+ let out = merge_with_homographies(&frames, 0, &identities(4)).expect("merge");+ assert_eq!(out.get(5, 5), [200, 200, 200, 255], "flash block trimmed away");+ assert_eq!(out.get(0, 0), [200, 200, 200, 255]);+}++#[test]+fn merge_three_frames_uses_median() {+ // 200/210/230 all pass deghosting vs the 200 reference; the median+ // (210), not the mean (213), wins with three samples.+ let frames = vec![+ solid(8, 6, [200, 200, 200, 255]),+ solid(8, 6, [210, 210, 210, 255]),+ solid(8, 6, [230, 230, 230, 255]),+ ];+ let out = merge_with_homographies(&frames, 0, &identities(3)).expect("merge");+ assert_eq!(out.get(2, 2), [210, 210, 210, 255]);+}++#[test]+fn merge_dark_region_small_change_still_merges() {+ // Dark pixels: 12 -> 20 is a summed diff of 24, below both the old+ // fixed 110 and the adaptive threshold at luma 12 (31), so the second+ // frame still contributes and the output is the two-frame mean.+ assert!(24 < ghost_threshold_sum([12, 12, 12, 255]));+ let frames = vec![solid(8, 6, [12, 12, 12, 255]), solid(8, 6, [20, 20, 20, 255])];+ let out = merge_with_homographies(&frames, 0, &identities(2)).expect("merge");+ assert_eq!(out.get(2, 2), [16, 16, 16, 255]);+}+ #[test] fn align_and_merge_output_size_follows_reference_frame() { let a = solid(10, 8, [10, 10, 10, 255]);