feat: implement sensor-aware noise model for RAW denoising

This commit is contained in:
Hinnka committed 2026-05-17 09:59:25 +08:00
1 parent be2089366c
commit f7886874b1
3 files changed
+67 -37

No files matched your search

@@ -22,6 +22,7 @@ import java.nio.FloatBuffer
import java.nio.ShortBuffer
import java.util.concurrent.Executors
import androidx.core.graphics.createBitmap
import kotlin.math.sqrt
/**
* LUT 图片处理器
@@ -1155,8 +1156,11 @@ class LutImageProcessor {
val texelW = 1.0f / width
val texelH = 1.0f / height
// 将降噪强度映射到合理范围 (0.001 ~ 0.1)
val h = 0.001f + noiseReduction * noiseReduction * 0.2f
val ch = 0.001f + chromaNoiseReduction * chromaNoiseReduction * 0.2f
val h = noiseReduction
val ch = chromaNoiseReduction
val s = 0.015f
val o = 0.001f
val identityMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
@@ -1177,6 +1181,7 @@ class LutImageProcessor {
0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmChromaProgram, "uH"), ch)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmChromaProgram, "uNoiseModel"), s, o)
drawQuad(nlmChromaProgram)
// NLM Pass H
@@ -1195,6 +1200,7 @@ class LutImageProcessor {
0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmPassHProgram, "uH"), h)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassHProgram, "uNoiseModel"), s, o)
drawQuad(nlmPassHProgram)
// NLM Pass V
@@ -1216,6 +1222,7 @@ class LutImageProcessor {
0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmPassVProgram, "uH"), h)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassVProgram, "uNoiseModel"), s, o)
drawQuad(nlmPassVProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
@@ -13,10 +13,10 @@ package com.hinnka.mycamera.raw
* PASS2_WIENER → gfFboId[1] (final Wiener-filtered result)
*
* Uniform interface (caller side):
* Pass 0 uInputTexture=source, uH=chromaH
* Pass 1 uInputTexture=chromaTex, uH=h
* Pass 0 uInputTexture=source, uH=chromaH, uNoiseModel=(S,O)
* Pass 1 uInputTexture=chromaTex, uH=h, uNoiseModel=(S,O)
* Pass 2 uInputTexture=chromaTex (noisy),
* uBasicTexture=gfTexId[0] (basic), uH=h
* uBasicTexture=gfTexId[0] (basic), uH=h, uNoiseModel=(S,O)
*
* Performance budget (5×5 search, 3×3 luma patch):
* Pass 1 ≈ 234 tex reads/px Pass 2 ≈ 260 tex reads/px
@@ -39,6 +39,7 @@ object BM3DShaders {
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
uniform vec2 uNoiseModel;
vec3 rgb2ycbcr(vec3 rgb) {
float y = dot(rgb, vec3(0.2126, 0.7152, 0.0722));
@@ -52,6 +53,11 @@ object BM3DShaders {
yuv.x - 0.3441 * cb - 0.7141 * cr,
yuv.x + 1.772 * cb);
}
float noiseScaleForLuma(float luma) {
float x = max(luma, 0.001);
float snr = x / sqrt(max(uNoiseModel.x * x + uNoiseModel.y, 1e-10));
return 1.0 / snr;
}
void main() {
vec3 oriRgb = texture(uInputTexture, vTexCoord).rgb;
@@ -63,8 +69,9 @@ object BM3DShaders {
// Chroma noise is low-frequency → large spatial step scale
float stepScale = 6.5;
float invChromaH2 = 1.0 / max((uH * 1.5) * (uH * 1.5), 1e-6);
float invLumaH2 = 1.0 / max((uH * 0.5) * (uH * 0.5), 1e-6);
float localH = uH * noiseScaleForLuma(yuv.x);
float invChromaH2 = 1.0 / max((localH * 1.5) * (localH * 1.5), 1e-6);
float invLumaH2 = 1.0 / max((localH * 0.5) * (localH * 0.5), 1e-6);
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
@@ -105,6 +112,7 @@ object BM3DShaders {
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
uniform vec2 uNoiseModel;
// 5×5 search window, 3×3 luma patch
#define SEARCH_RADIUS 2
@@ -129,14 +137,16 @@ object BM3DShaders {
float gate = 1.0 - smoothstep(t * 0.35, t * 1.55, ssd);
return soft * gate;
}
float noiseScaleForLuma(float luma) {
float x = max(luma, 0.001);
float snr = x / sqrt(max(uNoiseModel.x * x + uNoiseModel.y, 1e-10));
return 1.0 / snr;
}
void main() {
vec3 centerVal = texture(uInputTexture, vTexCoord).rgb;
if (uH <= 0.00001) { fragColor = vec4(centerVal, 1.0); return; }
// BM3D hard threshold: τ = factor × σ² × patch_size
// factor 2.7 is the standard BM3D constant, tuned here for 3×3 patches
float threshold = uH * uH * 9.0 * 2.7;
vec2 T = uTexelSize;
vec3 centerYuv = rgb2ycbcr(centerVal);
@@ -151,6 +161,11 @@ object BM3DShaders {
float c20 = dot(texture(uInputTexture, vTexCoord + vec2( 1.0,-1.0)*T).rgb, LW);
float c21 = dot(texture(uInputTexture, vTexCoord + vec2( 1.0, 0.0)*T).rgb, LW);
float c22 = dot(texture(uInputTexture, vTexCoord + vec2( 1.0, 1.0)*T).rgb, LW);
float localH = uH * noiseScaleForLuma(c11);
// BM3D hard threshold: τ = factor × σ² × patch_size
// factor 2.7 is the standard BM3D constant, tuned here for 3×3 patches
float threshold = localH * localH * 9.0 * 2.7;
float sumLuma = 0.0;
vec2 sumChroma = vec2(0.0);
@@ -194,7 +209,7 @@ object BM3DShaders {
// Fallback for low-match cases (edges/isolated noise) to break up clusters.
// Uses a tiny 3x3 guided luma average since we already have the patch data.
float lwSum = 1.0; float lvalSum = c11;
float invH2 = 1.0 / max(uH * uH * 2.0, 1e-5);
float invH2 = 1.0 / max(localH * localH * 2.0, 1e-5);
float w;
w = exp(-(c00-c11)*(c00-c11)*invH2); lwSum += w; lvalSum += c00*w;
w = exp(-(c01-c11)*(c01-c11)*invH2); lwSum += w; lvalSum += c01*w;
@@ -243,6 +258,7 @@ object BM3DShaders {
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
uniform vec2 uNoiseModel;
// Same search / patch geometry as Pass 1
#define SEARCH_RADIUS 2
@@ -267,6 +283,11 @@ object BM3DShaders {
float gate = 1.0 - smoothstep(t * 0.35, t * 1.55, ssd);
return soft * gate;
}
float noiseScaleForLuma(float luma) {
float x = max(luma, 0.001);
float snr = x / sqrt(max(uNoiseModel.x * x + uNoiseModel.y, 1e-10));
return 1.0 / snr;
}
float wideGuidedLumaBase(vec2 uv, vec2 texelSize, float centerGuideLuma, float sigma_n2) {
float sumY = 0.0;
float sumW = 0.0;
@@ -315,9 +336,10 @@ object BM3DShaders {
float c21 = dot(texture(uBasicTexture, vTexCoord + vec2( 1.0, 0.0)*T).rgb, LW);
float c22 = dot(texture(uBasicTexture, vTexCoord + vec2( 1.0, 1.0)*T).rgb, LW);
// Smoother luma noise boost to avoid abrupt transitions at edges
float lumaNoiseBoost = mix(1.25, 0.85, smoothstep(0.02, 0.80, c11));
float sigma_n2 = uH * uH * lumaNoiseBoost * lumaNoiseBoost;
// Sensor noise model: variance = S * luma + O, normalized so uH keeps
// its existing mid-gray strength while local denoise follows brightness.
float localH = uH * noiseScaleForLuma(c11);
float sigma_n2 = localH * localH;
float threshold = sigma_n2 * 9.0 * 2.7; // same τ as Pass 1, adapted by luma
vec3 basicYuv = rgb2ycbcr(basicCenter);
@@ -398,7 +420,7 @@ object BM3DShaders {
edgeSq + varSignal
);
float matchConfidence = smoothstep(2.5, 8.0, N) * smoothstep(0.08, 0.36, basicSample.a);
float residualLimit = max(uH * 0.65, 0.003);
float residualLimit = max(localH * 0.65, 0.003);
float residualPull = clamp(fullResY - lowFreqY, -residualLimit, residualLimit);
float lowFreqStrength = 0.35 * flatness * matchConfidence * (1.0 - detailProtect * 0.65);
float finalY = fullResY - residualPull * clamp(lowFreqStrength, 0.0, 0.35);
@@ -366,7 +366,6 @@ class RawDemosaicProcessor {
rawDROMode = rawDROMode,
sharpeningValue = sharpeningValue,
denoiseValue = denoiseValue,
chromaDenoiseValue = chromaDenoiseValue,
rawDcpId = rawDcpId,
dcpRenderPlan = dcpRenderPlan
)?.sdrBitmap
@@ -450,7 +449,6 @@ class RawDemosaicProcessor {
rawDROMode: DROMode = DROMode.fromPersistedName(null),
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
rawDcpId: String? = null,
dcpRenderPlan: DcpRenderPlan? = null,
dngFile: File? = null,
@@ -660,7 +658,7 @@ class RawDemosaicProcessor {
height = actualHeight,
metadata = actualMetadata,
denoiseValue = denoiseValue,
chromaDenoiseValue = chromaDenoiseValue,
chromaDenoiseValue = denoiseValue,
)
// demosaicTextureId / gfChromaTexId / gfTexId[0] 已被 NLM Pass 消费,提前释放
if (demosaicTextureId != 0) {
@@ -1156,31 +1154,19 @@ class RawDemosaicProcessor {
val postGain = ExposureNormalization.compute(metadata)
val totalGain = (isoGain * digitalGain * postGain).coerceAtLeast(0f)
// 基于噪声特性的基础强度
val s = metadata.noiseProfile[0]
val o = metadata.noiseProfile[1]
// 估算标准差,映射到一个易用的量级 (使用 1e-3 作为中等 RAW 亮度的估算)
val noiseBase = (sqrt((s * 1e-3f + o * 1e-6f).toDouble()).toFloat() * 100.0f)
var (s, o) = resolveDenoiseNoiseModel(metadata, totalGain)
// 动态计算 h 值 (衰减系数)
// 让 noiseProfile 的基础噪声和总增益都更明显地参与估算:
// 1. noiseBase 直接决定主体强度
// 2. totalGain 同时以 sqrt 与线性两部分参与,提升高增益场景下的去噪力度
val gainSqrt = sqrt(totalGain.toDouble()).toFloat()
val gainNoise = 0.0035f * gainSqrt + 0.0006f * totalGain
val baseNoise = if (noiseBase > 0f) {
noiseBase * 0.8f
} else {
0.010f * gainSqrt
if (s <= 0 || o <= 0) {
s = 1E-4f * totalGain
o = 4.5E-7f * sqrt(totalGain)
}
val noise = baseNoise + gainNoise
val denoiseValue = denoiseValue ?: 0f
val chromaDenoiseValue = chromaDenoiseValue ?: 0f
val h = (noise * denoiseValue).coerceIn(0.0f, 0.1f)
val ch = (noise * (chromaDenoiseValue + 0.5f)).coerceIn(0.0f, 0.1f)
PLog.d(TAG, "Dynamic BM3D: noise=$noise, h=$h ch=$ch")
val h = denoiseValue
val ch = chromaDenoiseValue + 0.5f
PLog.d(TAG, "Dynamic BM3D: s=$s o=$o, h=$h ch=$ch iso=${metadata.iso}")
val identityMatrix = FloatArray(16)
GlMatrix.setIdentityM(identityMatrix, 0)
@@ -1199,6 +1185,7 @@ class RawDemosaicProcessor {
1, false, identityMatrix, 0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(gfPass0Program, "uH"), ch)
GLES30.glUniform2f(GLES30.glGetUniformLocation(gfPass0Program, "uNoiseModel"), s, o)
drawQuad(gfPass0Program)
// ===== BM3D Pass 1: Basic Estimate (gfChromaTexId -> gfFboId[0]) =====
@@ -1215,6 +1202,7 @@ class RawDemosaicProcessor {
1, false, identityMatrix, 0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmPassHProgram, "uH"), h)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassHProgram, "uNoiseModel"), s, o)
drawQuad(nlmPassHProgram)
// ===== BM3D Pass 2: Wiener Refinement (gfChromaTexId + gfTexId[0] -> gfFboId[1]) =====
@@ -1236,11 +1224,24 @@ class RawDemosaicProcessor {
1, false, identityMatrix, 0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmPassVProgram, "uH"), h)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassVProgram, "uNoiseModel"), s, o)
drawQuad(nlmPassVProgram)
checkGlError("renderNLMDenoise")
}
private fun resolveDenoiseNoiseModel(metadata: RawMetadata, totalGain: Float): Pair<Float, Float> {
var s = metadata.noiseProfile.getOrElse(0) { 0f }
var o = metadata.noiseProfile.getOrElse(1) { 0f }
if (s <= 0f || o <= 0f) {
s = 1E-4f * totalGain
o = 4.5E-7f * sqrt(totalGain)
}
return s.coerceAtLeast(1e-10f) to o.coerceAtLeast(1e-10f)
}
private fun dhtSetCommonUniforms(program: Int, metadata: RawMetadata) {
val loc = GLES30.glGetUniformLocation(program, "uImageSize")
if (loc >= 0) GLES30.glUniform2f(loc, metadata.width.toFloat(), metadata.height.toFloat())