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>
This commit is contained in:
2026-11-23 15:19:25 +00:00
commit cd52a2f82f
121 changed files with 101872 additions and 0 deletions
+56
View File
@@ -0,0 +1,56 @@
/**
* Interleaved RGB <-> luma/chroma, so luma and chroma can take different
* denoise paths.
*
* Chroma noise is low-frequency and the eye has little chroma acuity, so it is
* worth smoothing hard; luma carries all the detail and is the expensive,
* gated path. The transform is the standard sRGB-weighted one and round-trips
* to within rounding.
*/
export interface RgbImage {
/** Interleaved 8-bit RGB, `width * height * 3` bytes. */
rgb: Uint8Array;
width: number;
height: number;
}
export interface YccPlanes {
y: Float32Array;
cb: Float32Array;
cr: Float32Array;
}
export function toYcc(image: RgbImage): YccPlanes {
const { rgb, width, height } = image;
const n = width * height;
const y = new Float32Array(n);
const cb = new Float32Array(n);
const cr = new Float32Array(n);
for (let i = 0, p = 0; i < n; i++, p += 3) {
const r = rgb[p];
const g = rgb[p + 1];
const b = rgb[p + 2];
y[i] = 0.299 * r + 0.587 * g + 0.114 * b;
cb[i] = 128 - 0.168736 * r - 0.331264 * g + 0.5 * b;
cr[i] = 128 + 0.5 * r - 0.418688 * g - 0.081312 * b;
}
return { y, cb, cr };
}
export function fromYcc(planes: YccPlanes, width: number, height: number): Uint8Array {
const n = width * height;
const out = new Uint8Array(n * 3);
for (let i = 0, p = 0; i < n; i++, p += 3) {
const y = planes.y[i];
const cb = planes.cb[i] - 128;
const cr = planes.cr[i] - 128;
const r = y + 1.402 * cr;
const g = y - 0.344136 * cb - 0.714136 * cr;
const b = y + 1.772 * cb;
out[p] = r < 0 ? 0 : r > 255 ? 255 : r + 0.5;
out[p + 1] = g < 0 ? 0 : g > 255 ? 255 : g + 0.5;
out[p + 2] = b < 0 ? 0 : b > 255 ? 255 : b + 0.5;
}
return out;
}
+253
View File
@@ -0,0 +1,253 @@
/**
* 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;
}
+176
View File
@@ -0,0 +1,176 @@
/**
* 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);
}
+179
View File
@@ -0,0 +1,179 @@
/**
* Scalar float planes plus the resampling and box-filter primitives the
* detail-preserving denoise is built from.
*
* Everything here is plain `Float32Array` arithmetic with no allocation in the
* hot loops: the full-resolution stage runs at proxy size (up to 24 MP), and
* allocation churn is the difference between two seconds and six per photo.
*/
export interface Plane {
data: Float32Array;
width: number;
height: number;
}
export function createPlane(width: number, height: number): Plane {
return { data: new Float32Array(width * height), width, height };
}
export function clamp01(v: number): number {
return v < 0 ? 0 : v > 1 ? 1 : v;
}
export function clamp(v: number, lo: number, hi: number): number {
return v < lo ? lo : v > hi ? hi : v;
}
/** Hermite ramp: 0 below `lo`, 1 above `hi`. */
export function smoothstep(lo: number, hi: number, x: number): number {
if (hi <= lo) return x >= hi ? 1 : 0;
const t = clamp01((x - lo) / (hi - lo));
return t * t * (3 - 2 * t);
}
function edge(i: number, n: number): number {
return i < 0 ? 0 : i >= n ? n - 1 : i;
}
/**
* Scratch buffer for the separable passes, grown on demand.
*
* Safe because `boxBlur` is not reentrant: every caller finishes with the
* buffer before making another call, and the buffer is never handed out.
*/
let scratchBuffer: Float32Array | null = null;
function scratch(length: number): Float32Array {
if (!scratchBuffer || scratchBuffer.length < length) scratchBuffer = new Float32Array(length);
return scratchBuffer.subarray(0, length);
}
/**
* Separable box blur with clamped edges, O(1) per pixel.
*
* `out` may alias `src`: the horizontal pass goes through the shared scratch
* buffer, and only the vertical pass writes `out`, so an in-place call is
* safe. That aliasing is what keeps the guided filter allocation-light.
*/
export function boxBlur(
src: Float32Array,
width: number,
height: number,
radius: number,
out?: Float32Array,
): Float32Array {
const dst = out ?? new Float32Array(src.length);
if (src.length < width * height) {
throw new Error(`plane is ${src.length} values, expected ${width * height}`);
}
if (radius <= 0) {
if (dst !== src) dst.set(src);
return dst;
}
const tmp = scratch(width * height);
const norm = 1 / (2 * radius + 1);
// Horizontal pass: src -> tmp.
for (let y = 0; y < height; y++) {
const row = y * width;
let sum = 0;
for (let x = -radius; x <= radius; x++) sum += src[row + edge(x, width)];
for (let x = 0; x < width; x++) {
tmp[row + x] = sum * norm;
sum += src[row + edge(x + radius + 1, width)] - src[row + edge(x - radius, width)];
}
}
// Vertical pass: tmp -> dst.
for (let x = 0; x < width; x++) {
let sum = 0;
for (let y = -radius; y <= radius; y++) sum += tmp[edge(y, height) * width + x];
for (let y = 0; y < height; y++) {
dst[y * width + x] = sum * norm;
sum +=
tmp[edge(y + radius + 1, height) * width + x] -
tmp[edge(y - radius, height) * width + x];
}
}
return dst;
}
/**
* Bilinear resample. Used for the two-scale split: luma is reduced to the
* inference size, denoised, then brought back up so full-resolution detail can
* be re-injected on top.
*/
export function resample(
src: Float32Array,
sw: number,
sh: number,
dw: number,
dh: number,
): Float32Array {
if (sw === dw && sh === dh) return src.slice();
const out = new Float32Array(dw * dh);
const xRatio = sw / dw;
const yRatio = sh / dh;
for (let y = 0; y < dh; y++) {
// Sample at pixel centres so a downscale is a centred box, not a shifted one.
const sy = clamp((y + 0.5) * yRatio - 0.5, 0, sh - 1);
const y0 = Math.floor(sy);
const y1 = Math.min(y0 + 1, sh - 1);
const wy = sy - y0;
for (let x = 0; x < dw; x++) {
const sx = clamp((x + 0.5) * xRatio - 0.5, 0, sw - 1);
const x0 = Math.floor(sx);
const x1 = Math.min(x0 + 1, sw - 1);
const wx = sx - x0;
const top = src[y0 * sw + x0] * (1 - wx) + src[y0 * sw + x1] * wx;
const bot = src[y1 * sw + x0] * (1 - wx) + src[y1 * sw + x1] * wx;
out[y * dw + x] = top * (1 - wy) + bot * wy;
}
}
return out;
}
/**
* O(n) percentile for large non-negative arrays, by histogram.
*
* `quantile` sorts, which is correct and fine for a 256-value block but ruinous
* for an 18 MP plane: two sorts there cost 11.5 s against a 6.6 s denoise. Bins
* over [0, max] return a median accurate to ~0.2 on 8-bit data, far inside the
* noise being measured.
*
* `values` must be non-negative (magnitudes, gradients, residuals).
*/
export function fastPercentile(values: Float32Array, q: number, bins = 1024): number {
const n = values.length;
if (n === 0) return 0;
let max = 0;
for (let i = 0; i < n; i++) {
const v = values[i];
if (v > max) max = v;
}
if (!(max > 0)) return 0;
const hist = new Uint32Array(bins);
const scale = (bins - 1) / max;
for (let i = 0; i < n; i++) hist[(values[i] * scale) | 0]++;
const target = clamp(q, 0, 1) * (n - 1);
let seen = 0;
for (let b = 0; b < bins; b++) {
seen += hist[b];
if (seen > target) return b / scale;
}
return max;
}
/** Linear-interpolated quantile of a copy of `values`. `q` is 0..1. */
export function quantile(values: Float32Array | number[], q: number): number {
const n = values.length;
if (n === 0) return 0;
const sorted = Float32Array.from(values as ArrayLike<number>).sort();
const pos = clamp(q, 0, 1) * (n - 1);
const lo = Math.floor(pos);
const hi = Math.min(lo + 1, n - 1);
return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
}
+349
View File
@@ -0,0 +1,349 @@
/**
* The RGB proxy denoise pipeline: two scales, one gate.
*
* proxy -> YCbCr
* -> base: downscale RGB, run `runBase`, upscale
* -> luma: low-pass at the detail scale, gate per pixel
* -> reconstruct: crossfade luma to the base where the gate is closed,
* and take chroma from the base outright
*
* `runBase` is the only thing that knows how to denoise. Today it is a guided
* filter or NLM; when the ONNX session lands it is a tiled model runner and
* nothing else in this file changes. That is the seam the build plan is built
* around, and it is RGB so a colour-trained model is fed what it expects.
*
* The reconstruction invariant: output luma is a per-pixel crossfade between
* the untouched input (gate 1) and the denoised base (gate 0). It is bounded by
* its two inputs, so it cannot ring or overshoot, and where the gate opens the
* pixels are identical to the original.
*/
import { fromYcc, toYcc, type RgbImage } from './color.ts';
import {
DEFAULT_GATE,
detailGate,
structureMap,
type GateOptions,
} from './detail.ts';
import { estimateNoise, type NoiseModel } from './noise.ts';
import { boxBlur, clamp01, clamp, resample, smoothstep } from './planes.ts';
import type { BaseDenoiser, BaseImage } from './standin.ts';
export type DenoiserName = 'guided' | 'nlm' | 'onnx';
export interface DenoiseOptions {
/** 0..1 blend against the input, applied after reconstruction. */
amount: number;
/**
* Long edge of the plane the base denoiser runs on.
*
* Raising this on extreme-ISO frames looks like a free win on a detail metric
* (+0.07 retention at 3200 on 18 MP ISO 6400) but was rejected: the corpus
* guard measured grain 0.52 -> 1.30 and chroma 0.50 -> 1.20 at 3200. A sharper
* base is not more detail, it is grain the crossfade then has to keep.
*/
baseEdge: number;
/** Scale below which content is treated as detail worth protecting. */
detailRadius: number;
/**
* Radius of the second, coarser detail band. 0 disables it.
*
* The fine band (radius 2) is what the original gate judged, and it leaves
* near-isotropic 3-8 px texture unread: the texture that survives is the
* part that happens to be coherent at 2 px. The coarse band is the difference
* of two low-passes, so it sees that scale while rejecting both gradients and
* pixel-scale grain -- measured in docs/PLAN.md.
*/
coarseRadius: number;
/** Coarse-band thresholds, in fine-band noise units. */
coarseLo: number;
coarseHi: number;
/**
* Below this measured global grain the frame is clean and the pipeline tapers
* itself to an identity. Without it a base-ISO file loses real micro-texture
* to a denoise it never needed: measured at 36% of high-frequency energy on a
* clean ISO 100 D700 frame.
*/
cleanSigma: number;
gate: GateOptions;
}
export const DEFAULT_OPTIONS: DenoiseOptions = {
amount: 1,
baseEdge: 1600,
detailRadius: 2,
coarseRadius: 6,
coarseLo: 1.2,
coarseHi: 2.0,
cleanSigma: 2.5,
gate: DEFAULT_GATE,
};
export interface StageTimings {
noise: number;
base: number;
detail: number;
coarse: number;
structure: number;
reconstruct: number;
total: number;
}
export interface DenoiseStats {
width: number;
height: number;
baseWidth: number;
baseHeight: number;
/** How much the base plane was reduced, e.g. 3.25 for a 6000px proxy. */
backscale: number;
amount: number;
noise: { a: number; b: number; trend: 'fit' | 'flat'; global: number; atMid: number };
/** Mean gate value: the share of the frame given back as structure. */
gateCoverage: number;
/** How much of the requested amount survived the clean-image taper (0..1). */
autoGate: number;
timings: StageTimings;
}
export interface DenoiseOutput {
rgb: Uint8Array;
/** Luma of the denoised base, before detail re-injection, for inspection. */
base: { data: Float32Array; width: number; height: number };
stats: DenoiseStats;
}
const now = () => performance.now();
/**
* Prefiltered decimation of interleaved RGB to the base plane.
*
* The prefilter is load-bearing, and the coarse gate is what exposed it. A bare
* bilinear tap reads four of every ~42 source pixels at `backscale` 3.25, so
* pixel-scale grain is aliased into the base and comes back wherever the gate
* is closed. Measured on the three mid-ISO frames at sigma 6, with the coarse
* band on: grain 0.32/0.20/0.35 with bilinear against 0.22/0.20/0.22 with the
* box prefilter, for 1.9% less high-frequency energy. The gate protects detail
* and cannot protect grain out of an aliased base, so this belongs in the
* decimator rather than in a threshold.
*
* One channel at a time through the tested `resample`, so the peak extra memory
* is a single full-resolution plane, not three.
*/
function resampleRgb(
image: RgbImage,
width: number,
height: number,
prefilterRadius: number,
): BaseImage {
const out = new Float32Array(width * height * 3);
const src = new Float32Array(image.width * image.height);
for (let k = 0; k < 3; k++) {
for (let i = 0, p = k; i < src.length; i++, p += 3) src[i] = image.rgb[p];
if (prefilterRadius > 0) boxBlur(src, image.width, image.height, prefilterRadius, src);
const small = resample(src, image.width, image.height, width, height);
for (let i = 0, p = k; i < small.length; i++, p += 3) out[p] = small[i];
}
return { rgb: out, width, height };
}
/**
* Bilinear upscale of the base to full resolution, quantised to 8 bits so the
* tested `toYcc` can be reused rather than duplicating the colour maths here.
*/
function upsampleBase(base: BaseImage, width: number, height: number): RgbImage {
const rgb = new Uint8Array(width * height * 3);
const xRatio = base.width / width;
const yRatio = base.height / height;
for (let y = 0; y < height; y++) {
const sy = clamp((y + 0.5) * yRatio - 0.5, 0, base.height - 1);
const y0 = Math.floor(sy);
const y1 = Math.min(y0 + 1, base.height - 1);
const wy = sy - y0;
for (let x = 0; x < width; x++) {
const sx = clamp((x + 0.5) * xRatio - 0.5, 0, base.width - 1);
const x0 = Math.floor(sx);
const x1 = Math.min(x0 + 1, base.width - 1);
const wx = sx - x0;
const a = (y0 * base.width + x0) * 3;
const b = (y0 * base.width + x1) * 3;
const c = (y1 * base.width + x0) * 3;
const d = (y1 * base.width + x1) * 3;
const o = (y * width + x) * 3;
for (let k = 0; k < 3; k++) {
const top = base.rgb[a + k] * (1 - wx) + base.rgb[b + k] * wx;
const bot = base.rgb[c + k] * (1 - wx) + base.rgb[d + k] * wx;
const v = top * (1 - wy) + bot * wy;
rgb[o + k] = v < 0 ? 0 : v > 255 ? 255 : v + 0.5;
}
}
}
return { rgb, width, height };
}
export async function denoiseRgb(
image: RgbImage,
options: Partial<DenoiseOptions>,
runBase: BaseDenoiser,
): Promise<DenoiseOutput> {
const opts: DenoiseOptions = { ...DEFAULT_OPTIONS, ...options, gate: { ...DEFAULT_GATE, ...options.gate } };
const started = now();
const { width, height } = image;
const pixels = width * height;
const { y, cb, cr } = toYcc(image);
let mark = now();
const noise: NoiseModel = estimateNoise(y, width, height);
const timings: StageTimings = {
noise: now() - mark,
base: 0,
detail: 0,
coarse: 0,
structure: 0,
reconstruct: 0,
total: 0,
};
// --- base: the inference scale -------------------------------------------
const longEdge = Math.max(width, height);
const scale = opts.baseEdge > 0 ? Math.min(1, opts.baseEdge / longEdge) : 1;
const baseWidth = Math.max(8, Math.round(width * scale));
const baseHeight = Math.max(8, Math.round(height * scale));
const backscale = width / baseWidth;
mark = now();
const prefilterRadius = backscale > 1.001 ? Math.max(0, Math.round((backscale - 1) / 2)) : 0;
const baseInput = resampleRgb(image, baseWidth, baseHeight, prefilterRadius);
// What the base denoiser is told about the noise it will see.
//
// The decimator is box(W) followed by the two bilinear taps. Along one axis
// the taps overlap in W-1 samples at weight 1/W each and contribute
// (1-t)^2 + t^2 at the two ends, which averages 2/3 over t, so the per-axis
// *variance* gain is (W - 1/3) / W^2. Both axes are equal, so the standard
// deviation falls by the same factor squared, i.e. by that number again:
// 0.296 at W=3 against 1/backscale = 0.373.
//
// The old `/ backscale` was a guess -- and with bare bilinear (W=1) the true
// figure is 2/3, which is why it read ~2x low. The classical stand-ins never
// noticed (`planeSigma` re-measures each plane), but a model consumes this as
// a prior, so it has to describe the filter that actually ran.
const prefilterWidth = 2 * prefilterRadius + 1;
const decimatedSigma =
backscale > 1.001 ? (prefilterWidth - 1 / 3) / (prefilterWidth * prefilterWidth) : 1;
const baseSigma = noise.sigmaAt(110) * decimatedSigma;
const baseOut = await runBase(baseInput, baseSigma);
const baseUp = toYcc(upsampleBase(baseOut, width, height));
timings.base = now() - mark;
// --- detail gate at full resolution --------------------------------------
//
// The split filter is a plain low-pass, deliberately, and not an
// edge-preserving one. An edge-aware filter follows strong edges, which
// leaves them in the low band; the base cannot represent them after the
// downscale, and nothing would put them back -- measured as 41% of edge
// contrast lost. A low-pass pushes edges into `detail`, where the gate sees
// them as signal.
mark = now();
const smooth = boxBlur(y, width, height, opts.detailRadius);
const detail = new Float32Array(pixels);
for (let i = 0; i < pixels; i++) detail[i] = y[i] - smooth[i];
timings.detail = now() - mark;
mark = now();
// The tensor is measured on the *original* luma, not on `smooth`.
//
// `smooth` is the same 5x5 low-pass that defines the detail band, so 2-3 px
// texture has already been attenuated by the time the tensor sees it: the
// gate was judging fine texture with a measurement that could not see it, and
// coverage on a texture-rich frame came out *lower* than on a smooth one
// (3.8% vs 9.3%). `structureMap` resamples to half resolution first, which
// halves the noise while leaving 2 px structure intact, so this reads the
// scale it is being asked about.
const structure = structureMap(y, width, height, 2, 2, noise.global);
const coherence = resample(structure.data, structure.width, structure.height, width, height);
const sigmaMap = new Float32Array(pixels);
for (let i = 0; i < pixels; i++) sigmaMap[i] = noise.sigmaAt(smooth[i]);
timings.structure = now() - mark;
mark = now();
let gate = detailGate(detail, width, height, sigmaMap, coherence, opts.gate);
// Second, coarser band: `smooth2 - smooth6` is a band-pass around 3-8 px. It
// rejects gradients (both low-passes follow them) and pixel-scale grain (both
// average it), so it can open on texture that the fine band reads as noise
// without opening on flat noisy sky. The isolated-point path is a fine-band
// instrument and is deliberately disabled here.
if (opts.coarseRadius > opts.detailRadius && opts.coarseHi > opts.coarseLo) {
const coarseSmooth = boxBlur(y, width, height, opts.coarseRadius);
const coarse = new Float32Array(pixels);
for (let i = 0; i < pixels; i++) coarse[i] = smooth[i] - coarseSmooth[i];
const coarseGate = detailGate(coarse, width, height, sigmaMap, coherence, {
...opts.gate,
lo: opts.coarseLo,
hi: opts.coarseHi,
pointHi: 0,
});
for (let i = 0; i < pixels; i++) if (coarseGate[i] > gate[i]) gate[i] = coarseGate[i];
timings.coarse = now() - mark;
}
// Clean frames get their amount tapered to nothing: 0.8 sigma of measured
// grain is quantisation, 2.5 is a genuinely noisy file.
const autoGate = opts.cleanSigma > 0 ? smoothstep(0.8, opts.cleanSigma, noise.global) : 1;
const amount = clamp01(opts.amount) * autoGate;
const outY = new Float32Array(pixels);
const outCb = new Float32Array(pixels);
const outCr = new Float32Array(pixels);
let gateSum = 0;
for (let i = 0; i < pixels; i++) {
gateSum += gate[i];
// Crossfade, never additive re-injection: additive detail lands on top of a
// base that already contains a softened copy of the same edge and overshoots
// by ~40%. A crossfade is bounded by its two inputs, so it cannot ring, and
// where the gate opens the pixels are bit-identical to the original.
outY[i] = y[i] + amount * (1 - gate[i]) * (baseUp.y[i] - y[i]);
// Chroma follows the same gate, for a different reason than luma does. The
// base carries chroma upsampled from `backscale` times smaller, so replacing
// it outright smears colour across every sharp edge: on a small aircraft
// against bright sky that is a magenta fringe along the wing and red/white
// paint that loses its boundary. Keeping the original chroma where the gate
// says "structure" keeps the paint edge registered with the luma edge it
// belongs to. Flat areas still take the base chroma, which is where the
// chroma noise lives.
outCb[i] = cb[i] + amount * (1 - gate[i]) * (baseUp.cb[i] - cb[i]);
outCr[i] = cr[i] + amount * (1 - gate[i]) * (baseUp.cr[i] - cr[i]);
}
const rgb = fromYcc({ y: outY, cb: outCb, cr: outCr }, width, height);
timings.reconstruct = now() - mark;
timings.total = now() - started;
const baseLuma = new Float32Array(baseWidth * baseHeight);
for (let i = 0, p = 0; i < baseLuma.length; i++, p += 3) {
baseLuma[i] = 0.299 * baseOut.rgb[p] + 0.587 * baseOut.rgb[p + 1] + 0.114 * baseOut.rgb[p + 2];
}
return {
rgb,
base: { data: baseLuma, width: baseWidth, height: baseHeight },
stats: {
width,
height,
baseWidth,
baseHeight,
backscale,
amount,
noise: {
a: noise.a,
b: noise.b,
trend: noise.trend,
global: noise.global,
atMid: noise.sigmaAt(110),
},
gateCoverage: gateSum / pixels,
autoGate,
timings,
},
};
}
+166
View File
@@ -0,0 +1,166 @@
/**
* Stand-in denoisers for the reduced-resolution base.
*
* These occupy exactly the slot the ONNX model occupies: take an interleaved
* RGB plane at inference scale plus the noise level there, return a denoised
* plane of the same shape. Having credible classical implementations in that
* slot is what lets the pipeline, the harness and the baselines be finished and
* measured before a model exists -- and they are the numbers the model has to
* beat.
*
* The seam is RGB, not luma, deliberately: a denoiser trained on colour images
* fed a replicated greyscale plane is out of distribution and underperforms a
* plain guided filter. Chroma also comes from this plane, so the model gets a
* say in colour noise, which is the part users actually complain about.
*
* `nlm` is the honest reference. `guided` is fast enough to iterate against.
*/
import { guidedFilter } from './detail.ts';
import { boxBlur } from './planes.ts';
export interface BaseImage {
/** Interleaved RGB, `width * height * 3`, 0..255. */
rgb: Float32Array;
width: number;
height: number;
}
/**
* Synchronous for the classical stand-ins, a promise for a model session.
* ONNX inference cannot be made synchronous, so the seam allows both and the
* pipeline awaits the result.
*/
export type BaseDenoiser = (image: BaseImage, sigma: number) => BaseImage | Promise<BaseImage>;
export function deinterleave(image: BaseImage): [Float32Array, Float32Array, Float32Array] {
const n = image.width * image.height;
const r = new Float32Array(n);
const g = new Float32Array(n);
const b = new Float32Array(n);
for (let i = 0, p = 0; i < n; i++, p += 3) {
r[i] = image.rgb[p];
g[i] = image.rgb[p + 1];
b[i] = image.rgb[p + 2];
}
return [r, g, b];
}
export function interleave(
r: Float32Array,
g: Float32Array,
b: Float32Array,
width: number,
height: number,
): BaseImage {
const rgb = new Float32Array(width * height * 3);
for (let i = 0, p = 0; i < r.length; i++, p += 3) {
rgb[p] = r[i];
rgb[p + 1] = g[i];
rgb[p + 2] = b[i];
}
return { rgb, width, height };
}
/**
* Robust sigma of one plane, from its own 3x3 high-pass.
*
* The caller's `sigma` is a luma figure, and per-channel noise differs a lot on
* a CFA sensor -- blue is the noisiest -- so filtering all three at the luma
* level over-smooths one channel and under-smooths another. Measuring each
* plane costs three cheap passes at base scale and removes the guesswork.
*/
function planeSigma(plane: Float32Array, width: number, height: number, fallback: number): number {
const smooth = boxBlur(plane, width, height, 1);
const residual = new Float32Array(plane.length);
for (let i = 0; i < plane.length; i++) residual[i] = Math.abs(plane[i] - smooth[i]);
const sorted = residual.sort();
const median = sorted[sorted.length >> 1] ?? 0;
const sigma = (median * 1.4826) / 0.943;
return sigma > 0.5 ? sigma : Math.max(1, fallback);
}
/** Guided filter per channel: cheap, edge-preserving, mildly waxy. */
export function guidedDenoiser(radius = 3, strength = 2.6): BaseDenoiser {
return (image, sigma) => {
const [r, g, b] = deinterleave(image);
const filter = (plane: Float32Array) => {
const s = planeSigma(plane, image.width, image.height, sigma);
return guidedFilter(plane, image.width, image.height, radius, (strength * s) ** 2);
};
return interleave(filter(r), filter(g), filter(b), image.width, image.height);
};
}
/**
* Non-local means, per channel. Slow, and deliberately so: it is the quality
* reference the neural model must beat, not a shipping path.
*/
export function nlmDenoiser(search = 2, patch = 1): BaseDenoiser {
const patchW = 2 * patch + 1;
const patchArea = patchW * patchW;
return (image) => {
const [r, g, b] = deinterleave(image);
const planes = [r, g, b].map(
(plane) => nlmPlane(plane, image.width, image.height, search, patch, patchW, patchArea),
);
return interleave(planes[0], planes[1], planes[2], image.width, image.height);
};
}
function nlmPlane(
plane: Float32Array,
width: number,
height: number,
search: number,
patch: number,
patchW: number,
patchArea: number,
): Float32Array {
const out = new Float32Array(plane.length);
const s = Math.max(1, search | 0);
const clampX = (v: number) => (v < 0 ? 0 : v >= width ? width - 1 : v);
const clampY = (v: number) => (v < 0 ? 0 : v >= height ? height - 1 : v);
let sumSq = 0;
let count = 0;
for (let i = 0; i < plane.length; i += 7) {
sumSq += plane[i] * plane[i];
count++;
}
const h = Math.max(2, Math.sqrt(sumSq / Math.max(1, count)) * 0.18);
const cutoff = 4 * h * h;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const centre = plane[y * width + x];
let acc = 0;
let weight = 0;
for (let dy = -s; dy <= s; dy++) {
for (let dx = -s; dx <= s; dx++) {
if (dx === 0 && dy === 0) continue;
const ny = y + dy;
const nx = x + dx;
if (ny < 0 || ny >= height || nx < 0 || nx >= width) continue;
let dist = 0;
for (let py = -patch; py <= patch; py++) {
const ay = clampY(y + py) * width;
const by = clampY(ny + py) * width;
for (let px = -patch; px <= patch; px++) {
const d = plane[ay + clampX(x + px)] - plane[by + clampX(nx + px)];
dist += d * d;
}
}
dist /= patchArea;
if (dist > cutoff) continue;
const w = Math.exp(-dist / (h * h));
acc += w * plane[ny * width + nx];
weight += w;
}
}
out[y * width + x] = (acc + centre) / (weight + 1);
}
}
return out;
}