feat: chroma prefilter and gating

This commit is contained in:
zhoubinjia committed 2026-11-06 16:06:41 +08:00
1 parent 3cf0f975e7
commit 172db82a80
7 files changed
+147 -93

No files matched your search

@@ -235,8 +235,7 @@ internal object PhotonDenoiseShaders {
uniform sampler2D uNoisyCoarse;
uniform ivec2 uSize;
uniform ivec2 uCoarseSize;
uniform float uAmount;
uniform ivec2 uSampleOrigin;
uniform ivec2 uSampleOrigin;
uniform ivec2 uExtent;
$UPSAMPLE
$MODEL_NOISE
@@ -244,49 +243,52 @@ internal object PhotonDenoiseShaders {
"""
/**
* §6.0 level-0 outlier correction: a luma sample far from its 3×3 median whose deviation has at
* most PREFILTER_GUARD same-signed neighbours (a dot, not a line) in a noise-like neighbourhood
* (mean L0² of the 5×5 ring below PREFILTER_FLAT σ²) is moved to the median, scaled by
* uAmount = min(luma strength, 1). Writes that correction (R32F, 0 elsewhere); σ² is the L0
* model noise times the §5.1 strength at the noisy base. Per row strip this program writes the
* samples (fine luma, L rounded to float16, σ²) of the strip and its border, [PREFILTER] the
* §6.0 level-0 outlier correction, per channel of Y, Cb, Cr: a sample far from its 3×3 median
* whose deviation has at most PREFILTER_GUARD same-signed neighbours (a dot, not a line) in a
* noise-like neighbourhood (mean L0² of the 5×5 ring below PREFILTER_FLAT σ²) is moved to the
* median, scaled by uAmounts (min(luma strength, 1), min(chroma strength, 1) twice; 0 switches a
* channel off). Writes that correction (RGBA32F, 0 elsewhere); σ² is the L0 model noise times
* the §5.1 strength at the noisy base. Per row strip this program writes the samples of the
* strip and its border, fine (RGBA32F) and L rounded to float16 (RGBA16F); [PREFILTER] the
* correction.
*/
val PREFILTER_SAMPLES = """
#version 310 es
$PREFILTER_COMMON
layout(rgba32f, binding = 0) writeonly uniform highp image2D uSamplesOut;
layout(rgba16f, binding = 1) writeonly uniform highp image2D uLapOut;
void main() {
ivec2 t = globalId();
if (any(greaterThanEqual(t, uExtent))) return;
ivec2 p = mirror2(uSampleOrigin + t, uSize);
float fine = working0(p).x;
vec3 base = upAt(uNoisyCoarse, p);
vec3 mu;
float noise = modelNoise(p, base, mu).x * strengthAt(base.x).x;
float lap = unpackHalf2x16(packHalf2x16(vec2(fine - base.x, 0.0))).x;
imageStore(uSamplesOut, t, vec4(fine, lap, noise, 0.0));
vec3 fine = working0(p);
vec3 lap = fine - upAt(uNoisyCoarse, p);
vec2 lapXy = unpackHalf2x16(packHalf2x16(lap.xy));
float lapZ = unpackHalf2x16(packHalf2x16(vec2(lap.z, 0.0))).x;
imageStore(uSamplesOut, t, vec4(fine, 0.0));
imageStore(uLapOut, t, vec4(lapXy, lapZ, 0.0));
}
""".trimIndent()
/** §6.0 correction of the strip rows from the [PREFILTER_SAMPLES] image (uSamples). */
/** §6.0 correction of the strip rows from the [PREFILTER_SAMPLES] images (uSamples, uLaps). */
val PREFILTER = """
#version 310 es
$PREFILTER_COMMON
uniform sampler2D uSamples;
uniform sampler2D uLaps;
uniform ivec2 uOutputOrigin; // pixel of texel 0
layout(r32f, binding = 0) writeonly uniform highp image2D uDelta;
uniform vec3 uAmounts;
layout(rgba32f, binding = 0) writeonly uniform highp image2D uDelta;
// Raw coordinates: the samples hold the values of the mirrored coordinate.
vec4 sampleAt(ivec2 c) { return texelFetch(uSamples, c - uSampleOrigin, 0); }
// Raw coordinates: the samples hold the values of the mirrored coordinate. mask selects the
// channel without dynamic vector indexing.
float fineAt(ivec2 c, vec3 mask) { return dot(texelFetch(uSamples, c - uSampleOrigin, 0).rgb, mask); }
float lapAt(ivec2 c, vec3 mask) { return dot(texelFetch(uLaps, c - uSampleOrigin, 0).rgb, mask); }
void main() {
ivec2 t = globalId();
if (any(greaterThanEqual(t, uExtent))) return;
ivec2 p = uOutputOrigin + t;
float correction(ivec2 p, vec3 mask, float noise) {
float v[9];
for (int j = 0; j < 9; ++j) v[j] = sampleAt(p + ivec2(j % 3 - 1, j / 3 - 1)).x;
for (int j = 0; j < 9; ++j) v[j] = fineAt(p + ivec2(j % 3 - 1, j / 3 - 1), mask);
for (int i = 1; i < 9; ++i) {
float x = v[i];
int j = i - 1;
@@ -297,32 +299,41 @@ internal object PhotonDenoiseShaders {
v[j + 1] = x;
}
float m = v[4];
vec4 centre = sampleAt(p);
float fineP = centre.x;
float sigma = sqrt(centre.z);
float fineP = fineAt(p, mask);
float sigma = sqrt(noise);
float dev = fineP - m;
float delta = 0.0;
if (sigma > 0.0 && abs(dev) > $PREFILTER_K * sigma) {
int count = 0;
for (int j = 0; j < 9; ++j) {
if (j == 4) continue;
float d = sampleAt(p + ivec2(j % 3 - 1, j / 3 - 1)).x - m;
if (abs(d) > $PREFILTER_K * sigma && sign(d) == sign(dev)) ++count;
}
if (count <= $PREFILTER_GUARD) {
float sum = 0.0;
for (int dy = -2; dy <= 2; ++dy) {
for (int dx = -2; dx <= 2; ++dx) {
float l = sampleAt(p + ivec2(dx, dy)).y;
sum += l * l;
}
}
float lp = centre.y;
float energy = (sum - lp * lp) / 24.0;
if (energy < $PREFILTER_FLAT * sigma * sigma) delta = (m - fineP) * uAmount;
if (!(sigma > 0.0) || abs(dev) <= $PREFILTER_K * sigma) return 0.0;
int count = 0;
for (int j = 0; j < 9; ++j) {
if (j == 4) continue;
float d = fineAt(p + ivec2(j % 3 - 1, j / 3 - 1), mask) - m;
if (abs(d) > $PREFILTER_K * sigma && sign(d) == sign(dev)) ++count;
}
if (count > $PREFILTER_GUARD) return 0.0;
float sum = 0.0;
for (int dy = -2; dy <= 2; ++dy) {
for (int dx = -2; dx <= 2; ++dx) {
float l = lapAt(p + ivec2(dx, dy), mask);
sum += l * l;
}
}
imageStore(uDelta, p, vec4(delta, 0.0, 0.0, 0.0));
float lp = lapAt(p, mask);
float energy = (sum - lp * lp) / 24.0;
return energy < $PREFILTER_FLAT * sigma * sigma ? m - fineP : 0.0;
}
void main() {
ivec2 t = globalId();
if (any(greaterThanEqual(t, uExtent))) return;
ivec2 p = uOutputOrigin + t;
vec3 base = upAt(uNoisyCoarse, p);
vec3 mu;
vec3 noise = modelNoise(p, base, mu).xyz * strengthAt(base.x);
vec3 delta = vec3(0.0);
if (uAmounts.x > 0.0) delta.x = correction(p, vec3(1.0, 0.0, 0.0), noise.x) * uAmounts.x;
if (uAmounts.y > 0.0) delta.y = correction(p, vec3(0.0, 1.0, 0.0), noise.y) * uAmounts.y;
if (uAmounts.z > 0.0) delta.z = correction(p, vec3(0.0, 0.0, 1.0), noise.z) * uAmounts.z;
imageStore(uDelta, p, vec4(delta, 0.0));
}
""".trimIndent()
@@ -812,7 +823,7 @@ internal object PhotonDenoiseShaders {
}
float gateY = sumS2 > 0.0 ? smoothstep(uGateLuma.x, uGateLuma.y, 9.0 * sumL2 / max(sumS2, 1e-30)) : 1.0;
float stat = mahalanobis(lap.yz, noise);
float gateC = stat >= 0.0 ? smoothstep(uGateChroma.x, uGateChroma.y, stat) : 1.0;
float gateC = uChromaGate == 0 ? 0.0 : stat >= 0.0 ? smoothstep(uGateChroma.x, uGateChroma.y, stat) : 1.0;
float gate = max(gateY, gateC);
chromaBand = (uChromaStrength * gate + (1.0 - uChromaStrength)) * lap.yz;
@@ -863,7 +874,7 @@ internal object PhotonDenoiseShaders {
$UPSAMPLE
$MODEL_NOISE
$STRENGTH_LOOKUP
// §6.0 level-0 isolated-outlier correction of the input luma (PREFILTER); used when FINE_IS_INPUT.
// §6.0 level-0 isolated-outlier correction of the input Y, Cb, Cr (PREFILTER); used when FINE_IS_INPUT.
uniform sampler2D uPrefilter;
uniform float uOutlier;
uniform float uAlpha;
@@ -872,6 +883,7 @@ internal object PhotonDenoiseShaders {
uniform float uChromaStrength; // min(s, 1)
uniform vec2 uGateLuma;
uniform vec2 uGateChroma;
uniform int uChromaGate; // §7.2 Mahalanobis gate on at this level
uniform float uBilateralLuma;
uniform float uBilateralChroma;
@@ -889,7 +901,7 @@ internal object PhotonDenoiseShaders {
// Level 0 reads the input at uLevel = 0: one gain serves the input and the clip test.
vec3 gain = lscGain(levelCentre(p, uLevel));
vec3 fine = FINE_IS_INPUT ? working0Gain(p, gain) : texelFetch(uFine, p, 0).rgb;
if (FINE_IS_INPUT && PREFILTER_ENABLED) fine.x += texelFetch(uPrefilter, p, 0).r;
if (FINE_IS_INPUT && PREFILTER_ENABLED) fine += texelFetch(uPrefilter, p, 0).rgb;
base = upDenoised(p);
lap = fine - upNoisy(p);
vec3 mu;
@@ -32,6 +32,8 @@ internal object PhotonDenoiseTuning {
val gateLuma: FloatArray,
/** Chroma Mahalanobis gate (χ²₂ quantiles). */
val gateChroma: FloatArray,
/** First level whose chroma detail the Mahalanobis gate may keep; finer ones use the luma gate only (§7.2). */
val chromaGateFrom: Int,
/** Coarsest chroma levels receiving the luma-guided joint bilateral (§7.3). */
val bilateralLevels: Int,
val bilateralLuma: Float,
@@ -63,6 +65,9 @@ internal object PhotonDenoiseTuning {
outlier = floatArrayOf(2.5f, 2.5f, 2.5f, 2.5f, 2.5f, 2.5f, 2.5f),
gateLuma = floatArrayOf(16.919f, 27.877f),
gateChroma = floatArrayOf(5.991f, 13.816f),
// At L0 / L1 the χ²₂ tail of demosaic-clustered chroma noise opens the gate as isolated
// colour dots (ISO 9100, 8 frames: all of them); real colour edges there carry luma (§7.2).
chromaGateFrom = 2,
bilateralLevels = 3,
bilateralLuma = 4f,
bilateralChroma = 4f,
@@ -123,7 +128,7 @@ internal object PhotonDenoiseTuning {
),
chroma = rows(
1f, 1f, 1f,
1f, 1f, 1f,
2f, 2f, 1f,
4f, 3f, 0.75f,
12f, 8f, 1.5f,
24f, 16f, 2f,
@@ -151,6 +156,7 @@ internal object PhotonDenoiseTuning {
outlier = mix(a.outlier, b.outlier),
gateLuma = mix(a.gateLuma, b.gateLuma),
gateChroma = mix(a.gateChroma, b.gateChroma),
chromaGateFrom = if (f < 0.5f) a.chromaGateFrom else b.chromaGateFrom,
bilateralLevels = if (f < 0.5f) a.bilateralLevels else b.bilateralLevels,
bilateralLuma = a.bilateralLuma + f * (b.bilateralLuma - a.bilateralLuma),
bilateralChroma = a.bilateralChroma + f * (b.bilateralChroma - a.bilateralChroma),
@@ -122,7 +122,7 @@ internal class PhotonMultiScaleDenoiser {
sink: PassSink? = null,
): Int? {
if (!initialize()) return null
val prefilterEnabled = params.lumaLevels > 0 && params.lumaStrength > 0f
val prefilterEnabled = prefilterAmounts(params).any { it > 0f }
val variants = List(params.levels) { level ->
val chroma = params.chromaStrength > 0f
PhotonSynthesisVariant(
@@ -201,7 +201,7 @@ internal class PhotonMultiScaleDenoiser {
prefilterTexture = 0
if (prefilterEnabled) {
prefilterTexture = texture(sizes[0], GLES30.GL_R32F)
prefilterTexture = texture(sizes[0], GLES30.GL_RGBA32F)
timing.gpu("prefilter", "L0 ${width}x$height") { prefilter(frame, prefilterTexture) }
sink?.onPass("prefilter0", prefilterTexture, 0, 0, width, height, true)
}
@@ -251,8 +251,9 @@ internal class PhotonMultiScaleDenoiser {
}
/**
* §6.0 per row strip: the luma samples (fine, rounded L, σ²) of the strip plus PREFILTER_BORDER
* into the strip noise image, then the correction of the strip's rows into [target].
* §6.0 per row strip: the samples of the strip plus PREFILTER_BORDER, fine Y/Cb/Cr into the
* strip noise image and L rounded to float16 into the strip lap image, then the correction of
* the strip's rows into [target].
*/
private fun prefilter(frame: SynthesisFrame, target: Int) {
val strips = frame.strips
@@ -268,16 +269,19 @@ internal class PhotonMultiScaleDenoiser {
uniform2i(prefilterSamplesProgram, "uSampleOrigin", sampleOrigin)
uniform2i(prefilterSamplesProgram, "uExtent", sampleExtent)
bindImage(0, strips.noise, GLES30.GL_RGBA32F)
bindImage(1, strips.lap, GLES30.GL_RGBA16F)
dispatch(prefilterSamplesProgram, sampleExtent)
val extent = intArrayOf(size[0], rows)
GLES31.glUseProgram(prefilterProgram)
bindPrefilter(prefilterProgram, frame)
bindSampler(prefilterProgram, "uSamples", UNIT_NOISE, strips.noise)
bindSampler(prefilterProgram, "uLaps", UNIT_LAP, strips.lap)
uniform3f(prefilterProgram, "uAmounts", prefilterAmounts(frame.params))
uniform2i(prefilterProgram, "uSampleOrigin", sampleOrigin)
uniform2i(prefilterProgram, "uOutputOrigin", intArrayOf(0, y))
uniform2i(prefilterProgram, "uExtent", extent)
bindImage(0, target, GLES30.GL_R32F)
bindImage(0, target, GLES30.GL_RGBA32F)
dispatch(prefilterProgram, extent)
GlesGpuScheduler.yieldToUiRenderer()
y += rows
@@ -291,7 +295,13 @@ internal class PhotonMultiScaleDenoiser {
bindSampler(program, "uNoisyCoarse", UNIT_NOISY_COARSE, frame.gaussians[1])
uniform2i(program, "uSize", frame.sizes[0])
uniform2i(program, "uCoarseSize", frame.sizes[1])
uniform1f(program, "uAmount", minOf(params.lumaStrength, 1f))
}
/** §6.0 correction scale of Y, Cb, Cr; 0 where that channel is not denoised. */
private fun prefilterAmounts(params: PhotonDenoiseParams): FloatArray {
val luma = if (params.lumaLevels > 0) minOf(params.lumaStrength, 1f) else 0f
val chroma = minOf(params.chromaStrength, 1f)
return floatArrayOf(maxOf(luma, 0f), maxOf(chroma, 0f), maxOf(chroma, 0f))
}
/**
@@ -554,6 +564,7 @@ internal class PhotonMultiScaleDenoiser {
uniform1f(program, "uGrain", params.lumaGrain(level))
uniform1f(program, "uGamma", params.gamma[level])
uniform1f(program, "uChromaStrength", minOf(params.chromaStrength, 1f))
uniform1i(program, "uChromaGate", if (level >= params.chromaGateFrom) 1 else 0)
val thresholdScale = params.chromaThresholdScale()
GLES31.glUniform2f(location(program, "uGateLuma"),
params.gateLuma[0] * thresholdScale, params.gateLuma[1] * thresholdScale)
@@ -66,6 +66,7 @@ internal class PhotonDenoiseParams(
val outlier: FloatArray,
val gateLuma: FloatArray,
val gateChroma: FloatArray,
val chromaGateFrom: Int,
val bilateralLevels: Int,
val bilateralLuma: Float,
val bilateralChroma: Float,
@@ -152,6 +153,7 @@ internal class PhotonDenoiseParams(
put("outlier", JSONArray(outlier.map(Float::toDouble)))
put("gateLuma", JSONArray(gateLuma.map(Float::toDouble)))
put("gateChroma", JSONArray(gateChroma.map(Float::toDouble)))
put("chromaGateFrom", chromaGateFrom)
put("bilateralLevels", bilateralLevels)
put("bilateralLuma", bilateralLuma.toDouble())
put("bilateralChroma", bilateralChroma.toDouble())
@@ -350,6 +352,7 @@ internal object PhotonNoiseModel {
outlier = tuning.outlier.copyOf(levels),
gateLuma = tuning.gateLuma.copyOf(),
gateChroma = tuning.gateChroma.copyOf(),
chromaGateFrom = tuning.chromaGateFrom,
bilateralLevels = tuning.bilateralLevels,
bilateralLuma = tuning.bilateralLuma,
bilateralChroma = tuning.bilateralChroma,
+20 -10
View File
@@ -205,12 +205,12 @@ G_l = L_l + ↑2 (2h * G_{l+1}) (按构造完美重建)
| 上限(SNR 5 / 20 / 40) | 亮度 | 色度 |
|---|---|---|
| L0 | 2 / 1.5 / 0.75 | 1 / 1 / 1 |
| L1 | 4 / 3 / 1.25 | 1 / 1 / 1 |
| L1 | 4 / 3 / 1.25 | 2 / 2 / 1 |
| L2 | 8 / 6 / 2.5 | 4 / 3 / 0.75 |
| L3 | 16 / 12 / 5 | 12 / 8 / 1.5 |
| L4 | 24 / 18 / 6 | 24 / 16 / 2 |
节点 40 来自 ISO 100 纹理场景;节点 5 / 20 高于 10x 镜头 ISO 9100 合成(SNR 12–16)的估计:亮度 L3 约 10、L4 约 15–20,色度 L3 约 7、L4 约 13。最初的上限(节点 20 处亮度 L3 7、色度 L3 2.5)把这些截到一半以下,色斑残留明显。节点 20–40 之间还没有实拍样本。
节点 40 来自 ISO 100 纹理场景;节点 5 / 20 高于 10x 镜头 ISO 9100 合成(SNR 12–16)的估计:亮度 L3 约 10、L4 约 15–20,色度 L3 约 7、L4 约 13。最初的上限(节点 20 处亮度 L3 7、色度 L3 2.5)把这些截到一半以下,色斑残留明显。节点 20–40 之间还没有实拍样本。色度 L1 原先各节点都是 1;8 帧合成 ISO 9100 暗光(SNR 16.5)去掉上限后,暗到中间调各档估计为 1.06–1.92,被截到 1 时 L1 彩噪只压掉约 55–70%,因此 SNR 5 / 20 放到 2。同一图最亮两档估到 5–9,来自显示器摩尔纹,仍被上限挡住。
**整图 SNR** 与 MGC FinishRaw 的定义相同:`SNR = S / √(m_s·s_G·S + m_r·r_G)`,`S` 为平均绿色信号(MGC EstimateSnr:中央 3/4、每 8 行取样、√信号均值的平方,归一化、未白平衡),`r_G, s_G` 为档案的绿色系数,`m` 为 §2.2 的名义合成方差比。`S` 取本次渲染在 CPU 像素上测得的值(`RawMetadata.denoiseSignal`,与锐化 SNR 同一次测量);像素只在 GPU 上的合成默认降噪取合成器测得的参考帧信号乘输出曝光(`RawDenoiseHistory.signal`,随记录持久化);两者都没有时按 MGC 取 0.18。
@@ -242,19 +242,21 @@ G_l = L_l + ↑2 (2h * G_{l+1}) (按构造完美重建)
### 6.0 第 0 层离群点预滤波
去马赛克让噪声在空间上相关,暗部出现 2–3 像素的小团(输入 L0 带中约 2.5–3σ)。§6.1 的窗口里,团内各点互为高权重邻点,能量由小团自身撑起,收缩后成片保留,提亮后可见。把 Huber 基准换成 3×3 中值无效(实测斑点数不降),因此在分解前对第 0 层亮度做条件中值:
去马赛克让噪声在空间上相关,暗部出现 2–3 像素的小团(输入 L0 带中约 2.5–3σ)。§6.1 的窗口里,团内各点互为高权重邻点,能量由小团自身撑起,收缩后成片保留,提亮后可见。把 Huber 基准换成 3×3 中值无效(实测斑点数不降),因此在分解前对第 0 层做条件中值。`Y`、`Cb`、`Cr` 三个通道各自独立判定,`c` 表示其中一个通道:
```
m = G0_Y 的 3×3 中值
σ² = §2.1 第 0 层亮度模型方差 × §5.1 强度(在未降噪的 ↑G1 上)
替换条件:|G0_Y − m| > 2.5σ
m = G0_c 的 3×3 中值
σ² = §2.1 第 0 层 c 通道模型方差 × §5.1 c 通道强度(在未降噪的 ↑G1 上)
替换条件:|G0_c − m| > 2.5σ
且 3×3 内与中心同号、偏离超过 2.5σ 的邻点不多于 2 个(线条至少有 2 个,保留)
且 5×5 内 L0² 的均值(不含中心)< 3σ²(邻域像噪声;纹理区远高于此)
G0_Y += (m − G0_Y) · min(s_Y, 1)
且 5×5 内 L0_c² 的均值(不含中心)< 3σ²(邻域像噪声;纹理区远高于此)
G0_c += (m − G0_c) · a_c,a_Y = min(s_Y, 1)(亮度未降噪时为 0),a_Cb = a_Cr = min(s_C, 1)
```
只改第 0 层的细节层输入(`G1` 及更粗的层仍来自原图,强度估计在预滤波之前)。实拍(4096×3072 单帧 ISO 694,暗部提亮约 40 倍):替换约 2.6% 的像素,斑点数 772 → 28;纹理区(灯阵、标识文字)与原输出的相对均方差约 2%,肉眼无差别。门限按模型 σ 而不是邻域 MAD:MAD 混入低频起伏,同样参数下只减少到 338。
色度通道:高 ISO 多帧合成后,暗部残留孤立的饱和红/蓝单像素。它们是稀疏的脉冲,§5.1 的中位数估计不受其影响;单点幅度又远超 σ,Wiener 收缩也保留。只做亮度预滤波时,这些彩点照样留下。实拍(4096×3072、8 帧合成、ISO 9100,暗部提亮 8–20 倍):`Cb`/`Cr` 各替换约 1.1–1.3% 的像素,两块暗区的彩点数 5725 → 3491、5353 → 2871,饱和彩点基本消失,余下的是淡的约 2 像素软斑。
### 6.1 逐层收缩:两阶段经验 Wiener
对 `L = L_{Y,l}(p)`,`σ² = σ²_{Y,l}(p)`:
@@ -316,6 +318,14 @@ out = gate · L_C
`ζ_Y` 使用亮度 pilot(已收缩的亮度带)与其模型方差:用带噪亮度带时,一个亮度噪声点会打开色度门,留下彩色点。pilot 在融合 dispatch 的共享内存中已有,亮度与色度仍在同一 dispatch 内完成。
`ζ_C` 只从第 `chromaGateFrom = 2` 层起参与,L0 / L1 的色度细节只由 `ζ_Y` 打开。原因:去马赛克与多帧合成后,细层色度噪声在空间上成团、尾部重,χ²₂ 门的尾部在暗部大面积开门,留下的就是提亮后的孤立彩点。实拍(4096×3072、8 帧合成、ISO 9100,暗部提亮 15–34 倍)三块暗区:
- 按单像素马氏距离(现状):彩点 2207 / 1050 / 1273;
- 去掉 `ζ_Y`、保留 `ζ_C`:数量不变;去掉 `ζ_C`:全部消失,说明彩点只来自 `ζ_C`;
- 只在 L0 关 `ζ_C`:1655 / 598 / 774;L0、L1 都关:1 / 0 / 1;
- 改为 3×3 累加的马氏距离(χ²₁₈ 分位):只降到 2015 / 852 / 947,色度噪声成团,邻域累加同样超阈。
代价是 L0 / L1 上不伴随亮度边界的颜色边缘不再单独保留。ISO 694 人像上,唇边、眼周的色度变化 rms 约为信号的 0.65%,1:1 并排看不出差别。
### 7.3 粗层联合双边滤波
亮度门控只处理细节层;低频色斑存在于粗层的高斯层本身。对色度最粗的 2–3 层,在 `base_C` 上额外做亮度引导的联合双边滤波:
@@ -367,7 +377,7 @@ Bitmap / JPEG 已经过 ISP:即使关闭机内降噪与锐化,输出的噪
| 3 | Analyze₁…N | `G_l → G_{l+1}`,亮度与色度两组滤波器同一 dispatch 输出 |
| 3a | Estimate₀…N−1 | §5.1 每层抽样、平坦门、按 (亮度档, 通道) 统计直方图:每个工作组在共享内存累加 64×64 个样本后并入全局 SSBO;参数已带强度表时跳过 |
| 3b | Resolve | §5.1 直方图 → 强度表 SSBO(中位数、跨档填补、上层回退、上限),一个工作组;需要记录时回读(默认降噪写入历史、调试导出) |
| 3c | Prefilter₀ | §6.0 第 0 层亮度条件中值,输出 `R32F` 修正量(`r16f` 不在 GLES 3.1 image 核心格式内),第 0 层合成读入时加到 `Y` 上;亮度强度为 0 时跳过 |
| 3c | Prefilter₀ | §6.0 第 0 层 `Y`/`Cb`/`Cr` 条件中值,输出 `RGBA32F` 修正量,第 0 层合成读入时加到三个通道上;亮度与色度强度都为 0 时跳过 |
| 4 | Synthesize_{N−1…1} | 每层一个融合 dispatch:共享内存分块计算 `L_l`、`base`、§2.1 协方差与亮度 pilot,再做第二阶段收缩 + 色度门控 + 粗层联合双边,输出 `G̃_l` |
| 5 | Synthesize₀ + Output | 第 0 层同一融合 dispatch,与 `M⁻¹ / K⁻¹ / W⁻¹`、乘回 `g` 合并,直接写相机 RGB 输出纹理 |
@@ -546,7 +556,7 @@ Spatial Bayer 合成后去马赛克所用的噪声档案(`spatialOutputNoiseMe
- 盲改写法(tile、`exp` 分解、取模快速路径)收益不可预期;有效的是减少实际访存与整数运算的结构性改动。
- **拆分为条带多 pass(2026-11-05,Mali-G715-Immortalis MC11,4096×3072,7 层)**:融合合成在 Mali 上合成合计约 9.5s(L0 8.5s、L1 0.75s),整条流程约 10.3s,Adreno 840 上同一实现 L0 约 0.3s。L0 亮度段增量 +6.5s,是 L1(+0.27s)的 24 倍,像素只差 4 倍。逐项排查后均未消除:阶段开关改为编译期常量(色度门控 +5.0s → +0.06s,亮度段不变);关闭 level-0 专有代码(输入、prefilter、输出换算);每次 dispatch 限制在 4096 个工作组。同一亮度程序只算 L0 的任一象限约 0.75s,四个象限合计约 3s,仍远小于整层。
- **采用:条带多 pass**。合成改为每 256 行一个条带,依次 dispatch Band → Pilot(仅亮度层)→ Final,不用共享内存与 barrier,邻域读条带纹理。条带纹理四周各留 4 / 2 像素边框,存镜像坐标的值,邻域读取为纯偏移,与原融合实现的边界约定相同;band、pilot 不再重复计算。条带纹理(L、base RGBA16F,noise RGBA32F,pilot RGBA16F)在整次调用中复用,L0 宽 4096 时约 43MB。Mali 上合成 9.5s → 0.43s(L0 8.5s → 0.27s,L1 0.75s → 0.09s),整条流程 10.3s → 1.2s。
- §6.0 prefilter 同样改为条带两 pass:先写条带及 2 像素边框的样本(fine、取整后的 L、σ²,复用 noise 条带纹理),再算校正。Mali 上 350ms → 127ms,整条流程约 0.98s。
- §6.0 prefilter 同样改为条带两 pass:先写条带及 2 像素边框的样本(三通道 fine 写入 noise 条带纹理,取整后的 L 写入 lap 条带纹理),再算校正;σ² 只用到中心像素,在第二个 pass 里计算。Mali 上 350ms → 127ms,整条流程约 0.98s。
- §5.1 强度估计:3 轮只有平坦门的缩放不同。第 1 轮计算样本时把每个样本存为记录(亮度箱与三通道桶号打包为一个 uint,加 base 梯度与 σ²_Y 两个 float,共 12 字节),第 2、3 轮(`ESTIMATE_RECORDS`)只读记录、按本轮门限重新计数,计数与逐轮重算逐位相同。记录缓冲只在估计期间存在,4096×3072、7 层约 31MB。原先 Mali 上 21 次 histogram 共约 310ms,改后待测。
- 共享直方图分摊原子争用:4 份副本(invocation i 计入第 i % 4 份),每份把桶 k 与 k + 32 打包为一个 uint 的低、高 16 位(每份每项至多 16 × 64 = 1024 次),4 份共 12KB,在 16KB 基线内;归并时逐字求和后写全局,计数不变。
- 实测(Mali-G715):第 2、3 轮每层降到 1–4ms;第 1 轮 L0–L2 由约 28ms 升到约 57ms,记录按样本连续存 3 个 uint 时相邻 lane 的写入间隔 12 字节。记录改为三个平面(打包值、梯度、σ²_Y 各一个平面),每条写入在 lane 间连续:无变化。记录缓冲跨调用复用(排除首次写入缺页):无变化,已撤回。第 1 轮改用 1 份副本(打包后 3KB,排除共享内存影响驻留):无变化,已恢复统一 4 份。剩余嫌疑为第 1 轮新增的记录写入本身,未继续排查:histogram 合计 310 → 233ms 已采用。histogram 合计 310 → 233ms,整条流程约 0.91s。
+6 -6
View File
@@ -55,6 +55,7 @@ def params_from_json(p: dict) -> pd.Params:
gate_luma=tuple(p["gateLuma"]),
gate_chroma=tuple(p["gateChroma"]),
bilateral_levels=p["bilateralLevels"],
chroma_gate_from=p.get("chromaGateFrom", 0),
bilateral_luma=p["bilateralLuma"],
bilateral_chroma=p["bilateralChroma"],
luma_strength=p["lumaStrength"],
@@ -120,17 +121,16 @@ def compare(input_rgb: np.ndarray, params: pd.Params, textures: dict[str, np.nda
params = replace(params, strength_table=gpu_table)
# Section 6.0: an outlier decision near its threshold may flip with last-ulp differences, so
# the correction passes when at most PREFILTER_FLIPS of the pixels disagree.
if params.luma_levels > 0 and params.luma_strength > 0:
if pd.prefilter_amounts(params).any():
ref = pd.prefilter(g0, gaussians[1], params)
gpu = textures.get("prefilter0")
if gpu is None:
results.append(("prefilter0", None))
else:
gpu = gpu[0]
gpu = gpu[:3]
flips = float(np.mean(np.abs(gpu - ref) > 1e-3 * np.maximum(np.abs(ref), np.abs(gpu)) + F32(1e-6)))
results.append(("prefilter0", (flips / PREFILTER_FLIPS, int(flips > PREFILTER_FLIPS), 0.0)))
g0 = g0.copy()
g0[0] = g0[0] + gpu
g0 = g0 + gpu
for level in range(params.levels - 1, -1, -1):
fine = g0 if level == 0 else gaussians[level]
denoised_coarse = gaussians[params.levels] if level == params.levels - 1 \
@@ -201,7 +201,7 @@ def self_test() -> bool:
np.full(4, 0.2, dtype=F32), np.full(4, 2.5, dtype=F32), (16.919, 27.877), (5.991, 13.816),
2, 4.0, 4.0, 1.0, 1.0, lsc,
merge_map=pd.MergeMap(rng.uniform(0.1, 1.0, (3, 4, 2)).astype(F32), (0, 0), (w, h)))
params = replace(params, gamma=np.array([0.5, 0.5, 0.5, 1.0], dtype=F32),
params = replace(params, gamma=np.array([0.5, 0.5, 0.5, 1.0], dtype=F32), chroma_gate_from=2,
strength_cap_luma=rng.uniform(0.5, 6.0, 4).astype(F32),
strength_cap_chroma=rng.uniform(0.01, 6.0, 4).astype(F32))
trace = pd.run(rgb, params)
@@ -213,7 +213,7 @@ def self_test() -> bool:
textures["output"] = trace.output
textures["strength"] = trace.strength
if trace.prefilter is not None:
textures["prefilter0"] = trace.prefilter[None]
textures["prefilter0"] = trace.prefilter
return compare(rgb, params, textures)
+33 -21
View File
@@ -148,6 +148,7 @@ class Params:
strength_cap_chroma: np.ndarray | None = None
merge_map: "MergeMap | None" = None # section 2.2 per-pixel ratios; None: the scalars
gamma: np.ndarray | None = None # [levels] section 6.1 second-stage gain exponent; None: 1 (MMSE)
chroma_gate_from: int = 0 # section 7.2 first level whose Mahalanobis gate is on
def luma_grain(self, level: int) -> float:
t, s = float(self.grain[level]), self.luma_strength
@@ -536,7 +537,7 @@ def final(lap: np.ndarray, base: np.ndarray, noise: np.ndarray, pilot_tex: np.nd
chroma_stat = np.where(det > 0, (s_cr * cb * cb - 2 * s_x * cb * cr + s_cb * cr * cr) / np.maximum(det, F32(1e-30)),
F32(np.inf))
low, high = params.chroma_thresholds(params.gate_chroma)
gate_c = _smoothstep(low, high, chroma_stat)
gate_c = _smoothstep(low, high, chroma_stat) if level >= params.chroma_gate_from else np.zeros_like(chroma_stat)
gate = np.maximum(gate_y, gate_c)
s = F32(min(params.chroma_strength, 1.0))
chroma_band = (s * gate + (1 - s)) * lap[1:3]
@@ -584,7 +585,7 @@ class Trace:
pilots: dict[int, np.ndarray] = field(default_factory=dict)
denoised: dict[int, np.ndarray] = field(default_factory=dict) # G~_l (stored f16 for l >= 1)
strength: np.ndarray | None = None # section 5.1 table used
prefilter: np.ndarray | None = None # section 6.0 level-0 luma correction
prefilter: np.ndarray | None = None # section 6.0 level-0 Y, Cb, Cr correction
output: np.ndarray | None = None
@@ -594,27 +595,39 @@ def _windows(image: np.ndarray, radius: int) -> np.ndarray:
return np.lib.stride_tricks.sliding_window_view(np.pad(image, radius, mode="reflect"), (side, side))
def prefilter_amounts(params: Params) -> np.ndarray:
"""Section 6.0 correction scale of Y, Cb, Cr; 0 where that channel is not denoised."""
luma = min(params.luma_strength, 1.0) if params.luma_levels > 0 else 0.0
chroma = min(params.chroma_strength, 1.0)
return np.array([max(luma, 0.0), max(chroma, 0.0), max(chroma, 0.0)], dtype=F32)
def prefilter(g0: np.ndarray, g1: np.ndarray, params: Params) -> np.ndarray:
"""Section 6.0 level-0 luma correction [H, W]: an isolated outlier in a noise-like
neighbourhood moves to its 3x3 median, scaled by min(luma strength, 1)."""
"""Section 6.0 level-0 correction [3, H, W] of Y, Cb, Cr: per channel, an isolated outlier in a
noise-like neighbourhood moves to its 3x3 median, scaled by prefilter_amounts."""
shape = g0.shape[1:]
base = up(g1, shape)
lap = f16(g0[0] - base[0])
noise, _ = model_noise(base, 0, params)
s = strength_at(params.strength_table, 0, base[0], params.scale)
sigma = np.sqrt(noise[0] * s[0])
y = g0[0]
n9 = _windows(y, 1)
m = np.sort(n9.reshape(*shape, 9), axis=-1)[..., 4]
dev = y - m
big = np.abs(n9 - m[..., None, None]) > PREFILTER_K * sigma[..., None, None]
same = big & (np.sign(n9 - m[..., None, None]) == np.sign(dev)[..., None, None])
outlier = np.abs(dev) > PREFILTER_K * sigma
count = same.sum(axis=(-1, -2)) - outlier
energy = ((_windows(lap, 2) ** 2).sum(axis=(-1, -2), dtype=F32) - lap * lap) / F32(24)
selected = (sigma > 0) & outlier & (count <= PREFILTER_GUARD) & (energy < PREFILTER_FLAT * sigma * sigma)
amount = F32(min(params.luma_strength, 1.0))
return np.where(selected, (m - y) * amount, F32(0)).astype(F32)
amounts = prefilter_amounts(params)
result = np.zeros((3,) + shape, dtype=F32)
for ch in range(3):
if amounts[ch] <= 0:
continue
lap = f16(g0[ch] - base[ch])
sigma = np.sqrt(noise[ch] * s[ch])
y = g0[ch]
n9 = _windows(y, 1)
m = np.sort(n9.reshape(*shape, 9), axis=-1)[..., 4]
dev = y - m
big = np.abs(n9 - m[..., None, None]) > PREFILTER_K * sigma[..., None, None]
same = big & (np.sign(n9 - m[..., None, None]) == np.sign(dev)[..., None, None])
outlier = np.abs(dev) > PREFILTER_K * sigma
count = same.sum(axis=(-1, -2)) - outlier
energy = ((_windows(lap, 2) ** 2).sum(axis=(-1, -2), dtype=F32) - lap * lap) / F32(24)
selected = (sigma > 0) & outlier & (count <= PREFILTER_GUARD) & (energy < PREFILTER_FLAT * sigma * sigma)
result[ch] = np.where(selected, (m - y) * amounts[ch], F32(0))
return result
def run(rgb: np.ndarray, params: Params) -> Trace:
@@ -628,10 +641,9 @@ def run(rgb: np.ndarray, params: Params) -> Trace:
if params.strength_table is None:
params = replace(params, strength_table=estimate_strength(g0, trace.gaussians, params))
trace.strength = params.strength_table
if params.luma_levels > 0 and params.luma_strength > 0:
if prefilter_amounts(params).any():
trace.prefilter = prefilter(g0, gaussians[1], params)
g0 = g0.copy()
g0[0] = g0[0] + trace.prefilter
g0 = g0 + trace.prefilter
denoised = gaussians[params.levels]
for level in range(params.levels - 1, -1, -1):
fine = g0 if level == 0 else gaussians[level]