/** * Detail / structure separation. * * The whole feature rests on one idea: a denoiser may only remove things that * do *not* look like structure. This module produces the map that decides * that, from three cheap local measurements: * * 1. `detail` -- the high-frequency residual of an edge-preserving filter. * 2. `sigma` -- the noise level expected at this luminance. * 3. `coherence` -- how organised the local gradient is (a curve vs. grain). * * A pixel with detail well above the noise floor, or with a coherent edge * through it, gets `gate -> 1` and its original values are restored verbatim * after denoising. Flat grain gets `gate -> 0` and is replaced wholesale. */ import { boxBlur, clamp, clamp01, resample, smoothstep } from './planes.ts'; /** * Guided filter (He et al.), O(1) per pixel. * * Used instead of a bilateral filter because it needs no per-pixel search: * four box passes, and the edge-preserving behaviour is exactly what the * base/detail split needs. `eps` is a variance, so it is the noise sigma * squared, scaled by how aggressively we want to smooth. */ export function guidedFilter( src: Float32Array, width: number, height: number, radius: number, eps: number, ): Float32Array { const a = boxBlur(src, width, height, radius); const b = new Float32Array(src.length); for (let i = 0; i < src.length; i++) b[i] = src[i] * src[i]; boxBlur(b, width, height, radius, b); // b <- a (the guided-filter gain), a <- mean * (1 - gain). const e = Math.max(eps, 1e-6); for (let i = 0; i < src.length; i++) { const mean = a[i]; const variance = b[i] - mean * mean; const gain = variance / (variance + e); b[i] = gain; a[i] = mean * (1 - gain); } boxBlur(b, width, height, radius, b); boxBlur(a, width, height, radius, a); const out = new Float32Array(src.length); for (let i = 0; i < src.length; i++) out[i] = b[i] * src[i] + a[i]; return out; } export interface StructureMap { /** 0 = isotropic (grain, flat), 1 = a clean line or edge. */ data: Float32Array; width: number; height: number; } /** * Structure-tensor coherence, computed at reduced resolution. * * Coherence is a geometric property of edges and varies slowly across the * frame, so measuring it at 1/`stride` and interpolating back is visually * identical and ~`stride^2` cheaper in both time and memory. */ export function structureMap( gray: Float32Array, width: number, height: number, radius = 2, stride = 2, sigmaFloor = 1, ): StructureMap { const sw = Math.max(2, Math.floor(width / stride)); const sh = Math.max(2, Math.floor(height / stride)); const small = resample(gray, width, height, sw, sh); const gx = new Float32Array(sw * sh); const gy = new Float32Array(sw * sh); for (let y = 0; y < sh; y++) { const y0 = clamp(y - 1, 0, sh - 1) * sw; const y1 = clamp(y + 1, 0, sh - 1) * sw; const row = y * sw; for (let x = 0; x < sw; x++) { const x0 = clamp(x - 1, 0, sw - 1); const x1 = clamp(x + 1, 0, sw - 1); // Scharr kernels: better rotational symmetry than Sobel at this size. gx[row + x] = (3 * (small[y0 + x1] - small[y0 + x0]) + 10 * (small[row + x1] - small[row + x0]) + 3 * (small[y1 + x1] - small[y1 + x0])) / 16; gy[row + x] = (3 * (small[y1 + x0] - small[y0 + x0]) + 10 * (small[y1 + x] - small[y0 + x]) + 3 * (small[y1 + x1] - small[y0 + x1])) / 16; } } const jxx = new Float32Array(sw * sh); const jyy = new Float32Array(sw * sh); const jxy = new Float32Array(sw * sh); for (let i = 0; i < gx.length; i++) { jxx[i] = gx[i] * gx[i]; jyy[i] = gy[i] * gy[i]; jxy[i] = gx[i] * gy[i]; } boxBlur(jxx, sw, sh, radius, jxx); boxBlur(jyy, sw, sh, radius, jyy); boxBlur(jxy, sw, sh, radius, jxy); const data = new Float32Array(sw * sh); const floor = sigmaFloor * sigmaFloor; for (let i = 0; i < data.length; i++) { const trace = jxx[i] + jyy[i]; const disc = Math.sqrt(Math.max(0, (jxx[i] - jyy[i]) * (jxx[i] - jyy[i]) + 4 * jxy[i] * jxy[i])); if (trace <= floor) continue; data[i] = clamp01(disc / trace); } return { data, width: sw, height: sh }; } /** * Mean |detail| of pure Gaussian noise, relative to sigma. * * The statistic compared against the threshold is a mean absolute value over * the 3x3-smoothed high-pass of a noise field, which measures ~1.0 sigma when * the noise model is correct. Calibrated against a flat ISO 6400 sky, where * |detail|/sigma had median 1.05. Expressing the ramp in these units puts 1.0 * at "indistinguishable from grain" instead of at "one sigma", which is not * the same thing at all. */ const NOISE_MAGNITUDE = 1.0; export interface GateOptions { /** Below this multiple of the expected noise magnitude, detail is noise. */ lo: number; /** Above this multiple, detail is unambiguously signal. */ hi: number; /** * How much an organised edge lowers the amplitude needed to open the gate. * 1.0 means a perfectly coherent line needs half the contrast of grain to be * believed; 0 disables the structure term entirely. */ coherenceBoost: number; /** * Isolated points have no coherence, so the structure term cannot save them * and the 3x3 magnitude average below shrinks them toward the noise floor. A * pixel that is the local maximum of |detail| and clears this many noise * magnitudes on its own opens the gate anyway. */ pointLo: number; /** Above this multiple, an isolated point is unambiguously real. */ pointHi: number; } // 1.0 measured on three D700 frames with synthetic sigma=6: fine-texture // retention 48/52/24% -> 78/79/45% against 0 (no structure term), edge // retention up, global grain unchanged. 1.5 reaches 97-98% but at 14% gate // coverage it starts keeping the grain that sits on the texture, which is not // separable at this scale anyway -- 1.0 is the knee. // pointLo/Hi measured by injecting 1 px sources into a real ISO 6400 sky. The // old gate kept 8% of a 5-sigma point's contrast and 44% of an 8-sigma one. // // The threshold looks high for a reason: the rule is a *local maximum*, and the // max of nine correlated grain samples routinely reaches ~2 sigma, so 2.2 both // protected grain and failed the corpus guard (grain 0.55 -> 1.36). 3.0 is the // lowest value that leaves grain and chroma unchanged across the guarded corpus // while keeping 5-sigma points (~0.9 of their contrast) and 8-sigma points // (~1.0). A 3-sigma point stays smoothed -- at this scale it is not separable // from the brightest grain beside it, and pretending otherwise costs the frame. export const DEFAULT_GATE: GateOptions = { lo: 1.15, hi: 2.1, coherenceBoost: 1.0, pointLo: 3.0, pointHi: 4.0, }; /** * Per-pixel "how much of this pixel is real" map, 0..1. * *`detail` is the signed residual, `sigma` the expected noise at each pixel. * The detail magnitude is box-smoothed so a single stray pixel cannot open the * gate on its own, and `coherence` scales the amplitude required to open it. * The one exception is an isolated peak large enough to be a point source: * smoothing would erase exactly the detail (stars, specular pinpoints) this * feature exists to keep, so local maxima get their own path. */ export function detailGate( detail: Float32Array, width: number, height: number, sigma: Float32Array, coherence: Float32Array, options: GateOptions = DEFAULT_GATE, ): Float32Array { const magnitude = new Float32Array(detail.length); for (let i = 0; i < detail.length; i++) magnitude[i] = detail[i] < 0 ? -detail[i] : detail[i]; boxBlur(magnitude, width, height, 1, magnitude); const gate = new Float32Array(detail.length); const pointOn = options.pointHi > 0 && options.pointHi > options.pointLo; for (let i = 0; i < detail.length; i++) { const s = sigma[i] < 0.05 ? 0.05 : sigma[i]; // 1.0 means "exactly what a flat noisy patch measures", not "one sigma". const ratio = magnitude[i] / (NOISE_MAGNITUDE * s); // Coherence of pure noise measures ~0.49, so it cannot be applied linearly: // that leaks ~0.12 of gate onto every grain pixel. Cubing it keeps ordinary // noise at ~0.12 while a real edge (0.9) still reaches 0.73. const organised = coherence[i] * coherence[i] * coherence[i]; // Coherence *lowers the bar*, it does not add to the answer. Adding an // independent term (the previous form) meant an organised line still had to // clear the full amplitude threshold on its own, so low-contrast 2-3 px // texture -- which is exactly what "detail soft" looks like -- got nothing. // Scaling the ratio instead says: a line needs less contrast to be believed, // which is the same claim the threshold makes about grain. const belief = 1 + options.coherenceBoost * organised; let g = smoothstep(options.lo, options.hi, ratio * belief); // Isolated-point path. The 3x3 average above shrinks a 1 px source toward // the noise floor, so the crossfade replaced it with the softened base -- // measured: a 5-sigma point kept 8%, an 8-sigma point 44%. The threshold sits // above the local maximum grain reaches (see DEFAULT_GATE). Ties pass so a // 2 px highlight is not lost to the comparison. if (pointOn) { const a = detail[i] < 0 ? -detail[i] : detail[i]; const own = a / (NOISE_MAGNITUDE * s); if (own > options.pointLo) { const x = i % width; const y = (i - x) / width; if (x > 0 && y > 0 && x < width - 1 && y < height - 1) { let peak = true; for (let dy = -1; dy <= 1 && peak; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) continue; const n = detail[i + dy * width + dx]; if ((n < 0 ? -n : n) > a) { peak = false; break; } } } if (peak) { const opened = smoothstep(options.pointLo, options.pointHi, own); if (opened > g) g = opened; } } } } gate[i] = g; } return gate; }