Files
luminary/server/denoise/noise.ts
T
bhursey cd52a2f82f Initial commit: Luminary photo catalog and RAW editor
Browser-based photo catalog with an optional team server (SQLite + LibRaw).
Local database, uploaded photos, build output and dependencies are gitignored.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-23 15:19:25 +00:00

177 lines
6.2 KiB
TypeScript

/**
* Noise level estimation from a single finished image.
*
* The model is the Poisson-Gaussian one the rest of the pipeline assumes:
*
* var(luma) = shot * luma + read
*
* but measured in 8-bit sRGB units directly, because the thing we can actually
* see and measure is the finished proxy -- after demosaic, tone curve and JPEG.
* Fitting a sensor model and then pushing it through LibRaw's tone curve would
* be more principled and much less reliable.
*
* Two details make the estimate usable on real photographs:
*
* - The high-pass residual is taken over 16x16 blocks, and texture (which
* raises the local MAD) is kept out of the answer by a two-step statistic:
* a low quantile of the per-block sigmas sets the scale, blocks near it are
* kept, and the median of those is the estimate. See the comment at the
* computation for why neither statistic works alone.
* - A 3x3 box high-pass attenuates white noise by sqrt(8/9); that gain is
* divided back out, otherwise every sigma is 6% low.
*/
import { boxBlur, clamp, quantile } from './planes.ts';
/** White-noise gain of `I - boxBlur(I, 1)`; sqrt(1 - 2/9 + 1/9). */
const HP_NOISE_GAIN = Math.sqrt(8 / 9);
/** MAD -> sigma for a Gaussian. */
const MAD_TO_SIGMA = 1 / 0.6745;
/** Below this, an 8-bit sRGB image has no measurable noise. */
export const SIGMA_FLOOR = 0.35;
export type NoiseTrend = 'fit' | 'flat';
export interface NoiseModel {
/** sigma = a + b * luma, 8-bit units. */
a: number;
b: number;
/** Whether the luminance trend was trusted, or a flat floor was used. */
trend: NoiseTrend;
/** Per-bin measurements that produced the fit (diagnostics). */
bins: { luma: number; sigma: number; blocks: number }[];
/** Robust global floor, ignoring the luminance trend. */
global: number;
sigmaAt(luma: number): number;
}
export function createNoiseModel(
a: number,
b: number,
global: number,
bins: NoiseModel['bins'],
trend: NoiseTrend = 'flat',
): NoiseModel {
return {
a,
b,
global,
trend,
bins,
sigmaAt(luma: number): number {
const s = a + b * clamp(luma, 0, 255);
return s < SIGMA_FLOOR ? SIGMA_FLOOR : s;
},
};
}
export function estimateNoise(luma: Float32Array, width: number, height: number): NoiseModel {
const residual = boxBlur(luma, width, height, 1);
for (let i = 0; i < residual.length; i++) residual[i] = luma[i] - residual[i];
const BLOCK = 16;
const BINS = 16;
const perBin: number[][] = Array.from({ length: BINS }, () => []);
const all: number[] = [];
const scratch = new Float32Array(BLOCK * BLOCK);
for (let by = 0; by + BLOCK <= height; by += BLOCK) {
for (let bx = 0; bx + BLOCK <= width; bx += BLOCK) {
let sumLuma = 0;
let n = 0;
for (let y = 0; y < BLOCK; y++) {
const row = (by + y) * width + bx;
for (let x = 0; x < BLOCK; x++) {
sumLuma += luma[row + x];
const v = residual[row + x];
scratch[n++] = v < 0 ? -v : v;
}
}
const meanLuma = sumLuma / n;
// Clipped highlights and crushed blacks have no usable noise statistic.
if (meanLuma < 6 || meanLuma > 249) continue;
const sigma = quantile(scratch.subarray(0, n), 0.5) * MAD_TO_SIGMA / HP_NOISE_GAIN;
// A perfectly flat block measures exactly zero and must be *kept*: it is
// the strongest evidence of a clean frame. Dropping it left a frame that
// was half flat and half texture reported as uniformly noisy.
if (!Number.isFinite(sigma)) continue;
all.push(sigma);
const bin = clamp(Math.floor(meanLuma / (256 / BINS)), 0, BINS - 1);
perBin[bin].push(sigma);
}
}
if (all.length === 0) {
return createNoiseModel(SIGMA_FLOOR, 0, SIGMA_FLOOR, []);
}
// Two steps, because either statistic alone fails on a real frame:
//
// - the *median* is accurate on a homogeneous field but reads texture as
// noise when more than half the frame is detailed (a brick wall, a striping
// shirt, half a test chart), which can push sigma 30x high;
// - a low quantile ignores texture but sits in the low tail of the
// estimator's own sampling noise.
//
// So: a low quantile sets the scale, blocks near it are kept, and the median
// of those is the answer. At ~10k blocks the quantile's bias is a few percent
// and the median removes it.
const floor = Math.max(SIGMA_FLOOR, quantile(all, 0.25));
const cutoff = floor * 1.5;
const flatBlocks = all.filter((value) => value <= cutoff);
const global = Math.max(SIGMA_FLOOR, quantile(flatBlocks.length > 0 ? flatBlocks : all, 0.5));
const bins: NoiseModel['bins'] = [];
for (let i = 0; i < BINS; i++) {
const flat = perBin[i].filter((v) => v <= cutoff);
if (flat.length < 5) continue;
bins.push({
luma: (i + 0.5) * (256 / BINS),
sigma: quantile(flat, 0.5),
blocks: flat.length,
});
}
// A bin that is mostly texture reports texture, not noise: on a frame with a
// detailed foreground the low-luma bins can read several times the true
// floor. Fit only the bins that sit near the floor, then reject the whole
// trend if the resulting line leaves a physically plausible range. A flat
// sigma is a worse model than a good trend and a far better one than a bad
// trend, and this keeps the bad trend out.
const usable = bins.filter((bin) => bin.blocks >= 8 && bin.sigma <= global * 1.6);
if (usable.length >= 3) {
let sw = 0;
let sx = 0;
let sy = 0;
let sxx = 0;
let sxy = 0;
for (const bin of usable) {
const w = bin.blocks;
sw += w;
sx += w * bin.luma;
sy += w * bin.sigma;
sxx += w * bin.luma * bin.luma;
sxy += w * bin.luma * bin.sigma;
}
const det = sw * sxx - sx * sx;
if (Math.abs(det) > 1e-6) {
const b = (sw * sxy - sx * sy) / det;
const a = (sy - b * sx) / sw;
const low = a;
const high = a + b * 255;
const lo = global * 0.5;
const hi = global * 2.5;
if (
Number.isFinite(a) &&
Number.isFinite(b) &&
low >= lo && low <= hi &&
high >= lo && high <= hi
) {
return createNoiseModel(a, b, global, bins, 'fit');
}
}
}
return createNoiseModel(global, 0, global, bins);
}