feat: BM3D

This commit is contained in:
Hinnka committed 2026-04-10 22:25:47 +08:00
1 parent b0b33ca2b5
commit f682874ac4
3 files changed
+309 -18

No files matched your search

@@ -10,7 +10,7 @@ import android.opengl.EGLSurface
import android.opengl.GLES30
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.model.ColorPaletteMapper
import com.hinnka.mycamera.raw.NLMShaders
import com.hinnka.mycamera.raw.BM3DShaders
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.currentCoroutineContext
@@ -907,12 +907,12 @@ class LutImageProcessor {
}
val vShader = compileShader(GLES30.GL_VERTEX_SHADER, IMAGE_VERTEX_SHADER)
nlmChromaProgram = createProgram(vShader, NLMShaders.PASS0_CHROMA_DENOISE)
nlmPassHProgram = createProgram(vShader, NLMShaders.NLM_PASS_H)
nlmPassVProgram = createProgram(vShader, NLMShaders.NLM_PASS_V)
nlmChromaProgram = createProgram(vShader, BM3DShaders.PASS0_CHROMA_DENOISE)
nlmPassHProgram = createProgram(vShader, BM3DShaders.PASS1_BASIC_ESTIMATE)
nlmPassVProgram = createProgram(vShader, BM3DShaders.PASS2_WIENER)
GLES30.glDeleteShader(vShader)
PLog.d(TAG, "NLM programs initialized: Chroma=$nlmChromaProgram H=$nlmPassHProgram V=$nlmPassVProgram")
PLog.d(TAG, "BM3D programs initialized: Pass0=$nlmChromaProgram Pass1=$nlmPassHProgram Pass2=$nlmPassVProgram")
}
private fun initHDFPrograms() {
@@ -1094,7 +1094,7 @@ class LutImageProcessor {
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassVProgram, "uInputTexture"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, nlmPassTexId[0])
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassVProgram, "uBlurTexture"), 1)
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassVProgram, "uBasicTexture"), 1)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassVProgram, "uTexelSize"), texelW, texelH)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(nlmPassVProgram, "uMVPMatrix"),
@@ -0,0 +1,291 @@
package com.hinnka.mycamera.raw
/**
* Mobile-optimised BM3D (Block-Matching 3D Filtering) denoising shaders.
*
* Replaces [NLMShaders] with a two-step BM3D approximation that trades slightly
* higher ALU/texture cost for significantly better detail retention and noise
* reduction, particularly in high-ISO shots.
*
* Pipeline (same FBO bindings as NLM):
* PASS0_CHROMA_DENOISE → gfChromaFboId
* PASS1_BASIC_ESTIMATE → gfFboId[0] (RGB = basic estimate, A = match fraction)
* 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 2 uInputTexture=chromaTex (noisy),
* uBasicTexture=gfTexId[0] (basic), uH=h
*
* Performance budget (5×5 search, 3×3 luma patch):
* Pass 1 ≈ 234 tex reads/px Pass 2 ≈ 260 tex reads/px
* Total ≈ 520 reads/px (vs ≈ 122 for NLM — 4× cost, substantially higher quality)
*/
object BM3DShaders {
// ─── Pass 0 : Chroma Denoise ──────────────────────────────────────────────
/**
* Cross-bilateral filter on the chroma channels guided by luma.
* Runs before luma denoising to supply a cleaner guide image.
* Wide chroma tolerance + tight luma tolerance prevents halo/bleed.
*/
val PASS0_CHROMA_DENOISE = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture;
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
vec3 rgb2ycbcr(vec3 rgb) {
float y = dot(rgb, vec3(0.2126, 0.7152, 0.0722));
return vec3(y,
dot(rgb, vec3(-0.169, -0.331, 0.5 )) + 0.5,
dot(rgb, vec3( 0.5, -0.419, -0.081 )) + 0.5);
}
vec3 ycbcr2rgb(vec3 yuv) {
float cb = yuv.y - 0.5, cr = yuv.z - 0.5;
return vec3(yuv.x + 1.402 * cr,
yuv.x - 0.3441 * cb - 0.7141 * cr,
yuv.x + 1.772 * cb);
}
void main() {
vec3 oriRgb = texture(uInputTexture, vTexCoord).rgb;
if (uH <= 0.00001) { fragColor = vec4(oriRgb, 1.0); return; }
vec3 yuv = rgb2ycbcr(oriRgb);
vec2 sumUV = vec2(0.0);
float sumW = 0.0;
// 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);
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
vec2 ofs = vec2(float(x), float(y)) * uTexelSize * stepScale;
vec3 sYuv = rgb2ycbcr(texture(uInputTexture, vTexCoord + ofs).rgb);
float wS = exp(-float(x*x + y*y) * 0.25);
float dL = sYuv.x - yuv.x;
vec2 dC = sYuv.yz - yuv.yz;
float wR = exp(-(dL * dL) * invLumaH2 - dot(dC, dC) * invChromaH2);
float w = wS * wR;
if (x == 0 && y == 0) w = max(w, 0.1);
sumUV += sYuv.yz * w;
sumW += w;
}
}
yuv.yz = sumUV / sumW;
fragColor = vec4(ycbcr2rgb(yuv), 1.0);
}
""".trimIndent()
// ─── Pass 1 : BM3D Basic Estimate ────────────────────────────────────────
/**
* Hard-threshold block matching in a 5×5 search window with 3×3 luma patches.
*
* Matches the BM3D Step-1 philosophy: a candidate block is either in the group
* (ssd ≤ τ) or out (weight = 0), producing a collaborative average that acts as
* a spatial hard-threshold in the transform domain.
*
* Output alpha = match fraction (0–1), forwarded to Pass 2 for noise estimation.
*/
val PASS1_BASIC_ESTIMATE = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture;
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
// 5×5 search window, 3×3 luma patch
#define SEARCH_RADIUS 2
#define PATCH_RADIUS 1
const vec3 LW = vec3(0.2126, 0.7152, 0.0722);
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;
// Pre-fetch the 3×3 center-patch luma values (unrolled to avoid
// dynamic-array indexing, which can be slow on some mobile GPUs)
float c00 = dot(texture(uInputTexture, vTexCoord + vec2(-1.0,-1.0)*T).rgb, LW);
float c01 = dot(texture(uInputTexture, vTexCoord + vec2(-1.0, 0.0)*T).rgb, LW);
float c02 = dot(texture(uInputTexture, vTexCoord + vec2(-1.0, 1.0)*T).rgb, LW);
float c10 = dot(texture(uInputTexture, vTexCoord + vec2( 0.0,-1.0)*T).rgb, LW);
float c11 = dot(centerVal, LW);
float c12 = dot(texture(uInputTexture, vTexCoord + vec2( 0.0, 1.0)*T).rgb, LW);
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);
vec3 sumColor = vec3(0.0);
float sumWeight = 0.0;
for (int dx = -SEARCH_RADIUS; dx <= SEARCH_RADIUS; dx++) {
for (int dy = -SEARCH_RADIUS; dy <= SEARCH_RADIUS; dy++) {
vec2 nUV = vTexCoord + vec2(float(dx), float(dy)) * T;
// Cache the neighbor center pixel for reuse in SSD + accumulation
vec3 nC = texture(uInputTexture, nUV).rgb;
float nL = dot(nC, LW);
// 3×3 luma SSD – center pixel reuses nL from the cached fetch
float ssd = 0.0;
float d;
d = c00 - dot(texture(uInputTexture, nUV + vec2(-1.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c01 - dot(texture(uInputTexture, nUV + vec2(-1.0, 0.0)*T).rgb, LW); ssd += d*d;
d = c02 - dot(texture(uInputTexture, nUV + vec2(-1.0, 1.0)*T).rgb, LW); ssd += d*d;
d = c10 - dot(texture(uInputTexture, nUV + vec2( 0.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c11 - nL; ssd += d*d;
d = c12 - dot(texture(uInputTexture, nUV + vec2( 0.0, 1.0)*T).rgb, LW); ssd += d*d;
d = c20 - dot(texture(uInputTexture, nUV + vec2( 1.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c21 - dot(texture(uInputTexture, nUV + vec2( 1.0, 0.0)*T).rgb, LW); ssd += d*d;
d = c22 - dot(texture(uInputTexture, nUV + vec2( 1.0, 1.0)*T).rgb, LW); ssd += d*d;
// Hard threshold: binary weight (key BM3D characteristic vs NLM soft exp)
// step(edge, x) = 1 if x >= edge → step(ssd, threshold) = 1 if ssd ≤ threshold
float w = step(ssd, threshold);
sumColor += nC * w;
sumWeight += w;
}
}
// The center itself is always included (dx=0,dy=0 gives ssd=0 ≤ threshold)
// Store normalised match count in alpha → Pass 2 uses it to refine noise estimate
float maxCandidates = float((2*SEARCH_RADIUS+1) * (2*SEARCH_RADIUS+1)); // 25
fragColor = vec4(sumColor / max(sumWeight, 1.0), sumWeight / maxCandidates);
}
""".trimIndent()
// ─── Pass 2 : BM3D Wiener Refinement ─────────────────────────────────────
/**
* Uses the basic estimate (Pass 1) as a noise-reduced guide for block matching.
* For each matched group, estimates the local signal variance from the basic
* estimate and computes the Wiener-optimal blend weight:
*
* w = σ_s² / (σ_s² + σ_n²/N)
*
* where σ_s² = signal variance in the group, σ_n² = noise variance (uH²),
* N = number of matched patches.
*
* The final pixel is mixed between the basic estimate (near-noise-free prior)
* and the average of matched noisy patches (structure-preserving signal estimate).
*
* Uniforms:
* uInputTexture – original (chroma-denoised) noisy image
* uBasicTexture – Pass-1 output (RGB = basic estimate, A = match fraction)
*/
val PASS2_WIENER = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture; // chroma-denoised noisy image
uniform sampler2D uBasicTexture; // Pass-1 basic estimate (A = match fraction)
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
// Same search / patch geometry as Pass 1
#define SEARCH_RADIUS 2
#define PATCH_RADIUS 1
const vec3 LW = vec3(0.2126, 0.7152, 0.0722);
void main() {
vec3 noisyCenter = texture(uInputTexture, vTexCoord).rgb;
vec4 basicSample = texture(uBasicTexture, vTexCoord);
vec3 basicCenter = basicSample.rgb;
// alpha from Pass 1: fraction of the 25 candidates that were merged
// → approximates N_basic, the effective patch count in the basic estimate
float N_basic = basicSample.a * 25.0 + 1.0;
if (uH <= 0.00001) { fragColor = vec4(noisyCenter, 1.0); return; }
float sigma_n2 = uH * uH;
float threshold = sigma_n2 * 9.0 * 2.7; // same τ as Pass 1
vec2 T = uTexelSize;
// Pre-fetch 3×3 center-patch luma from BASIC estimate (less noisy guide)
float c00 = dot(texture(uBasicTexture, vTexCoord + vec2(-1.0,-1.0)*T).rgb, LW);
float c01 = dot(texture(uBasicTexture, vTexCoord + vec2(-1.0, 0.0)*T).rgb, LW);
float c02 = dot(texture(uBasicTexture, vTexCoord + vec2(-1.0, 1.0)*T).rgb, LW);
float c10 = dot(texture(uBasicTexture, vTexCoord + vec2( 0.0,-1.0)*T).rgb, LW);
float c11 = dot(basicCenter, LW);
float c12 = dot(texture(uBasicTexture, vTexCoord + vec2( 0.0, 1.0)*T).rgb, LW);
float c20 = dot(texture(uBasicTexture, vTexCoord + vec2( 1.0,-1.0)*T).rgb, LW);
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);
vec3 sumNoisy = vec3(0.0);
float sumWeight = 0.0;
float sumL = 0.0; // luma sum for variance estimation
float sumL2 = 0.0; // luma² sum for variance estimation
for (int dx = -SEARCH_RADIUS; dx <= SEARCH_RADIUS; dx++) {
for (int dy = -SEARCH_RADIUS; dy <= SEARCH_RADIUS; dy++) {
vec2 nUV = vTexCoord + vec2(float(dx), float(dy)) * T;
// Cache basic estimate center for SSD + variance stats
vec3 nBasic = texture(uBasicTexture, nUV).rgb;
float nL = dot(nBasic, LW);
// Patch SSD over BASIC estimate – cleaner matching than noisy image
float ssd = 0.0;
float d;
d = c00 - dot(texture(uBasicTexture, nUV + vec2(-1.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c01 - dot(texture(uBasicTexture, nUV + vec2(-1.0, 0.0)*T).rgb, LW); ssd += d*d;
d = c02 - dot(texture(uBasicTexture, nUV + vec2(-1.0, 1.0)*T).rgb, LW); ssd += d*d;
d = c10 - dot(texture(uBasicTexture, nUV + vec2( 0.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c11 - nL; ssd += d*d;
d = c12 - dot(texture(uBasicTexture, nUV + vec2( 0.0, 1.0)*T).rgb, LW); ssd += d*d;
d = c20 - dot(texture(uBasicTexture, nUV + vec2( 1.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c21 - dot(texture(uBasicTexture, nUV + vec2( 1.0, 0.0)*T).rgb, LW); ssd += d*d;
d = c22 - dot(texture(uBasicTexture, nUV + vec2( 1.0, 1.0)*T).rgb, LW); ssd += d*d;
float w = step(ssd, threshold);
// Accumulate signal-variance statistics from basic estimate
sumL += nL * w;
sumL2 += nL * nL * w;
// Filter the NOISY image with weights derived from basic-estimate matching
sumNoisy += texture(uInputTexture, nUV).rgb * w;
sumWeight += w;
}
}
// ── Wiener weight computation ────────────────────────────────────
// Estimate signal variance from the matched group in the basic estimate.
// var_total(basic group) ≈ var_signal + σ_n²/N_basic (residual noise)
float N = max(sumWeight, 1.0);
float meanL = sumL / N;
float varTotal = sumL2 / N - meanL * meanL;
// Subtract residual noise in basic estimate (σ_n² / N_basic)
float varSignal = max(0.0, varTotal - sigma_n2 / N_basic);
// Wiener weight: w = σ_s² / (σ_s² + σ_n²/N)
// Large N, large σ_s² (texture) → w≈1 → trust matched noisy average
// Small N or small σ_s² (smooth) → w≈0 → trust the basic estimate
float noiseOfAvg = sigma_n2 / N;
float wienerW = varSignal / max(varSignal + noiseOfAvg, 1e-6);
vec3 avgNoisy = sumNoisy / N;
fragColor = vec4(mix(basicCenter, avgNoisy, wienerW), 1.0);
}
""".trimIndent()
}
@@ -922,11 +922,11 @@ class RawDemosaicProcessor {
return program
}
gfPass0Program = createGfProgram(vShader, NLMShaders.PASS0_CHROMA_DENOISE, "GF_Pass0")
nlmPassHProgram = createGfProgram(vShader, NLMShaders.NLM_PASS_H, "NLM_PassH")
nlmPassVProgram = createGfProgram(vShader, NLMShaders.NLM_PASS_V, "NLM_PassV")
gfPass0Program = createGfProgram(vShader, BM3DShaders.PASS0_CHROMA_DENOISE, "BM3D_Pass0")
nlmPassHProgram = createGfProgram(vShader, BM3DShaders.PASS1_BASIC_ESTIMATE, "BM3D_Pass1")
nlmPassVProgram = createGfProgram(vShader, BM3DShaders.PASS2_WIENER, "BM3D_Pass2")
PLog.d(TAG, "Denoise programs: GF_Pass0=$gfPass0Program NLM_H=$nlmPassHProgram NLM_V=$nlmPassVProgram")
PLog.d(TAG, "Denoise programs: BM3D_Pass0=$gfPass0Program BM3D_Pass1=$nlmPassHProgram BM3D_Pass2=$nlmPassVProgram")
}
private fun setupNLMFramebuffers(width: Int, height: Int) {
@@ -1004,9 +1004,9 @@ class RawDemosaicProcessor {
/**
* 渲染 NLM 降噪
* 渲染 BM3D 降噪
*
* 管线: tonemapTexture → [Pass0 Chroma] → [NLM] → gfFboId[1]
* 管线: tonemapTexture → [Pass0 Chroma] → [BM3D Basic] → [BM3D Wiener] → gfFboId[1]
*
* @param sourceTextureId 输入纹理 (ToneMap 输出)
*/
@@ -1059,7 +1059,7 @@ class RawDemosaicProcessor {
val h = (noise * denoiseValue).coerceIn(0.0f, 0.1f)
val ch = (noise * (chromaDenoiseValue + 0.5f)).coerceIn(0.0f, 0.1f)
PLog.d(TAG, "Dynamic NLM: noise=$noise, h=$h ch=$ch")
PLog.d(TAG, "Dynamic BM3D: noise=$noise, h=$h ch=$ch")
val identityMatrix = FloatArray(16)
GlMatrix.setIdentityM(identityMatrix, 0)
@@ -1080,7 +1080,7 @@ class RawDemosaicProcessor {
GLES30.glUniform1f(GLES30.glGetUniformLocation(gfPass0Program, "uH"), ch)
drawQuad(gfPass0Program)
// ===== NLM Pass 1: Horizontal (gfChromaTexId -> gfFboId[0]) =====
// ===== BM3D Pass 1: Basic Estimate (gfChromaTexId -> gfFboId[0]) =====
GLES30.glUseProgram(nlmPassHProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, gfFboId[0])
GLES30.glViewport(0, 0, width, height)
@@ -1096,18 +1096,18 @@ class RawDemosaicProcessor {
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmPassHProgram, "uH"), h)
drawQuad(nlmPassHProgram)
// ===== NLM Pass 2: Vertical (gfChromaTexId + gfTexId[0] -> gfFboId[1]) =====
// ===== BM3D Pass 2: Wiener Refinement (gfChromaTexId + gfTexId[0] -> gfFboId[1]) =====
GLES30.glUseProgram(nlmPassVProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, gfFboId[1])
GLES30.glViewport(0, 0, width, height)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, gfChromaTexId) // Original (Guide)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, gfChromaTexId) // Original noisy (chroma-denoised)
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassVProgram, "uInputTexture"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, gfTexId[0]) // Blur Input
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassVProgram, "uBlurTexture"), 1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, gfTexId[0]) // Pass-1 basic estimate
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassVProgram, "uBasicTexture"), 1)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassVProgram, "uTexelSize"), texelW, texelH)
GLES30.glUniformMatrix4fv(