chore: Photon denoise doc and tools

This commit is contained in:
zhoubinjia committed 2026-11-06 15:15:37 +08:00
1 parent 8d85d1746e
commit 3cf0f975e7
12 files changed
+3139

No files matched your search

+625
View File
@@ -0,0 +1,625 @@
# Photon 多尺度降噪设计
## 1. 目标与原则
用一套白盒 GLES compute 多尺度降噪替换现有全部降噪实现,并成为 App 内唯一的降噪算法:
| 被替换 | 位置 |
|---|---|
| MGC Pecan 亮度 + ChromaDenoisePyramidComplete 色度 + ComputeDenoiseStrengthMaps + RgbRawToYuv/YuvToRgb + MeasureMoire | `MgcFullResolutionDenoise.kt`、`mgc_full_resolution_denoise_jni.cpp`、`mgc_full_resolution_denoise_static.S.in`、`mgc_demoire_static.S.in` |
| Spatial 合成强度图 AOT | `mgc_spatial_strength_jni.cpp`、`MgcSpatialStrengthMap*`、`MgcSpatialStrengthAtlasLayout.kt`、`MgcSpatialDenoiseModel.kt` |
| MGC 降噪用的噪声模型推导 | `DemosaicNoisePropagationCalibrator.kt`、`DemosaicNoiseAtlasGenerator.kt`、`MgcSabreMergedNoiseModel.kt` |
| darktable NLM | `DenoiseProfileAlgorithm.kt`、`DenoiseProfileNlmConfig.kt`、`DenoiseProfileStripePlanner.kt` |
| 多尺度边缘引导色度降噪 | `lut/ChromaDenoiseAlgorithm.kt` |
| Bitmap NLM / 色度 | `LutImageProcessor.kt` 内 bitmap denoise 程序 |
设计原则:
1. **噪声 = RAW 噪声档案 × 白噪声理论值**。每层噪声方差由档案系数与“白噪声经本金字塔”的精确能量系数相乘得到,运行时只需查档案、做乘法。不做离线标定,也不从图像实测。
2. **模型的系统误差显式记录,不在模型中补偿**。白噪声理论不包含去马赛克(VGN 的相关与色彩噪声重建)等上游影响(附录 A–C 记录了推算、标定、实测三条路线的结论)。这些误差的大小用成对拍摄测量并写入本文档(§12.1),降噪强度由各管线的调参表(§7.4、§8.4)以 PSNR 为目标确定。
3. **显式处理两种空间变化**:LSC(降噪入口除以已施加的增益,降噪后乘回,§3)与多帧合成的逐像素方差比(剔除区参与帧少、噪声高,§2.2)。
4. **不以 Pecan 为画质基准**,不追求兼容旧小波或 MGC 输出。借鉴 MGC 的是:信号相关的噪声多项式、按金字塔层的噪声水平、亮度与色度分治。
5. **亮度与色度是两个算法**,共享噪声模型与金字塔框架,侧重点不同(§6、§7)。
6. **全 GPU**,无 CPU 往返、无回读;只在 CPU 上计算与图像尺寸无关的小表(白噪声能量系数)。
7. 移除 MeasureMoire。
## 2. 噪声模型
### 2.1 定义
在 §4 的工作域金字塔上,分量 `k ∈ {Y, Cb, Cr}`、层 `l`、多相相位 `φ = (y & 1)·2 + (x & 1)` 处,拉普拉斯层的噪声协方差为:
```
Σ_{l,φ}(p) = κ⁰_{k(·),l,φ} · m · t²_{l} · A · diag( r_c + s_c · μ_c(p) ) · Aᵀ, A = K · M · W
```
- `r_c, s_c`:RAW 噪声档案的读出、散粒系数(归一化、未白平衡相机 RGB,与 `RawNoiseModel` 同域;`RawNoiseProfileManager` 选出的 DNG NoiseProfile / Camera2 / 自定义档案)。四通道档案的两个绿色位点取均值。
- `μ_c(p)`:除 LSC 增益后的相机 RGB 信号,取已降噪的上一粗层 `↑G̃_{l+1}` 经 `M⁻¹`、`K⁻¹`、`W⁻¹` 得到。使用降噪后低通而非带噪像素,避免信号相关方差的估计偏差。
- `A diag(·) Aᵀ`:各源通道噪声独立时工作域 YCbCr 的点协方差(3×3)。亮度、色度方差与 Cb–Cr 互协方差都由此精确得到;不沿用 MGC `NoiseModel::Transform` 中“零和色度行丢弃散粒项”“色度共用通道 0 散粒/二次项”的截断。
- `κ⁰_{k,l,φ}`:白噪声经本金字塔第 `l` 层、相位 `φ` 的能量系数,亮度用亮度滤波器、色度用色度滤波器。由 `PhotonNoisePropagation`(单位谱)精确计算,按四个相位分别保留;Cb、Cr 共用色度系数,Cb–Cr 互协方差同样乘以色度系数。
- `m`:多帧合成的方差比(§2.2),单帧为 1。
- `t²_l`:已降噪输入的残余比(§2.4),未降噪为 1。
### 2.2 多帧合成
合成像素 `ŷ(p) = Σ_i w_i(p) y_i(p) / Σ_i w_i(p)`,各帧噪声独立且已换算到参考曝光(系数 `r_i, s_i`):
```
m_r(p) = e² · Σ_i w_i(p)² ρ_{r,i} / (Σ_i w_i(p))², ρ_{r,i} = r_i / r_ref
m_s(p) = e · Σ_i w_i(p)² ρ_{s,i} / (Σ_i w_i(p))², ρ_{s,i} = s_i / s_ref
w_i(p) = g_i · a_i(p)
```
- `g_i`:帧的全局权重(Sabre 为 1,Spatial 为 `globalFrameWeight`)。
- `a_i(p) ∈ [0, 1]`:帧在 `p` 处的接受度,即合成着色器实际乘入的逐帧权重纹理在参考坐标处的值(Spatial 的 `mergeWeight`,含超短帧掩膜改写;Sabre 的覆盖权重 `frameWeight`;参考帧不读权重纹理,为 1)。两条路径的权重纹理都在 RAW/4 网格上,以线性过滤采样,方差比在同一网格上累加。
- `ρ_i`:各帧换算到参考曝光后的相机 RGB 系数与参考帧之比(三通道之和的比值);`e`:合成输出的曝光缩放(Spatial 接受超短帧时 `e = 1/曝光比`)。
- 读出项乘 `m_r(p)`、散粒项乘 `m_s(p)`。静止区全部接受时等于名义值(等曝光等权为 `1/N`);只有参考帧被接受的剔除区为 `e²·1`、`e·1`,即单帧噪声,降噪强度随之回到单帧水平。
不进入模型的部分:帧内的空间核与鲁棒性权重(Sabre 的逐通道 RBF 权重、Spatial 的核宽)只在帧内做插值平均,与去马赛克相关同类,属于 §2.5 的系统误差。
**合成方差图**。合成时在 RAW/4 网格上用计算着色器累加 `(Σ w_i, Σ w_i² ρ_{r,i}, Σ w_i² ρ_{s,i})`:每帧一次 dispatch,在网格格心以线性过滤读取与合成着色器相同的权重纹理,乘全局权重;累加存于 SSBO,每格由同一调用读改写,无需乒乓。合成结束后第二个 dispatch 对 8×8 格的方差比取均值,得到 RAW/32 的 `(m_r, m_s)` 图(一格内没有任何帧权重时取 1,即合成保留参考帧),经 SSBO 映射读回(4096×3072 时 128×96×2 个 float,约 98KB)并按持久化精度取整为 float16。默认降噪与用户调整降噪使用同一张 RAW/32 图。降噪器在 Band 计算 §2.1 协方差时,按像素中心在整图中的归一化位置对该图做双线性采样(与 LSC 增益图 Camera2 模式相同的手动双线性,保证与参考实现一致);没有方差图的像素以 1×1 的名义标量代替。粗层像素覆盖多个图格时仍取中心点。
**标量名义值**。`RawDenoiseHistory.mergeRead/mergeShot` 保留为全部接受时的名义值,只用于与像素无关的量:§5 的调参坐标 `n`、§4.2 的色度层数、Spatial Bayer 去马赛克的阈值档案。剔除区的降噪强度由方差图给出,调参节点仍按整张照片的名义 `n` 选择。
**持久化**。方差图作为 `RawDenoiseHistory.mergeMap`(`RawMergeVarianceMap`)随合成结果、默认降噪的输出记录一起写入相册元数据(`RawDenoiseHistoryMetadata`,float16 小端 Base64,约 65KB),用户调整降噪读取后同样双线性采样。RAW/32 的格均值使运动边界约 32 像素内的方差比被平均,边界两侧的降噪强度过渡变宽。
**实现位置**:`raw/denoise/PhotonMergeNoise.kt`(GPU 累加与换算,同时保留名义标量);`GlesMgcRawSpatialStacker` 在 Spatial 的四处接纳点(超短帧基底 / 超短帧 / 无超短帧的参考帧 / 时间帧,传入与合成相同的权重纹理:Bayer 输出为 `mergeWeight` 等,RGB 输出为 AOT 消费的剔除平面)与 Sabre(参考帧无权重纹理,后续帧为 `frameWeight`)调用;结果随 `RawStackResult.denoiseHistory` 交给默认降噪。累加器登记在合成器上,合成异常时随 `release()` 释放。
### 2.3 白噪声能量系数
`κ⁰` 只依赖金字塔结构(滤波器、层数、边界方式),由第 1 步已验证的传播计算给出(附录 A:合成数据上 5 层 × 4 相位最大偏差 1.02%)。按 `(分量, 层, 相位)` 预先算好,随金字塔结构一起固定。
### 2.4 多次降噪
默认降噪(合成后写 DNG 前)把实际使用的残余比 `t²_{k,l}` 写入相册元数据(`RawDenoiseHistoryMetadata`,与已施加 LSC 增益图同一机制)。取平坦区最坏情况:亮度在收缩的层上为 `t_l(s)²`(§6.2、§8),未收缩的层为 1;色度细节层门控关闭,为 `(1 − min(s, 1))²`(`s ≥ 1` 时为 0);本次未处理的层保持输入值。多次降噪时逐层相乘。用户调整降噪读取后,第 `l` 层协方差乘以 `D Σ D`,`D = diag(t_{Y,l}, t_{Cb,l}, t_{Cr,l})`。没有该元数据的输入按未降噪处理。
同一条记录还保存合成方差比 `m_r, m_s`(§2.2)和产生像素的管线(选择调参表,§5)。单帧保存时清除该记录;没有记录的 RAW 按单帧处理,管线由 CFA 决定(Quad Bayer 为 `QUAD`,其余为 `VGN`)。
### 2.5 已知的系统误差
| 来源 | 影响 | 已有证据 |
|---|---|---|
| 去马赛克的空间相关 | 白噪声理论高估细层、低估粗层的噪声(相关噪声的能量向低频集中) | 合成数据中 `[1,2,1]/4` 相关使第 0 层真实方差约为理论值的 1/40(附录 C) |
| VGN 色彩噪声重建、坏点修复 | 色度噪声低于理论值,且随噪声水平非线性变化 | 单通道加噪时输出方差被压到 5%–22%(附录 A) |
| Quad Bayer 块结构 | 第 1 层相位间差异、低频色斑,理论值不含 | 附录 A |
| 帧内空间核与鲁棒性权重 | 合成方差图只含逐帧接受度,帧内插值平均使实际噪声略低于预测 | §2.2 |
| 档案误差 | 档案幅度偏差等比例进入所有层 | — |
这些误差不进入模型。它们的实际大小由 §12.1 用成对拍摄按管线、层、亮度测量并记录;降噪强度通过各管线的调参表确定。
## 3. LSC 归一化
### 3.1 原理
LSC 在去马赛克之前逐 CFA 位点乘入增益 `g`。设乘增益前的信号为 `μ₀`,乘增益后某像素的噪声方差为 `g²·σ₀²(μ₀)`,其中 `σ₀²` 是未施加 LSC 时的噪声函数。降噪入口按通道除以 `g`:
```
x_n = x / g ⇒ Var[x_n] = σ₀²(μ₀), μ₀ = μ / g
```
噪声在空间上恢复平稳,与档案同域。降噪在 `x_n` 域进行,输出乘回 `g`。
- `g` 是平滑场,去马赛克只在局部插值,因此在去马赛克之后、按 RGB 通道除增益与在 Bayer 位点上除增益的差异可以忽略。G 通道取两个绿色位点增益的均值。
- 不把管线中的 LSC 挪到降噪之后施加:VGN 的方向判断、色彩噪声重建与坏点修复在白平衡域工作,带暗角与偏色的输入会改变去马赛克结果;高光重建与增益的先后顺序也会改变结果。除增益再乘回只影响降噪这一段。
- 除增益后的四角带有原始的色偏,色度降噪在该域中处理色偏后的色度;色偏是低频且线性的,乘回后精确恢复。
### 3.2 增益来源
已核实的现状:
| 路径 | 像素是否已含 LSC | 增益图来源 |
|---|---|---|
| 单帧 RAW | 是(`VgnDemosaicAlgorithm.lensShadingGainAt`,`sensorAt(q) · gain`) | `RawMetadata.lensShadingMap` |
| 合成默认降噪(Spatial / Sabre) | 由 `outputIncludesLensShading` 决定(`RawDemosaicProcessor.kt:995`) | `denoiseMetadata` 中保留的增益图 |
| **持久化合成 DNG** | 是 | **当前被移除**(`RawProcessor.kt:134`、`:741`) |
实现(已完成):合成结果以“像素已含 LSC”保存时,`GalleryManager` 把合成实际使用的增益图(`RawAppliedLensShading.fromCamera2`,与 `MultiFrameStacker.validLensShadingOrNull` 同一取值)写入相册元数据 `customProperties`(`RawAppliedLensShadingMetadata`,与 `RawPhotonHdrMetadata` 同一机制;float32 小端 Base64 + 尺寸 + 契约名);单帧保存时清除该项。所有渲染入口(`PhotoProcessor` 2 处、`GalleryManager` 5 处)读取后经 `RawDemosaicProcessor` 的 `appliedLensShading` 参数写入 `RawMetadata.appliedLensShading`。它与“待施加增益图”(`lensShadingMap`)分开,后者仍按现状清空,DNG 配置不会重复施加 LSC;用户关闭 LSC 的偏好也只影响后者。
合成施加 LSC 的方式(已核实,`GlesMgcRawSpatialShaders` normalizeRgb / normalizeAotRgb、`GlesMgcRawSabreShaders` 输出变换):合成后在 RGB 上乘增益,采样坐标为整幅输出图 UV `(p + 0.5) / outputSize`,双线性,G 取两个绿色位点增益的均值,通道顺序为 Camera2 的 R, Ge, Go, B。持久化增益图与其宽高即可精确还原。
没有任何增益图(设备不提供 LSC)时 `g ≡ 1`。
### 3.3 增益纹理
由增益图生成 1/4 分辨率 `RGBA16F` 纹理 `(g_R, g_G, g_B, ·)`。采样坐标与 VGN 一致(DNG 网格或 Camera2 网格、bounds origin),复用 `lensShadingGainAt` 的映射逻辑,保证除掉的正是施加的增益。
## 4. 金字塔
### 4.1 工作域
```
x_wb = W · (rgb_camera / g) (除 LSC 增益、白平衡后的线性相机 RGB)
[Y, Cb, Cr]ᵀ = M · x_wb · K
```
- 必须在任何非线性(色调曲线、gamma、LUT)之前。线性域内噪声零均值,色度降噪不会产生去饱和偏差。
- `M` 取可逆矩阵 `Y = (R + 2G + B)/4, Cb = B − G, Cr = R − G`:灰轴上 `Cb = Cr = 0`,色度零点与中性色一致;全部系数为 2 的幂,fp16 下无额外舍入。
- `K` 为数值缩放:`K = min(2^12, 2^15 / maxSignal)`,使读出噪声远离 fp16 次正规区,同时为 HDR 合成留出余量。§2.1 的 `A` 含 `K`。
### 4.2 分解
降采样拉普拉斯金字塔(Burt–Adelson):
```
G_{l+1} = ↓2 (h * G_l)
L_l = G_l − ↑2 (2h * G_{l+1}) (二维增益 4)
G_l = L_l + ↑2 (2h * G_{l+1}) (按构造完美重建)
```
`h` 直流增益为 1,因此 `G_l` 保持信号均值,`μ` 在所有层级同义。
| | 亮度 `h_Y` | 色度 `h_C` |
|---|---|---|
| 滤波器 | `[-1, 0, 9, 16, 9, 0, -1] / 32`(4 点 Deslauriers–Dubuc,`H(π)=0`) | `[1, 4, 6, 4, 1] / 16`(二项式) |
| 选择理由 | 频带选择性好,层间混叠小,纹理细节集中在本层 | 无负瓣,色边界处不振铃、不产生彩边 |
| 层数 | 5 个细节层 + 基底 | 自适应:直到某层预测色度噪声标准差低于 `0.25·LSB_K`,上限 7 层 |
两者都是奇长度对称滤波,降采样网格不偏移半像素。
### 4.3 处理顺序
```
分解:G_0 → G_1 → … → G_N
合成(自粗到细):
G̃_N = G_N (基底不处理,其噪声已可忽略)
for l = N-1 … 0:
base = ↑2 (2h * G̃_{l+1})
L_l = G_l − ↑2 (2h * G_{l+1}) (带噪拉普拉斯,现场计算不落盘)
Σ_l = §2.1,μ 取 base
Ỹ 层 = base_Y + ShrinkLuma(L_{Y,l}, …)
C̃ 层 = base_C + ShrinkChroma(L_{C,l}, …, 亮度引导)
G̃_l = (Ỹ, C̃)
输出:M⁻¹ / K⁻¹ / W⁻¹,乘回 g
```
## 5. 管线与调参表
各管线的噪声与理论值的偏差不同(§2.5),调参表按管线分开:
| 管线 | 输入 | `m` |
|---|---|---|
| `VGN` | 标准 Bayer 单帧 | 1 |
| `QUAD` | Quad Bayer 单帧 | 1 |
| `SABRE` | Sabre 合成(RGB 输出) | §2.2 |
| `SPATIAL` | Spatial RGB 合成(CPU AOT) | §2.2 |
| `BITMAP` | 无 RAW 档案的 Bitmap / JPEG | §9 |
调参坐标为档案给出的中灰相对噪声 `n = √(m · v_Y(0.18)) / 0.18`,`v_Y` 为 §2.1 中亮度分量的点方差(不含 `κ⁰`、`K`)。
调参表在 `PhotonDenoiseTuning`:每条管线一组按 `n` 排序的节点,节点字段与 `tune.py` 的输出一致(`α_l, t_l, d_l`、两组门限、联合双边层数与系数);节点之间按 `ln n` 线性插值(层数取较近节点),两端外取端点值。调参前每条管线只有同一个默认节点。
### 5.1 逐图噪声强度
§2.1 模型给出噪声的**形状**:随信号的 read / shot 两项、LSC、§2.2 合成方差图、§2.4 残余比、去马赛克后各层的相对比例。它的**大小**与实际不符,且因传感器、增益、管线而异:去马赛克与传感器自身的噪声相关性把能量推向粗层,档案在高增益下偏高 1.6–1.8 倍,低增益下暗部偏低;同一张图内“实际 / 模型”还随亮度变化,高 ISO 暗部低于亮部,ISO 100 相反。App 面向所有机型,不能按镜头逐个调表,因此每张图在降噪前估出自己的强度表。
**强度表** `S[l][b][c]`:`l` 为金字塔层(全部层),`b` 为 8 个亮度档(`log₂(Y/K)` 在 `[−8, 0]` 上每档 1 级,档中心 `b + 0.5 − 8`),`c ∈ {Y, Cb, Cr}`。Band 按本层基底亮度在档中心之间对 `log₂` 线性插值(两端外取端点),模型方差 `Y, Cb, Cr` 分别乘 `S_Y, S_Cb, S_Cr`,`Cb–Cr` 协方差乘 `√(S_Cb S_Cr)`。
**估计**(GPU,分析金字塔建好之后、合成之前;`PhotonNoiseEstimator`):
1. 逐层取 `L = G_l − ↑G_{l+1}`、`base = ↑G_{l+1}`(均为未降噪金字塔),按 §2.1(含 §2.2、§2.4,不含强度)算模型方差 `N_c`;截断像素、`N_c ≤ 0` 的像素、基底绿色信号不为正的像素(黑边)不参与。
2. 抽样:第 0 层每 4 像素、第 1 层每 2 像素取一个样本,每 2×2 个样本错开一个像素以覆盖四个 Bayer 相位;更深的层取全部像素。平坦门:粗层 `G_{l+1}` 的亮度中心差分(折算到本层像素)`|∇G_{l+1,Y}| / 4 < 0.5 √(g_l · N_Y)`,`g_l` 第一轮为 1,之后取上一轮本层 8 个亮度档强度的中位数。门限若只按模型 σ,实际噪声远高于模型时(Bitmap 的名义参考噪声为一个码值,实际是其数十倍)几乎所有平坦像素都被基底中的噪声梯度挡住;共 3 轮,Bitmap 实测第 2 轮起收敛,RAW 的结果变化在 10% 以内。
3. 每个 (层, 亮度档, 通道) 统计 `log₂(L_c² / N_c)` 的 64 桶直方图(`[−12, 8)`,工作组内共享内存累加后并入全局计数)。
4. 解析:桶内线性插值求中位数,除以 χ²₁ 的中位数 0.4549 得到方差比;样本少于 200 的档为空。每层每通道的空档按档序号在已测档之间线性插值、两端外取最近已测档;随后每档限定在相邻 5 档(含自身,边缘取实际存在的档)中位数的 `[1/1.5, 1.5]` 倍之间——纹理占据单个亮度档时该档孤立偏高(10x 合成 1793253630461 的 L2 / L3 有 19、30、55 而相邻档 4–7),样本少的档可能孤立偏低。整层没有已测档时,取上两层逐档比值的中位数(限定在 1–2)乘上一层,第 0 层为 1:实测各管线的强度都随层级增长,沿用上一层会系统偏低。结果限定在 `[0, 4096]`。
5. **上限**:盲估计无法区分与噪声能量相当的细纹理(附录 C),纹理落在某个亮度档时,该档被估高,表现为抹平细纹理。纹理与噪声幅度接近时误判代价最大,这发生在高 SNR;低 SNR 下噪声远大于纹理,估计可靠。因此每层的上限按整图 SNR(下方定义)在节点 5 / 20 / 40 之间对 ln SNR 线性插值、两端外取端点(`PhotonDenoiseTuning.ESTIMATE_CAP`,L4 之后沿用 L4):
| 上限(SNR 5 / 20 / 40) | 亮度 | 色度 |
|---|---|---|
| L0 | 2 / 1.5 / 0.75 | 1 / 1 / 1 |
| L1 | 4 / 3 / 1.25 | 1 / 1 / 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 之间还没有实拍样本。
**整图 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。
**来源**:
| 输入 | 强度表 |
|---|---|
| 单帧 `VGN` / `QUAD` | 每次渲染时盲估计 + 上限 |
| 合成 `SABRE` / `SPATIAL` 默认降噪 | 盲估计 + 上限(阶段 A);阶段 B 改为半合成差分 |
| 合成图的用户调整 | 默认降噪时的强度表,随 `RawDenoiseHistory` 持久化;无记录时盲估计 + 上限 |
| `BITMAP` | 每次渲染时盲估计,不设上限(无整图 SNR,§9) |
**阶段 B:半合成差分(多帧)**。合成时把各帧轮流累加到 A、B 两组累加器(参考帧在 A),全合成为两者之和;`D = M_A − M_B` 中场景内容抵消,只剩噪声。按逐像素的帧权重和与平方和,`r = Var(M) / Var(D) = [(Q_A + Q_B)/(W_A + W_B)²] / [Q_A/W_A² + Q_B/W_B²]`,`Ñ = √r · D` 与 `M` 的噪声同分布,且包含合成核的低通效果(§2.5)。`Ñ` 加到 `M` 上再走一遍解析与输出变换,`X' − X` 即经过真实去马赛克的噪声样本;估计步骤 1 的 `L` 换成 `L(X') − L(X)`,不设平坦门,只排除任一半接受度不足的区域,也不需要上限。代价是第二套累加器与第二次解析(Sabre、Spatial 的解析在 CPU AOT 上),实施前先测这部分耗时。
**验证**(numpy 原型,2026-10-29):
- 设备导出(阶段 A 首版):GPU 估计值与按基底梯度选平坦像素的离线实测逐档一致(单帧 3x / 10x,ISO 9100);10x 合成偏低来自上限,按上表放宽后色斑明显减少。暗部仍有孤立的彩色亮点(重尾冲激噪声),中位数估计与色度门控都不针对它,另行处理。
- Bitmap(1793253833193,3072×4096):L0 亮度在暗档约 26、亮档约 210,L1 85–440,原固定值 0.6 / 9.6 低一到两个数量级;按估计值降噪后平坦区明显更干净,叶片边缘保留。
- 3x 镜头单帧(ISO 9100,SNR 5.3):估计后各层各档“实际 / 估计”0.87–1.10;平坦区残余亮度 L0–L3 为 1–12%。原先按另一颗镜头测的固定表在这张图上偏低 1.7–3.3 倍,残余 14–43%。
- ISO 100 纹理场景(Sabre 1793243503594,SNR 91):不设上限时暗档 L0 / L1 被深色材料的细纹理估到 2.5 / 4.1,纹理被抹平;在亮度档内再按空间分块取低分位无改善(暗档内没有平坦区域);加上限后与原固定表的结果一致。
- 与附录 C 的关系:附录 C 要求单图估计在所有场景(含纹理铺满)都准确,未能达到;这里不再要求,纹理场景的误差由按 SNR 收紧的上限限定在可接受范围,多帧则由阶段 B 绕开盲估计。
**原实测强度图**(2026-10-29,按管线 × 整图 SNR 节点的固定表,已删除)只作为验证记录:VGN 来自 1793246008853(ISO 6375,SNR 5.3)与 1793250894093(ISO 9052,SNR 8.8);SABRE 来自 1793245968158(ISO 5769,SNR 15.8)与 1793243503594(ISO 100,SNR 91);SPATIAL 来自 1793245987100(ISO 6253,SNR 14.2)与 1793243490454(ISO 100,SNR 86)。同一 SNR 下 3x 镜头与上述镜头相差 1.7–6 倍,这是改为逐图估计的直接原因。
## 6. 亮度算法
侧重点:**保留纹理与边缘,避免涂抹感;接受可控的细颗粒**。对应 Pecan 的特征:更锐的分解滤波、每层强度、离群距离、细节回填(revert)。
### 6.0 第 0 层离群点预滤波
去马赛克让噪声在空间上相关,暗部出现 2–3 像素的小团(输入 L0 带中约 2.5–3σ)。§6.1 的窗口里,团内各点互为高权重邻点,能量由小团自身撑起,收缩后成片保留,提亮后可见。把 Huber 基准换成 3×3 中值无效(实测斑点数不降),因此在分解前对第 0 层亮度做条件中值:
```
m = G0_Y 的 3×3 中值
σ² = §2.1 第 0 层亮度模型方差 × §5.1 强度(在未降噪的 ↑G1 上)
替换条件:|G0_Y − m| > 2.5σ
且 3×3 内与中心同号、偏离超过 2.5σ 的邻点不多于 2 个(线条至少有 2 个,保留)
且 5×5 内 L0² 的均值(不含中心)< 3σ²(邻域像噪声;纹理区远高于此)
G0_Y += (m − G0_Y) · min(s_Y, 1)
```
只改第 0 层的细节层输入(`G1` 及更粗的层仍来自原图,强度估计在预滤波之前)。实拍(4096×3072 单帧 ISO 694,暗部提亮约 40 倍):替换约 2.6% 的像素,斑点数 772 → 28;纹理区(灯阵、标识文字)与原输出的相对均方差约 2%,肉眼无差别。门限按模型 σ 而不是邻域 MAD:MAD 混入低频起伏,同样参数下只减少到 338。
### 6.1 逐层收缩:两阶段经验 Wiener
对 `L = L_{Y,l}(p)`,`σ² = σ²_{Y,l}(p)`:
1. **结构张量**:在 `G̃_{Y,l+1}`(已降噪,噪声小)上计算结构张量,得到局部主方向与各向异性度 `a ∈ [0,1]`。
2. **导向能量估计(pilot)**:在沿边缘方向拉长的椭圆窗(平坦区退化为 5×5 圆窗)内,以 Huber 权重估计信号能量:
`Ê = max( Σ_q w_q (L_q² − σ_q²) / Σ_q w_q , 0 )`。Huber 权重对 `|L_q − L_p| > d_l·σ` 的邻点降权,`d_l` 即“离群距离”,防止一侧强边缘污染另一侧的能量估计。中心点的权重另乘 `smoothstep(6, 10, |L_p|/σ)`:Huber 以中心为基准,中心只要偏出约 `d_l·σ`,所有邻点都被降权,能量几乎只来自中心自身,这个噪声点就自我保留——实拍(4096×3072 单帧 ISO 694,2026-11-04)中这类点在提亮后成片可见;10σ 以上的真实点(星点、高光点)仍按原规则计入。
3. **pilot 收缩**:`ŝ₁ = L · Ê / (Ê + α_l σ²)`。
4. **第二阶段**:在同一窗内用 `ŝ₁²` 重估信号能量 `Ê₂`,增益 `g = Ê₂ / (Ê₂ + α_l σ²)`,最终 `ŝ = L · g'`,`g' = g + smoothstep(0.25, 0.5, g) · (g^{γ_l} − g)`。两阶段可抑制单阶段经验 Wiener 的“音乐噪声”(孤立残留斑点)。
`α_l = 1`、`γ_l = 1` 即模型噪声下的最小均方误差(MMSE)估计。MMSE 把与噪声同量级的细节压掉一半左右:人像(4096×3072 单帧 ISO 694,2026-11-05)脸部 L1 / L2 在局部 `E/N` 1.5–3 的像素上只保留 0.52 / 0.54 的信号幅度,这类像素占脸部 L1/L2 的 40–50%,脸部发虚,锐化补不回(L0 在脸部几乎没有信号)。`γ_l = 0.5`(L0–L2)在这段保留约 0.7。全局 `g^γ` 会把纯噪声区的小增益(0–0.3)放大成 0.3–0.55,暗部提亮后的斑点从 28 个回到 443 个;只在 `g ≥ 0.25` 起渐入,纯噪声区保持 MMSE(斑点 65 个,观感与 MMSE 相同),脸部清晰度与全局 `γ` 相同。
### 6.2 颗粒保留(替代 revert factor)
```
out = ŝ + β_l · (L − ŝ)
```
在平坦区(`Ê ≈ 0`)残余噪声标准差为 `β_l σ`,因此 `β_l` 的物理含义是**本层保留的原始噪声比例**。调参参数直接写为目标残余噪声比 `t_l`,`β_l = t_l`。中高频层的少量颗粒保留是避免“塑料感”的主要手段。
### 6.3 层间分工
| 层 | 内容 | 典型设置 |
|---|---|---|
| L0 | 像素级细节、高频噪声 | `t` 较高,窗口小(3×3 + 方向拉伸) |
| L1–L2 | 主要纹理 | MMSE,`t` 中等 |
| L3–L4 | 低频亮度斑块 | `t` 低、`α` 略高,暗部低频起伏是高 ISO 的主要观感问题 |
### 6.4 调参参数
每条管线、每个噪声水平节点 `n`、每层:`α_l, t_l, γ_l, d_l`。由 §12.2 的离线 PSNR 优化得出,不从 MGC binarypb 换算,因为两者参数语义不同。§2.5 的系统误差使不同管线、不同层的最优 `α_l` 偏离 1,偏离量与 §12.1 测得的模型误差一同记录,便于判断调参是否在弥补模型误差之外引入了别的偏差。
### 6.5 截断区域
信号接近白点(含合成后的 HDR 白点)或被钳位到 0 的像素:噪声方差视为 0,在能量估计中权重置 0。高光内部不降噪,也不让截断像素参与邻域统计。
## 7. 色度算法
侧重点:**彻底消除低频色斑;色边界不渗色、不振铃;不降低饱和度;不保留色颗粒**。对应 MGC ChromaDenoise 的特征:更平滑的滤波器、按通道的噪声方差、离群阈值、更依赖粗层。
### 7.1 向量化处理
`(Cb, Cr)` 作为二维向量处理,使用 §2.1 的 2×2 协方差 `Σ_C,l(p)`(含 Cb–Cr 互协方差)。距离采用马氏距离 `D² = Δcᵀ Σ_C⁻¹ Δc`,各向同性阈值在色度空间中自动随噪声形状变化。
### 7.2 亮度门控的细节层
色度细节层 `L_{C,l}` 绝大部分是噪声。保留规则:
```
ζ_Y = 亮度 pilot ŝ₁ 在 3×3 内的显著度 = Σ ŝ₁² / Σ σ_Y² (亮度不处理的层用 L_Y)
ζ_C = L_Cᵀ Σ_C,l⁻¹ L_C (马氏距离平方)
gate = max( smooth(ζ_Y; χ²_9 分位 τ_Y), smooth(ζ_C; χ²_2 分位 τ_C) )
out = gate · L_C
```
- 亮度边缘处的色度细节保留(真实颜色边界几乎总伴随亮度边界);
- 等亮度色边缘由色度自身马氏距离超阈保留(`τ_C` 即离群阈值,以卡方分位数表示);
- 其余细节清零,不做颗粒回填(`t_C = 0`)。
`ζ_Y` 使用亮度 pilot(已收缩的亮度带)与其模型方差:用带噪亮度带时,一个亮度噪声点会打开色度门,留下彩色点。pilot 在融合 dispatch 的共享内存中已有,亮度与色度仍在同一 dispatch 内完成。
### 7.3 粗层联合双边滤波
亮度门控只处理细节层;低频色斑存在于粗层的高斯层本身。对色度最粗的 2–3 层,在 `base_C` 上额外做亮度引导的联合双边滤波:
```
w(p,q) = 空间核 · exp(−‖Ỹ_p − Ỹ_q‖² / (2 c_Y σ²_{Y,l})) · exp(−D²_C(p,q) / (2 c_C))
```
`Ỹ` 用本层已降噪亮度。亮度距离以本层亮度拉普拉斯的模型方差 `σ²_{Y,l}` 为单位,色度距离为马氏距离,`c_Y, c_C` 为无量纲调参量。
### 7.4 调参参数
每条管线、每个噪声水平节点:`τ_Y, τ_C`(卡方分位)、联合双边层数与 `c_Y, c_C`、各层 `α_C`。
## 8. 用户强度映射
`DenoiseStrength` 范围 `0..2` 保留,只作用于估计器的激进程度,不修改噪声模型:
| 强度 `s` | 亮度 | 色度 |
|---|---|---|
| `0` | 关闭 | 关闭 |
| `0 < s ≤ 1` | `t_l(s) = 1 − s·(1 − t_l)`,`α = α_l` | 门控输出 `= s·gate·L + (1−s)·L` |
| `1 < s ≤ 2` | `t_l → t_l·(2 − s)`,`α = α_l·s²` | 阈值分位上移、联合双边 `c_C·s²` |
`s = 1` 等于调参默认值。
## 9. Bitmap / JPEG 路径
Bitmap / JPEG 已经过 ISP:即使关闭机内降噪与锐化,输出的噪声也已被处理过(细层基本被抹去,残余集中在中低频,色度更明显),没有可用的噪声模型,也不做测量(2026-10-29 对一张 JPEG 的测量中,L0 只剩 8 位量化,粗层的"噪声"主要是处理残留与画面缓变,色度在亮部被量化到中位数绝对偏差为 0,无法作为强度依据)。因此该路径做**盲降噪**,强度不来自噪声模型:
1. 不线性化,直接在 sRGB 编码值上降噪:JPEG 的残余噪声在编码域近似与亮度无关。`W = I`,`g ≡ 1`,`m = 1`;
2. 参考噪声为恒定的一个 8 位码值(`r = (1/255)²`,`s = 0`,三通道相同),只作为强度的单位;
3. 各层强度由 §5.1 的逐图估计给出(相对一个码值的参考噪声,不设上限)。此前用参考 JPEG(导出 1793245183659,3072×4096)测得的固定强度(亮度 L0–L4 0.6 / 9.6 / 57 / 209 / 209,色度 0.046 / 0.55 / 2.3 / 15 / 105)不随图片变化,在其他 JPEG 上偏低一到两个数量级,已删除。ISP 处理后的残余噪声从 L1 起是几个码值的成片起伏,越往粗层越强,且随图片差异很大;
4. 用户的亮度、色度强度按 §8 分别作用,与 RAW 路径相同;
5. 降噪前先把输入复制为 `RGBA16F`,降噪后再复制回原纹理;调试导出写的就是这张 `RGBA16F` 输入(文件名 `<时间>_BITMAP_EDIT_<原点>`,`.json` 中没有 RAW 元数据)。
实现:`LutImageProcessor.renderBitmapPhotonDenoise` → `PhotonNoiseModel.buildBitmap` → 本降噪器。编辑预览、导出与相册 AI 前置色度(`applyChromaDenoise`,只开色度)共用;相册 AI 前置色度使用的处理器实例没有 `Context`,不会导出。
## 10. GPU 实现
遵循 `docs/gles-driver-compatibility.md`:所有浮点 sampler 显式 `highp`;`RGBA16F` image 只写、ping-pong,不原位读写;全帧纹理,不分条带;分配前查询 `GL_MAX_TEXTURE_SIZE`。
### 10.1 Pass
| # | Pass | 输入 → 输出 |
|---|---|---|
| 1 | LscGain | 已施加增益图 → 1/4 分辨率增益纹理(§3.3) |
| 2 | Analyze₀ | 相机 RGB → 除增益、白平衡、`M`、`K` → `G1`(`G0` 现场计算,不落盘) |
| 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 时跳过 |
| 4 | Synthesize_{N−1…1} | 每层一个融合 dispatch:共享内存分块计算 `L_l`、`base`、§2.1 协方差与亮度 pilot,再做第二阶段收缩 + 色度门控 + 粗层联合双边,输出 `G̃_l` |
| 5 | Synthesize₀ + Output | 第 0 层同一融合 dispatch,与 `M⁻¹ / K⁻¹ / W⁻¹`、乘回 `g` 合并,直接写相机 RGB 输出纹理 |
所有 pass 用 shared memory 瓦片(含滤波器与窗口所需的 halo),工作组尺寸只依赖 GLES 3.1 的最低保证。
大 pass 按工作组行分带提交(Analyze 每带 ≤16384 组、Synthesize ≤8192 组即约 52 万像素、Estimate ≤128 组即约 52 万样本),带之间 `GlesGpuScheduler.waitForGpuCheckpoint`:整帧一次 dispatch 会让 GPU 连续被占用数百毫秒,UI 掉帧;各带写入互不重叠,pass 的 barrier 放在最后一带之后。
### 10.2 存储
- 金字塔层:`RGBA16F`(Y, Cb, Cr, 空),`K` 缩放保证精度。
- 第 0 层不存 `G0` 和 `G̃0`;总额外显存约为 `(1/4 + 1/16 + …) × 2`(`G` 与 `G̃`)≈ 0.67 张全分辨率 `RGBA16F`,外加增益纹理。
- 所有方差运算在着色器中以 `highp float` 进行。
- 噪声 UBO:档案系数、`A`、`κ⁰[k][l][φ]`、`t²_{k,l}`、调参参数,每次渲染上传一次;合成方差图 `(m_r, m_s)` 为 `RG16F` 纹理(单帧为 1×1 的常量 `(1, 1)`)。
### 10.3 接入点
| 路径 | 当前 | 新 |
|---|---|---|
| 路径 | 原实现 | 现实现(第 6 步已接入) |
|---|---|---|
| Spatial / Sabre 默认降噪(`processMgcSpatialGpuLinearRgb`) | 回读 → MGC CPU → 上传 | 直接对 `workingFloatTexture` 运行,输出转 RGBA16UI;不再有 CPU 回读边界 |
| 用户调整(整图与分块,`renderPhotonUserAdjustmentDenoise`) | MGC,失败时回退 NLM + 色度 | 唯一路径,无回退;没有 RAW 噪声档案时不降噪并记录日志 |
| Bitmap 编辑(`LutImageProcessor`) | NLM + 色度 | §9 |
| 相册 AI 前置色度(`GalleryViewModel` → `applyChromaDenoise`) | 色度降噪 | §9,只开色度 |
拍摄时的强度(`CameraViewModel.resolveCaptureDenoiseStrengths`):设置中的 RAWmax 亮度 / 色度强度,合成拍摄写入默认降噪(可编辑初始值为 0);单帧 RAW 没有默认降噪,同一强度作为可编辑初始值,由用户调整降噪施加。
## 11. 实现的正确性
`κ⁰` 与 §2.1 协方差的计算有 numpy 参考实现(`tools/photon_denoise/noise_model.py`),着色器与 Kotlin 实现逐项与之比对。
## 12. 验证
### 12.1 模型误差测量(记录,不作门禁)
同一静止场景、同一参数拍两次(三脚架、遥控或定时快门;合成管线为两次独立合成),经 App 管线处理到降噪入口后导出(debug 属性 `debug.photon.denoise.dump`,每次写 `<stem>.{json,rgba16f,params.json}`)。两幅图的拉普拉斯层相减再除以 `√2`,信号抵消,方差即单幅图的真实噪声方差。离线工具 `tools/photon_denoise/model_error.py` 按管线、层、相位、亮度箱、ISO 计算“真实 / 模型”之比与 Cb–Cr 相关系数,并输出 §13 记录表的行。
工具细节(已实现):
- 两幅图各自用降噪器的金字塔分解;模型方差按两幅图上一粗层高斯层的均值计算(模型 `r + sμ` 对 `μ` 线性,噪声均值不带来偏差)。
- 错位保护:同层高斯差分 `G_l^A − G_l^B` 的任一分量超过所在亮度箱稳健标准差(MAD)的 4 倍时剔除,再膨胀 3 像素;判定只用数据本身,不依赖被检验的模型。4σ 截断对纯噪声的方差影响约 0.07%。保护针对场景变化(移动物体);亚像素或 1 像素的整体错位残余与单像素噪声同量级,任何统计判据都无法分离,只能由拍摄规程排除。
- 自测 `--self-test`:白噪声(模型在此精确成立)加一个只出现在 B 中的移动物体,2048×1536、5 层。在亮度 ≥ 2⁻⁷ 的箱上,比值偏差最差为容差(5% 与 4 倍标准误取大)的 0.78 倍,Cb–Cr 相关为 0.62 倍,通过。更暗的箱如实报告但不参与判定:那里粗层底图自身的噪声超过信号,模型中的 `max(μ, 0)` 使预测方差偏大(最暗箱比值约 0.93),这是降噪器在最深暗部的真实模型误差。
该比值不进入算法。它用于:判断 §2.5 各项误差的实际大小;解释 §6.4 调参中 `α_l` 偏离 1 的原因;发现档案本身的错误。
### 12.2 合成真值 PSNR 与 DnCNN 对照
内置 `assets/dncnn.tflite`(`ml/DnCNNDenoiseEstimator`)已核实的特性(用 LiteRT Python 加载检查):
| 项 | 结果 |
|---|---|
| 输入 / 输出 | `image [1,256,256,1] float32` → `denoised_image [1,256,256,1]`,**单通道** |
| 结构 | 17 层 `CONV_2D` + `SUB` + `MINIMUM`:标准 DnCNN 深度,内部做残差学习(输入减去预测噪声),输出直接是降噪结果 |
| 预处理 | `native-lib.cpp` 中 `preprocessNative`:8-bit sRGB `/255`,单通道模型取 `0.299R + 0.587G + 0.114B` |
| 噪声输入 | 无 σ 输入,是盲去噪 |
| 实测有效范围(平坦 0.5 灰 + AWGN,8-bit 刻度) | σ=10 → 残差 0.42;σ=25 → 1.28;σ=50 → 35.99(失效)。有效范围约为 σ ≤ 25–30 |
| 训练噪声类型 | 无法从模型文件确定;行为与 AWGN 训练的盲 DnCNN 一致 |
推论:DnCNN 只能对照**亮度**;色度算法没有 DnCNN 基线。测试集需要按显示域等效 σ 分组,超出 σ≈25 的组单独报告,不与 DnCNN 比较。
对照协议:
1. **干净参考**:基础 ISO 三脚架多帧合成,再做 2×2 binning,得到线性干净图像 `x`。
2. **带噪输入**:同一场景按调参节点的 ISO 实拍(单帧与各合成管线),经实际管线;与 `x` 配准、曝光对齐。
3. **本算法**:实际管线 → 本降噪 → 固定参考渲染(固定白平衡、矩阵、sRGB 曲线,无局部影调)。
4. **DnCNN**:实际管线 → 同一固定渲染 → 8-bit → 取亮度(与 `preprocessNative` 相同的系数)→ DnCNN,256×256 分块,重叠拼接。
5. **指标**:
- 亮度:在固定渲染后的 sRGB 亮度上,对真值的同一亮度计算 PSNR / SSIM,本算法与 DnCNN 并列;
- 全色彩:本算法在 sRGB 与线性域各算 PSNR,并报告 CIEDE2000 色差,用于评估色度(无 DnCNN 对照);
- 按亮度分箱(暗部、中间调、高光)以及按显示域等效 σ 分组分别报告。
6. **解读**:DnCNN 在空间变化、信号相关的噪声上处于训练分布之外,且受 8-bit 量化和 σ≈25 有效上限的限制。它作为亮度参照基线,不作为必须超越的门槛。§6.4、§7.4 的调参以本项 PSNR 为优化目标。
### 12.3 实拍
无真值实拍做方法噪声检查(平坦区 `(输入 − 输出)` 的方差应接近 `(1 − t²)σ²`,与输出梯度的相关应接近 0)与主观评审。DnCNN 输出不作为实拍的 PSNR 参考。
### 12.4 工具
- `tools/photon_denoise/`(uv 管理):`noise_model.py`(`κ⁰` 与协方差参考实现)、`validate_model.py`(§16 第 1 步门禁)、`validate_propagation.py`(`κ⁰` 传播的门禁)、`photon_denoise.py`(逐 pass 数值参考)、`compare_passes.py`(设备逐 pass 比对)、`model_error.py`(§12.1)、`image_metrics.py`(固定参考渲染、PSNR / SSIM / CIEDE2000、DnCNN 推理(LiteRT Python))、`tune.py`(§12.2 对照与参数搜索)。
- 设备端:debug 构建中以属性 `debug.photon.denoise.dump` 在降噪入口导出相机 RGB 浮点纹理、元数据(档案、白平衡、增益图、管线、帧数)与本次的模型参数(`<stem>.params.json`);另设 `debug.photon.denoise.parity` 时追加运行本降噪器并导出逐 pass 纹理(约 350MB / 6MP,供 `compare_passes.py`)。
## 13. 模型误差记录
§12.1 的测量结果按下表记录。每行由 `model_error.py` 直接输出:“各层 真实 / 模型”为第 0 层到最深层在最接近中灰(0.18)的已测亮度箱上的相位平均比值,“Cb–Cr 相关”为各层“实测 / 模型”相关系数。完整的按层 × 亮度箱 × 相位明细随工具输出一同保存。
拍摄规程:
1. 三脚架固定,遥控或定时快门;静止场景,含灰阶卡、彩色色块、大面积平坦区与纹理区;光源稳定(避免频闪)。
2. 设置 `debug.photon.denoise.dump=true`;每个组合连拍两张:合成管线(Sabre、Spatial)直接拍摄即导出默认降噪入口;单帧管线(VGN、Quad Bayer)拍摄单帧 RAW 后在编辑中把降噪调到大于 0,导出用户调整入口。
3. 覆盖:每条管线 × ISO(基础值到最高,约每 1 EV 一档)。
4. `adb pull` 导出目录后运行 `model_error.py A.json B.json …`,把输出的 §13 行追加到下表。
| 管线 | ISO | 分量 | 各层 真实 / 模型(中灰) | Cb–Cr 相关(实测 / 模型) | 备注 |
|---|---|---|---|---|---|
| — | — | — | — | — | 尚未拍摄 |
## 14. 代码结构
```
raw/denoise/
PhotonNoiseModel.kt §2 档案系数、m、κ⁰、残余比、调参 → PhotonDenoiseParams;LSC 增益图(PhotonLensShading);§2.4 输出残余比
PhotonMergeNoise.kt §2.2 合成方差比
PhotonNoisePropagation.kt §2.3 κ⁰(白噪声传播)
PhotonDenoiseTuning.kt §5 各管线调参表与插值,§5.1 估计上限,§9 Bitmap 名义档案与固定强度
PhotonDenoiseShaders.kt Analyze / Estimate / Resolve / Synthesize(融合)着色器;工作 YCbCr 矩阵与两组滤波器系数;LSC 增益在着色器中双线性采样
PhotonMultiScaleDenoiser.kt GLES 编排、资源管理
PhotonDenoiseDump.kt §12.4 调试导出(debug)
raw/RawAppliedLensShading.kt 已施加 LSC 增益图及其相册元数据(§3.2)
raw/RawDenoiseHistory.kt 管线、合成方差比、残余比、强度表及其相册元数据(§2.2、§2.4、§5.1)
raw/RawMetadata.kt appliedLensShading、denoiseHistory 字段
cpp/mgc_denoise_static/mgc_halide_runtime.cpp 共享 Halide 运行时(分配、并行、错误钩子),供其余 MGC capsule 使用(§15)
cpp/mgc_denoise_static/mgc_denoise_static.cpp 只剩锐化与引导上采样 AOT 的包装
cpp/mgc_denoise_static/mgc_guided_prepare_adapter.h 引导上采样的线性 YUV 前向矩阵与白盒 YuvToRgb(§15)
```
调参表以 Kotlin 常量(或 JSON asset)保存,替代 `assets/mgc_denoise/*.binarypb`。
已有代码的去留:
- `raw/denoise/PhotonNoisePropagation.kt` 与 `tools/photon_denoise/noise_model.py`、`validate_propagation.py`:保留,`κ⁰` 的计算与验证。
- `raw/denoise/PhotonNoiseState.kt`:源通道传递矩阵与谱的模型不再使用;工作 YCbCr 矩阵(含精确逆)并入 `PhotonDenoiseShaders.kt`,档案到工作域协方差的计算并入 `PhotonNoiseModel.kt`,其余删除。
- `tools/photon_denoise/noise_estimator.py`、`validate_estimator.py`:实测方案已放弃(附录 C),已删除。
## 15. 移除清单
已核实的依赖关系(各 capsule 导出符号与引用):
| 符号 / 代码 | 所在 | 降噪以外的使用者 | 处理 |
|---|---|---|---|
| Halide 运行时(`photon_mgc_halide_malloc` 等 hidden 符号、`HalideDoParFor`) | `mgc_denoise_static.cpp` | **所有 capsule**(guided upsample、polysharp、raisr、sabre resolve、sharpen、spatial rgb merge) | 拆到 `mgc_halide_runtime.cpp`,保留 |
| `photon_mgc_yuv_to_rgb_s16` / `RunYuvToRgb` | 完整分辨率降噪 capsule | **`mgc_guided_upsample_jni.cpp:82`**(低分辨率 YUV → RGB) | 按 `mgc_guided_prepare_adapter.h` 中 `GuidedFloatRgbaToLinearYuv` 的做法,从 AOT 中恢复其定点逆矩阵与舍入顺序,写成白盒特化;与 AOT 逐位一致后再移除 capsule |
| `photon_mgc_compute_{bayer,rgb}_noise_model_f32_tile_size_16`、`photon_mgc_downsample_*` | 完整分辨率降噪 capsule | 仅 `ComputeSpatialStrengthMap` | 随其移除 |
| 锐化 YUV 矩阵 | `mgc_sharpen_jni.cpp:15` 自带一份 | — | 不受影响 |
| guided prepare 输入 | `RawDemosaicProcessor.kt:3934` 使用降噪输出纹理 | — | 只依赖纹理,不受影响 |
capsule 生成脚本 `scripts/research/generate_mgc_denoise_static_asm.py`(CMake 报错信息中引用)已不在仓库,无法裁剪 capsule 只保留部分符号。新设计不需要 `ComputeSpatialStrengthMap`,因此 `RunYuvToRgb` 白盒化之后,**完整分辨率降噪 capsule 整体移除**。
移除项(第 6、7 步已全部完成):
- `MgcFullResolutionDenoise.kt`,`mgc_full_resolution_denoise_jni.cpp`、`mgc_full_resolution_denoise_capsule.bin`、`mgc_full_resolution_denoise_static.S.in`
- `mgc_demoire_capsule.bin`、`mgc_demoire_static.S.in`(MeasureMoire)
- `mgc_denoise_static.cpp/.h` 中全部降噪函数;运行时拆到 `mgc_halide_runtime.cpp`(只保留其余 capsule 引用的 37 个错误钩子),`RunSharpenTo16Bit`、`RunGuided*` 保留
- `RunYuvToRgb`:白盒化为 `GuidedLinearYuvToRgb`(`mgc_guided_prepare_adapter.h`)。系数取自 AOT 入口写入闭包的 4 个常量,`R = Y + rshr(V·25802, 15)`、`G = Y + rshr(V·−15340 + U·−8658, 16)`、`B = Y + rshr(U·21442, 14)`,`rshr` 为带舍入的算术右移,结果饱和到 int16。逐位比对:把 capsule 汇编成目标文件,用 unicorn 在主机上直接执行 AOT 的并行体(宽度为 8 的倍数,不进入尾部;引导上采样的低分辨率宽度恒为 32 的倍数),±32768 边界组合网格与全范围随机输入共 819,200 像素,与白盒公式零差异
- `mgc_spatial_strength_jni.cpp`、`mgc_strength_map_scaler.cpp`、`MgcSpatialStrengthMap.kt`、`MgcSpatialStrengthMapGenerator.kt`、`MgcSpatialStrengthMapScaler.kt`、`MgcSpatialDenoiseModel.kt`;`GlesMgcRawSpatialStacker` 中强度图回读、解算与 Bayer Q14 打包。强度采集本身(`StrengthCapture`)保留并只在 RGB 输出时创建:RGB 合成 AOT 的对齐 / 剔除图集来自它;RGB 合成不再生成只供强度图使用的 Q14 诊断缓冲(`nativeConvertPlanarF16ToFixed16` 删除)
- `MgcSabreMergedNoiseModel.kt`,以及 Sabre 中只为其日志服务的合成因子回读(`readSabreAverageMergeFactor`、`reciprocalGreenWeight4x4`)
- `DemosaicNoisePropagationCalibrator.kt`、`DemosaicNoiseAtlasGenerator.kt`、`DenoiseProfileAlgorithm.kt`、`DenoiseProfileNlmConfig.kt`、`DenoiseProfileStripePlanner.kt`、`lut/ChromaDenoiseAlgorithm.kt`(第 6 步)
- `assets/mgc_denoise/*.binarypb`
- `RawMetadata`、`RawStackResult` 中 `mgcDenoiseReadNoise`、`mgcDenoiseShotNoise`、`mgcDenoiseCorrelation`、`mgcSpatialStrengthMap`、`mgcDenoiseTuningSnr`。这些字段只存在于进程内(DNG 与相册数据库从未保存),无需迁移。单帧的 SNR 测量只保留锐化用的 `mgcSharpenTuningSnr`
- `CMakeLists.txt` 中对应目标与源文件
- 对应的单元测试
Spatial Bayer 合成后去马赛克所用的噪声档案(`spatialOutputNoiseMetadata`)原取自强度图 AOT 的输出模型,改为参考帧 RAW 档案 × §2.2 合成方差比(`DNG_RGB` 布局,`frameCount = 1`),与降噪器使用同一噪声来源。
## 16. 实施顺序与门禁
1. **噪声模型参考实现**:`noise_model.py` 增加 §2.1 的工作域协方差(含 `m`、`t²`)与 `κ⁰` 表输出;`κ⁰` 的传播计算已验证(附录 A)。→ 门禁:合成白噪声(独立源通道、给定档案与 `m`)经本金字塔,各层、各相位协方差与模型之比在 `1 ± 0.03` 内(白噪声满足模型假设,此项检验实现正确性)。
**已完成(2026-10-28)**:`noise_model.py` 新增 `MergeRatio`(§2.2)、`working_point_covariance`(§2.1 点协方差)、`Kappa0`(κ⁰ 表,`python noise_model.py <亮度层数> <色度层数>` 输出 JSON)、`level_noise`(含残余比 `D Σ D`)。门禁 `validate_model.py`:2048²、每组 6 次实现、5 层 × 4 相位,单帧 / 4 帧不等权不等曝光合成(`m_r = 0.2974`、`m_s = 0.2875`)/ 残余比 `(0.5, 0.3, 0.2)` 三种情况 × 两组彩色信号,Y、Cb、Cr 方差与 Cb–Cr 互协方差最大偏差 2.17%(第 4 层,抽样误差)。实测脚本 `noise_estimator.py`、`validate_estimator.py` 已删除。
2. **已施加 LSC 增益图**的传递与持久化(§3.2),**调试导出**(§12.4)→ 门禁:重新打开持久化 DNG 得到的增益图与写出前一致;导出数据可在 numpy 中正确读取。(“numpy 复现的金字塔与设备端一致”移到第 3 步:设备端金字塔在第 3 步才实现。)
**代码已完成(2026-10-28)**:`raw/RawAppliedLensShading.kt`、`RawMetadata.appliedLensShading`、渲染入口参数、`raw/denoise/PhotonDenoiseDump.kt`(属性 `debug.photon.denoise.dump`,钩在合成默认降噪与用户调整降噪的回读回调中,写 `.rgba16f` + `.json` 到 `Android/data/<包名>/files/photon_denoise_dump/`)、`tools/photon_denoise/load_dump.py`。往返校验:保存时日志 `Applied LSC persisted WxH hash=…`,重新渲染时日志 `Applied LSC restored WxH hash=…`,两者一致即通过。
**设备端门禁通过(2026-10-28,PMA110)**:Sabre 8 帧、ISO 100 合成照片,`Applied LSC persisted 17x13 hash=296727762` 与 `Applied LSC restored 17x13 hash=296727762` 一致;`SABRE_DEFAULT` 导出 2728×2048,`load_dump.py` 读取正常(R/G/B 均值 0.104 / 0.253 / 0.153,全部有限),重采样的合成增益 R 1.026–2.608、G 1.008–2.473、B 1.001–2.461。用户调整降噪入口的导出尚未在设备上触发。
3. **着色器与编排**(亮度、色度)→ 门禁:与 numpy 参考逐 pass 比对,最大误差在 fp16 量化界内。
**代码已完成(2026-10-28),设备比对待运行**:
- numpy 参考 `tools/photon_denoise/photon_denoise.py`:Analyze(↓2)、Band(`L`、`base`、§2.1 协方差、截断置零)、Pilot(结构张量、各向异性 5×5 窗、Huber、ŝ₁)、Final(第二阶段 Wiener、颗粒保留、色度门控、粗层联合双边、第 0 层输出乘回增益)。上采样按“粗层镜像”的直接定义实现,奇数尺寸向上取整。存储按格式取整(RGBA16F → float16,噪声 RGBA32F)。
- GLES:`raw/denoise/PhotonDenoiseShaders.kt`(ANALYZE / BAND / PILOT / FINAL)、`PhotonMultiScaleDenoiser.kt`(编排)、`PhotonNoiseModel.kt`(§2 参数、κ⁰、色度层数)、`PhotonDenoiseTuning.kt`(调参前默认值)。LSC 增益在着色器中由增益图手动双线性采样(不用硬件过滤,保证与参考一致),不再单独生成 1/4 分辨率增益纹理。
- 比对:`debug.photon.denoise.dump=true` 时,在导出降噪输入后用同一纹理运行本降噪器,逐 pass 回读到 `<stem>.<pass>.f16|f32` 与 `<stem>.photon.json`(参数与 pass 清单);`tools/photon_denoise/compare_passes.py` 以 GPU 的输入逐 pass 重算并按 fp16 ulp 比较(2 ulp + 通道最大值 × 2⁻¹⁴),`--self-test` 已通过。
- 设备比对第一轮(2026-10-28,PMA110,Sabre 8 帧 2728×2048,7 层):40 个 pass 中 37 个在容差内,全部 `denoised` 与 `output` 一致;`pilot0/1/2` 共 272 个像素超差,全部位于各向异性恰为 0(结构张量全零)的像素的方向分量 cos/sin 上——GLSL 的 `atan(0, 0)` 未定义,numpy 返回 0;各向异性为 0 时窗口为圆形,方向不影响下游。已在着色器与参考中把退化张量的方向统一定义为 θ = π/2。
- **设备比对通过(2026-10-28 复测,PMA110,Sabre 8 帧 2728×2048,7 层)**:40 个 pass 全部在容差内,最差 0.485 倍容差;`max_ulp` 偏大的项(G1 568、band0 3072、pilot0 106)均为接近 0 的值上的抵消误差,按容差计算在 0.49 倍以内。
- **融合(2026-10-28)**:各层的 Band、Pilot、Final 合并为一个 dispatch(`PhotonDenoiseShaders.synthesize`)。工作组处理 8×8 输出块,在共享内存中计算块加 4 像素边框(16×16)的 band、base、noise 与块加 2 像素边框(12×12)的 pilot,共约 14.6KB(按 16 字节对齐估算),在 GLES 3.1 保证的 16KB 内。共享内存按图像坐标寻址、所有邻域先 `mirror2`,与参考的边界语义一致;写入共享内存时 band、base、pilot 按 float16 取整,与原先写纹理一致。调试变体(`synthesize(true)`)改为写出 band、base、noise、pilot 四张图(GLES 3.1 最低的 4 个 image 单元),比对工具不变;正式变体只写结果。三个着色器已用 NDK `glslc --target-env=opengl` 离线编译通过。
- 融合后第一次设备比对(2026-10-28):band、base、noise 全部一致,pilot 大面积不一致(规范化方向符号后,第 0 层仍有约 60% 像素的各向异性超差),`denoised` 与 `output` 略超容差。原因:共享内存原以 float 数组保存经 `unpackHalf2x16(packHalf2x16(x))` 取整的值,编译器可合法地把这一往返折叠为 `x`,共享内存因而保留未取整的 float32;调试输出写纹理时才取整,参考用取整值计算结构张量。base 平滑、相邻差值小,梯度对 1 ulp 敏感,各向异性随之偏离。改为以 `uvec3`(L 与 base 的 6 个 half)和 `uvec2`(pilot 的 4 个 half)保存打包位,取整不可再被省略;共享内存降为约 9.3KB。
- **融合后设备比对通过(2026-10-28 复测,PMA110,Sabre 8 帧 2728×2048,7 层)**:40 个 pass 全部在容差内,最差 0.765 倍容差(band0,接近 0 的抵消误差),`output` 最多 1 ulp。
- 显存:中间纹理全部消除,只保留高斯层 `G_1..G_N`(约 1/3 张全分辨率)与相邻两层降噪结果(至多约 1/4 + 1/16),合计约 0.65 张全分辨率 `RGBA16F`(2728×2048 约 29MB,原先约 270MB),另加输出纹理,满足 §10.2。代价是 band 在 4 倍、pilot 在 2.25 倍的像素上重复计算。用户调整入口的合成方差比与残余比在第 6 步接入前固定为 1。
- **性能(2026-11-03,Adreno 840,4080×3064,7 层)**:调试属性 `debug.photon.denoise.timing`(`true` 逐 pass 计时,`ablation` 另把每层合成拆成 band / 亮度 / 色度门控 / 双边,各跑 3 次取最快)。串行合计约 957ms,合成占 89%(L0 655ms、L1 147ms),金字塔 54ms,强度估计 52ms;L0 消融:仅 band 302ms、亮度 +218ms、色度门控约 0。以下改动在干净基线上逐项实测后均不采用:
- 合成 tile 16×16、64 invocation(每个 invocation 写 4 行):整体多约 100ms。128 invocation 的 16×16 / 16×8 更慢(16×8@128 亮度段寄存器溢出,L0 全开约 1.9s)。
- 亮度窗口空间权重按整数偏移分解为 `ex^(dx²) · ey^(dy²) · e^(dx·dy)`(每窗口 3 次 `exp` 代替 25 次,数学等价):无可测差别,亮度段不受 `exp` 吞吐限制。
- `mirrorIndex` 先判区间内与单次反射再取模(返回值逐位相同):整体多约 500ms。
- **采用:预镜像共享内存**。band 与 pilot 写入共享内存时按 `mirror2(c)` 计算、存在原坐标 `c`,邻域读取改为纯偏移,去掉内层循环中每输出像素约 500 次整数取模(结构张量的 9 个采样点仍先镜像,否则边界梯度符号会翻转)。读到的源像素与原实现逐一相同(模拟 259 万次读取一致),结果逐位不变。L0:全开 655 → 349ms,Δ亮度 +218 → +57ms,仅 band 302 → 290ms。
- **采用:coarse tile 缓存**。每个工作组先把 band 区域上采样所需的 `G_{l+1}`、`G̃_{l+1}` 各 12×12 个 texel(镜像坐标的值)读进共享内存,上采样按原顺序从共享内存累加;原先每个 band 像素各取约 12 个 texel、再乘 4 倍冗余。L0 的 `lscGain` 在输入与截断判断间复用一次。共享内存约 13.9KB,仍在 16KB 基线内;结果逐位不变(模拟 9 万次抽头均落在缓存内)。L0:全开 349 → 297ms,仅 band 290 → 206ms;整条流程 610 → 555ms(原始 957ms)。
- 盲改写法(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。
- §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。
- 融合实现、`dispatchBands` 与对应调试属性已删除。parity 导出时条带高度取整层高度,每层一个条带,逐 pass 从条带纹理按边框偏移回读 band、base、noise、pilot,比对的就是正式路径。条带化后的 parity 比对与 Adreno 计时待运行。
4. **模型误差测量**(§12.1):VGN、Quad Bayer、Sabre、Spatial,结果写入 §13。
**工具已完成(2026-10-28)**:`tools/photon_denoise/model_error.py`(自测通过,见 §12.1),导出增加 `<stem>.params.json`,逐 pass 导出改由 `debug.photon.denoise.parity` 单独开启。按 §13 的规程拍摄后填表;尚未拍摄。
5. **离线调参**(§12.2)得到各管线调参表。
**工具已完成(2026-10-28),尚未拍摄**:
- `image_metrics.py`:固定参考渲染(未白平衡相机 RGB × 固定白平衡 × 固定曝光 → sRGB 曲线,单位色彩矩阵,无局部影调;曝光取干净图白平衡后亮度第 99 百分位映射到 0.9);sRGB PSNR、BT.601 亮度(与 `preprocessNative` 相同)上的 PSNR 与 SSIM(高斯 11×11、σ 1.5)、CIEDE2000(Sharma 2005);DnCNN 推理按应用的方式量化到 8 bit,256 分块、重叠 32、取中心拼接。
- `tune.py`:输入 `cases.json`(`[{"clean": "<干净图导出 stem>", "noisy": ["<带噪导出 stem>", ...]}]`,均为降噪入口的调试导出,带 `<stem>.params.json`)。干净图做 2×2 binning;带噪图经参考实现降噪后同样 binning,按通道最小二乘对齐曝光,在每张图上取 4 个 384×384 网格裁块(裁块时平移 LSC 增益图原点,噪声模型与整图一致)。一个带噪导出即一个调参节点,节点坐标为 §5 的 `n = √(m·v_Y(0.18))/0.18`。目标为节点内全部裁块的平均 sRGB PSNR;以 `PhotonDenoiseTuning` 默认值为起点做坐标下降(2 轮):各层 `α_l`、`t_l`、`d_l`,色度门限缩放(亮度与色度门同乘),联合双边的层数与两个系数。输出 `photon_denoise_tuning.json`:按管线列出各节点的调参值、`n`,以及带噪 / 默认 / 调参后的 sRGB PSNR、亮度 PSNR / SSIM、CIEDE2000、线性 PSNR 与 DnCNN 亮度 PSNR。
- 自测(`tune.py --self-test`,合成平滑彩色场景 + 按档案生成、经 `√(8/3)` 相关化的噪声):sRGB PSNR 带噪 32.08 → 默认 38.94 → 调参后 42.18 dB;亮度 PSNR 43.75 dB(DnCNN 35.87 dB);SSIM 0.9724;CIEDE2000 6.180 → 1.212。通过。自测只检验工具链路(导入、裁块、对齐、搜索、输出)正确,数值不代表实拍画质。
- 同时修正:σ = 0 时 Huber 权重为 0/0。着色器与参考都改为 `|ΔL| ≤ d·σ` 时权重 1,否则 `d·σ/|ΔL|`;σ > 0 时输出不变。`compare_passes.py --self-test` 与 `glslc` 离线编译已通过,设备逐 pass 比对需在下次以 `debug.photon.denoise.parity` 导出时复测。
6. **接入全部路径**(§10.3),残余比的写入与读取(§2.4),Bitmap 路径(§9)。
**代码已完成(2026-10-28),设备验证待运行**:
- 合成方差比:`PhotonMergeNoise` 在 Spatial(4 处帧接纳点,与强度图采集同一位置,与其是否开启无关)与 Sabre(参考帧 + 每个后续帧)累加,经 `RawStackResult.denoiseHistory` → 合成输出元数据 → 默认降噪;`GalleryManager` 的默认降噪可用性判断改为检查该记录,不再依赖 MGC 合成噪声模型。
- 默认降噪:`processMgcSpatialGpuLinearRgb` 用 `PhotonMultiScaleDenoiser` 直接处理 `workingFloatTexture`,输出 RGBA16UI;PBO 回读 / 上传与 `MgcFullResolutionDenoise` 调用移除;`MgcSpatialGpuDenoiseResult.denoiseHistory` 带出本次的残余比(§2.4)。
- 持久化:`GalleryManager` 合成保存时与已施加 LSC 一起写入 `RawDenoiseHistoryMetadata`(日志 `Denoise history persisted …`),单帧保存时清除;全部渲染入口(`PhotoProcessor` 2 处、`GalleryManager` 5 处)读取后经 `RawDemosaicProcessor` 的 `denoiseHistory` 参数写入 `RawMetadata.denoiseHistory`(日志 `Denoise history restored …`)。
- 用户调整:整图与分块两处改为 `renderPhotonUserAdjustmentDenoise`,读取 `denoiseHistory`(无记录按单帧 `VGN` / `QUAD`),NLM 与色度的回退删除;`DemosaicNoisePropagationCalibrator` 的用户调整预标定随之删除。
- 残余比改为逐层(`PhotonDenoiseParams.residual[l]`,着色器 `uResidual` 每层上传一次),numpy 参考与工具同步,`compare_passes.py --self-test`(含色度残余比 0 的层)、`model_error.py --self-test`、`tune.py --self-test` 均通过。
- 调参表按管线组织(§5),Bitmap 路径(§9)接入;调试导出改为由导出模块自行回读输入纹理,文件名为 `<时间>_<管线>_<DEFAULT|USER>_<原点>`,`pipeline` 字段为 §5 的管线名。
- 已无调用者而删除:`DemosaicNoisePropagationCalibrator.kt`、`DemosaicNoiseAtlasGenerator.kt`、`DenoiseProfileAlgorithm.kt`、`DenoiseProfileNlmConfig.kt`、`DenoiseProfileStripePlanner.kt`、`lut/ChromaDenoiseAlgorithm.kt`。MGC 降噪 capsule、强度图与 `MgcSabreMergedNoiseModel` 仍供 Spatial 去马赛克的噪声档案(`spatialOutputNoiseMetadata`)使用,留到第 7 步。
- 设备验证项:合成照片保存与重开时 `Denoise history persisted/restored` 一致;默认降噪与用户调整的输出正常;Bitmap 编辑与相册 AI 前置色度正常。
7. Halide 运行时拆分、`RunYuvToRgb` 白盒化(与 AOT 逐位比对),随后移除旧实现(§15)。
**已完成(2026-10-28)**,内容见 §15。验证:Kotlin 编译通过;`buildCMakeDebug[arm64-v8a]` 编译链接通过,`libmy-native-lib.so` 无未解析的 `photon_mgc_*` 符号;`RunYuvToRgb` 白盒实现与 AOT 逐位一致(主机端模拟执行)。设备端尚未运行:需确认 RAWmax(Sabre / Spatial)拍摄、引导上采样与锐化输出正常。单元测试编译受已有的 `BokehShadersTest`(`LAYER_MEDIAN_COMPUTE_SHADER` 不存在)阻塞,与本步无关。
8. 性能与显存在目标设备上测量,记录到本文档。
9. **逐像素合成方差比**(§2.2):合成方差图的 GPU 累加(Spatial、Sabre)、降噪器采样、相册元数据持久化;numpy 参考、`compare_passes.py` 与导出格式同步。→ 门禁:逐 pass 比对通过;合成数据上(numpy,已知逐帧接受度)方差图与解析值一致;实拍运动场景中剔除区与静止区降噪后残余噪声水平相近。
**代码已完成(2026-10-29),设备验证待运行**:
- Kotlin:`PhotonMergeNoise` 改为 GPU 累加(`ACCUMULATE`)与归约(`REDUCE`),`RawMergeVarianceMap` 与其持久化,`PhotonDenoiseParams.mergeMap`,着色器 `mergeRatio()` 取代 `uMergeRead/uMergeShot`。Kotlin 编译通过;5 个改动的计算着色器经 `glslc --target-env=opengl` 离线编译通过。
- numpy:`photon_denoise.MergeMap` / `merge_ratio()`,`point_covariance` 逐像素;`compare_passes.py` 读取导出中的 `mergeMap`,`--self-test` 用非均匀 3×4 图通过;`tune.py` 裁块时平移方差图原点;`model_error.py --self-test` 通过。
- 门禁 `validate_merge_map.py`(numpy 镜像两个着色器):512×384、6 帧(曝光比 0.8–1.25、全局权重 0.6–1.0、输出曝光 0.8),各帧沿运动路径剔除,另有一块所有非参考帧都剔除的区域;160 次实现的合并像素方差按 RAW/32 格与方差图预测相比,m_r 覆盖名义 0.118 到单帧 0.640,最大偏差 2.21%(容差 3%),通过。
- 设备验证项:逐 pass 比对(`debug.photon.denoise.parity`);运动场景中剔除区与静止区降噪后的残余噪声;合成保存 / 重开时方差图一致。
10. **逐图噪声强度**(§5.1,阶段 A):GPU 估计(`ESTIMATE` / `RESOLVE`)、Band 按亮度档查强度表、默认降噪把所用强度表写入 `RawDenoiseHistory`(契约 v4);numpy `estimate_strength` / `strength_at`,`compare_passes.py` 比对 `strength`(相对容差 2%,GPU 表随后作为 Band 的输入)。按管线的实测强度图删除,`BITMAP` 保留固定强度。
**代码已完成(2026-10-29),设备验证待运行**:编译通过,`--self-test` 25 项一致,五个着色器 `glslc` 通过。设备验证项:逐 pass 比对;3x 镜头与原镜头单帧暗部残余;ISO 100 纹理场景;估计耗时。
11. **半合成差分**(§5.1 阶段 B):先测 Sabre / Spatial 第二次解析的耗时,再决定实施方式。
## 17. 已核实事项
| 事项 | 结论 |
|---|---|
| 降噪输入是否已含 LSC | 是。单帧在去马赛克前逐 CFA 位点施加;合成默认降噪按 `outputIncludesLensShading` 保留增益图。持久化 DNG 会移除增益图,§3.2 补上 |
| 合成路径 | 生产环境 `MgcRawMaxMode.outputMode` 恒为 `RGB`(`MultiFrameStacker.kt:48`),默认 Sabre(GPU);Spatial RGB 由 CPU AOT `MgcSpatialRgbMerger` 合成 |
| 单帧去马赛克 | 标准 Bayer 为 VGN,Quad Bayer 为独立路径;VGN 内含噪声自适应的坏点修复、方向阈值与色彩噪声重建 |
| 锐化 / 上采样依赖 | 引导上采样依赖完整分辨率降噪 capsule 中的 `photon_mgc_yuv_to_rgb_s16`;所有 capsule 共用 `mgc_denoise_static.cpp` 中的 Halide 运行时;capsule 生成脚本已缺失 |
| DnCNN | 单通道亮度、256×256、盲去噪、残差学习;有效范围约 σ ≤ 25–30(8-bit);训练噪声类型无法从文件确定 |
## 附录 A:已放弃的噪声传播方案
最初的设计把噪声表示为“源通道系数 × 去马赛克传递矩阵 `T_c` × 可分离空间谱 × LSC / 合成噪声场”,沿管线精确传播到每个金字塔层。
- 传播计算本身在合成数据上成立:8 次 2048² 实现、5 层 × 4 相位,最大偏差 1.02%。这部分作为 `κ⁰` 的计算保留(§2.3)。
- 去马赛克标定在设备上未通过(2026-10-28,PMA110 / Adreno 840):
| 路径 | 加和性误差 | 电平依赖 | 第 0 层点方差 | 金字塔各层 |
|---|---|---|---|---|
| VGN | 0.62 | 0.25 | Y +146%,Cb +26% | Y +92%…+213%;C −46%…+47% |
| Quad Bayer | 0.046 | 0.036 | 全部在 ±3.5% 内 | Y 第 1 层按相位 ±16%;C 第 2–4 层 +55%…+95% |
- VGN:只给单个通道加噪时输出方差被大幅压低(`T_R` 的 RR 项 0.054),三通道同时加噪的输出方差是单通道之和的约 2.5 倍。VGN 的坏点修复、方向阈值与色彩噪声重建都依赖噪声,线性传递矩阵不成立。
- Quad Bayer:点模型成立,但 2×2 同色块使噪声以 4 像素为周期循环平稳,块状插值产生的低频色度噪声也不可分离。
该方案的去马赛克标定器、合成噪声 atlas、门禁与调试触发代码已删除。
## 附录 B:已放弃的离线标定方案
曾设计按管线、噪声水平、合成帧数,用同场景成对拍摄的差分离线标定每层系数 κ,运行时用档案乘 κ。因标定工作量与设备依赖,未实施。差分测量本身保留为 §12.1 的模型误差测量工具。
## 附录 C:已放弃的单图实测方案
在降噪入口从图像本身测量各层噪声,先后三轮,均在离线门禁(2048²,5 层,平坦 / 局部纹理 / 纹理铺满 × 线性相关 / 色度中值 / 亮度软阈值)上未通过(2026-10-28):
1. **参考尺度来自数据**(相对选块 + 共享噪声曲线拟合):平坦场景选块后实测/真值 0.94–1.05,拟合后最差 −13%(亮端深层斜坡曲率)与 −37%(亮度软阈值使噪声曲线偏离二次多项式);纹理铺满时第 0 层信号能量即为噪声的 27 倍,估计偏高数百倍。
2. **参考尺度来自档案 × 白噪声理论值**,逐箱 Gamma 截断估计 + 分布一致性检验:档案 ×0.5、×2 的结果与 ×1 相同;但整箱都是纹理或平滑信号时箱内尺度随数据放大(深层达真值 4000 倍以上),一致性检验无法识别;跨层趋势外推依据被污染的深层,第 0 层被外推为真值的 0.001 倍。Gamma 形状须由低分位比反解:用块内协方差会被剔除阈值截断,用相关系数会忽略相位间方差不等,两者都使一致性比值稳定偏大约 1.35。
3. **增加尺度物理上限 2、以最暗 3 个已测箱为基准的跨箱锚定(1.5 倍)、外推改为沿用最近已测层**:平坦场景最差 1.24–1.34 倍(色度第 4 层亮端的平滑色相变化);纹理铺满场景已测部分 2.1–4.0 倍、深层 8–16 倍;局部纹理场景亮度全部退回理论值(第 0 层偏 40 倍);上限以档案为参考,档案 ×2 时最差 6.7 倍。
结论:纹理能量与噪声相当的区域,仅凭箱内能量分布的形状无法可靠区分信号与噪声;每增加一条判别规则只修正一类失败并引入新的失败,三轮没有收敛。另,“在 `G0` 上测噪声自相关”在单幅图像上不可行:去除信号必须高通,而高通同时去掉了噪声的低频部分。
+234
View File
@@ -0,0 +1,234 @@
"""Pass-by-pass parity between the GLES Photon denoiser and photon_denoise.py (implementation step 3).
Each pass is recomputed from the GPU's own dumped inputs, so arithmetic differences do not
accumulate across passes. Tolerance per element: 2 float16 ulps of the value plus 2^-14 of the
channel's largest magnitude (cancellation floor). A pass passes when no element exceeds it.
Usage:
uv run --with numpy python -I tools/photon_denoise/compare_passes.py <dump stem or .json>
uv run --with numpy python -I tools/photon_denoise/compare_passes.py --self-test
"""
from __future__ import annotations
import json
from dataclasses import replace
import sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import noise_model # noqa: E402
import photon_denoise as pd # noqa: E402
F32 = np.float32
STRENGTH_TOLERANCE = 0.02
PREFILTER_FLIPS = 1e-4
def params_from_json(p: dict) -> pd.Params:
lsc = None
if "lensShading" in p:
l = p["lensShading"]
lsc = pd.LensShading(
np.asarray(l["gains"], dtype=F32).reshape(l["height"], l["width"], 4),
np.asarray(l["dngGrid"], dtype=F32) if "dngGrid" in l else None,
(p["originX"], p["originY"]),
(p["fullWidth"], p["fullHeight"]),
)
return pd.Params(
scale=p["scale"],
white_balance=np.asarray(p["whiteBalance"], dtype=F32),
read=np.asarray(p["read"], dtype=F32),
shot=np.asarray(p["shot"], dtype=F32),
merge_read=p["mergeRead"],
merge_shot=p["mergeShot"],
residual=np.asarray(p["residual"], dtype=F32),
kappa_luma=np.asarray(p["kappaLuma"], dtype=F32),
kappa_chroma=np.asarray(p["kappaChroma"], dtype=F32),
levels=p["levels"],
luma_levels=p["lumaLevels"],
alpha=np.asarray(p["alpha"], dtype=F32),
grain=np.asarray(p["grain"], dtype=F32),
outlier=np.asarray(p["outlier"], dtype=F32),
gate_luma=tuple(p["gateLuma"]),
gate_chroma=tuple(p["gateChroma"]),
bilateral_levels=p["bilateralLevels"],
bilateral_luma=p["bilateralLuma"],
bilateral_chroma=p["bilateralChroma"],
luma_strength=p["lumaStrength"],
chroma_strength=p["chromaStrength"],
lsc=lsc,
strength_table=np.asarray(p["strengthTable"], dtype=F32).reshape(p["levels"], pd.STRENGTH_BINS, 3)
if "strengthTable" in p else None,
gamma=np.asarray(p["gamma"], dtype=F32) if "gamma" in p else None,
strength_cap_luma=np.asarray(p["strengthCapLuma"], dtype=F32) if "strengthCapLuma" in p else None,
strength_cap_chroma=np.asarray(p["strengthCapChroma"], dtype=F32) if "strengthCapChroma" in p else None,
merge_map=pd.MergeMap(
np.asarray(p["mergeMap"]["values"], dtype=F32).reshape(p["mergeMap"]["height"], p["mergeMap"]["width"], 2),
(p["originX"], p["originY"]),
(p["fullWidth"], p["fullHeight"]),
) if "mergeMap" in p else None,
)
def load_texture(path: Path, width: int, height: int, fmt: str) -> np.ndarray:
dtype = "<f2" if fmt == "f16" else "<f4"
data = np.fromfile(path, dtype=dtype).reshape(height, width, 4).astype(F32)
return np.moveaxis(data, -1, 0)
def tolerance_excess(gpu: np.ndarray, ref: np.ndarray) -> tuple[float, int, float]:
"""(worst |diff| / tolerance, count over tolerance, worst diff in ulps)."""
magnitude = np.maximum(np.abs(gpu), np.abs(ref))
ulp = np.spacing(magnitude.astype(np.float16)).astype(F32)
floor = np.max(np.abs(ref), axis=(1, 2), keepdims=True) * F32(2.0 ** -14)
tolerance = 2 * ulp + floor
ratio = np.abs(gpu - ref) / np.maximum(tolerance, F32(1e-30))
return float(ratio.max()), int((ratio > 1).sum()), float((np.abs(gpu - ref) / np.maximum(ulp, 1e-30)).max())
def compare(input_rgb: np.ndarray, params: pd.Params, textures: dict[str, np.ndarray]) -> bool:
sizes = pd.level_sizes(input_rgb.shape[1], input_rgb.shape[2], params.levels)
results = []
def check(name: str, ref: np.ndarray, channels: int):
if name not in textures:
results.append((name, None))
return
gpu = textures[name][:channels]
results.append((name, tolerance_excess(gpu, ref[:channels])))
g0 = pd.analyze0(input_rgb, params)
gaussians = {0: g0}
for level in range(params.levels):
fine = g0 if level == 0 else textures[f"G{level}"][:3]
check(f"G{level + 1}", pd.f16(pd.down(fine, sizes[level + 1])), 3)
gaussians[level + 1] = textures[f"G{level + 1}"][:3]
# Section 5.1: estimated from the GPU's own Gaussians when the params carry no table. Bucket
# boundaries may flip with last-ulp log2 differences, so the table is compared relatively.
if params.strength_table is None:
ref_table = pd.estimate_strength(g0, [gaussians[l + 1] for l in range(params.levels)], params)
gpu_table = textures.get("strength")
if gpu_table is None:
results.append(("strength", None))
else:
rel = np.abs(gpu_table - ref_table) / np.maximum(np.abs(ref_table), F32(1e-3))
results.append(("strength", (float(rel.max() / STRENGTH_TOLERANCE),
int((rel > STRENGTH_TOLERANCE).sum()), 0.0)))
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:
ref = pd.prefilter(g0, gaussians[1], params)
gpu = textures.get("prefilter0")
if gpu is None:
results.append(("prefilter0", None))
else:
gpu = gpu[0]
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
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 \
else textures[f"denoised{level + 1}"][:3]
lap, base, noise = pd.band(fine, gaussians[level + 1], denoised_coarse, level, params)
check(f"band{level}", lap, 3)
check(f"base{level}", base, 3)
check(f"noise{level}", noise, 4)
gpu_lap = textures[f"band{level}"][:3]
gpu_base = textures[f"base{level}"][:3]
gpu_noise = textures[f"noise{level}"][:4]
gpu_pilot = None
if level < params.luma_levels and params.luma_strength > 0:
check(f"pilot{level}", pd.pilot(gpu_lap, gpu_base, gpu_noise, level, params), 4)
gpu_pilot = textures[f"pilot{level}"][:4]
result = pd.final(gpu_lap, gpu_base, gpu_noise, gpu_pilot, level, params)
if level > 0:
check(f"denoised{level}", pd.f16(result), 3)
else:
check("output", pd.output(result, params), 3)
ok = True
for name, stats in results:
if stats is None:
print(f" {name:<11} missing")
ok = False
continue
worst, count, ulps = stats
status = "ok" if count == 0 else "FAIL"
ok &= count == 0
print(f" {name:<11} worst={worst:8.3f}x tol over={count:<8} max_ulp={ulps:10.1f} {status}")
return ok
def load_dump(path: str) -> tuple[np.ndarray, pd.Params, dict[str, np.ndarray]]:
stem = Path(path)
if stem.suffix == ".json":
stem = stem.with_suffix("")
meta = json.loads(stem.with_suffix(".json").read_text())
raw = np.fromfile(stem.with_suffix(".rgba16f"), dtype="<f2").reshape(meta["height"], meta["width"], 4)
rgb = np.moveaxis(raw[..., :3].astype(F32), -1, 0)
photon = json.loads(Path(f"{stem}.photon.json").read_text())
textures = {
entry["name"]: load_texture(Path(f"{stem}.{entry['name']}.{entry['format']}"),
entry["width"], entry["height"], entry["format"])
for entry in photon["passes"]
}
params = params_from_json(photon["params"])
if "strength" in photon:
textures["strength"] = np.asarray(photon["strength"], dtype=F32).reshape(params.levels, pd.STRENGTH_BINS, 3)
return rgb, params, textures
def self_test() -> bool:
"""Feeds the reference's own trace back as 'GPU' textures: every pass must match exactly."""
rng = np.random.default_rng(3)
h, w = 75, 101 # odd sizes exercise the mirror and ceil paths
mu = np.array([0.08, 0.2, 0.11], dtype=F32)
read = np.full(3, 2e-5, dtype=F32)
shot = np.full(3, 3e-4, dtype=F32)
yy, xx = np.mgrid[0:h, 0:w]
clean = (mu[:, None, None] * (1 + 0.3 * np.sin(xx / 7.0) * np.cos(yy / 5.0))[None]).astype(F32)
rgb = pd.f16(clean + np.sqrt(read + shot * mu)[:, None, None] * rng.standard_normal((3, h, w)).astype(F32))
kappa = noise_model.Kappa0.build(4, 4)
lsc = pd.LensShading(rng.uniform(1.0, 2.0, (5, 7, 4)).astype(F32), None, (0, 0), (w, h))
residual = np.array([[0.09, 0.0, 0.0], [0.04, 0.0, 0.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]], dtype=F32)
params = pd.Params(4096.0, np.array([2.0, 1.0, 1.6], dtype=F32), read, shot, 0.5, 0.5, residual,
kappa.luma.astype(F32), kappa.chroma.astype(F32), 4, 4, np.ones(4, dtype=F32),
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),
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)
textures = {f"G{i + 1}": g for i, g in enumerate(trace.gaussians)}
for level, (lap, base, noise) in trace.bands.items():
textures[f"band{level}"], textures[f"base{level}"], textures[f"noise{level}"] = lap, base, noise
textures.update({f"pilot{level}": p for level, p in trace.pilots.items()})
textures.update({f"denoised{level}": d for level, d in trace.denoised.items() if level > 0})
textures["output"] = trace.output
textures["strength"] = trace.strength
if trace.prefilter is not None:
textures["prefilter0"] = trace.prefilter[None]
return compare(rgb, params, textures)
def main() -> int:
if sys.argv[1:] == ["--self-test"]:
print("self-test")
return 0 if self_test() else 1
ok = True
for path in sys.argv[1:]:
print(path)
rgb, params, textures = load_dump(path)
ok &= compare(rgb, params, textures)
print("PASS" if ok else "FAIL")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())
+142
View File
@@ -0,0 +1,142 @@
"""Reference render and image metrics of docs/photon-multiscale-denoise.md section 12.2.
The fixed reference render maps un-white-balanced camera RGB to display sRGB with a fixed white
balance, an identity colour matrix (camera RGB treated as linear sRGB primaries), a fixed
exposure and the sRGB transfer curve, with no local tone mapping. Every compared image goes
through the same render, so the render cancels out of the comparison.
"""
from __future__ import annotations
import numpy as np
F32 = np.float32
def srgb_encode(linear: np.ndarray) -> np.ndarray:
x = np.clip(linear, 0.0, 1.0)
return np.where(x <= 0.0031308, 12.92 * x, 1.055 * np.power(x, 1 / 2.4) - 0.055).astype(F32)
def render(camera_rgb: np.ndarray, white_balance: np.ndarray, exposure: float) -> np.ndarray:
"""[3, H, W] un-white-balanced camera RGB -> display sRGB in [0, 1]."""
return srgb_encode(camera_rgb * (np.asarray(white_balance, dtype=F32) * F32(exposure))[:, None, None])
def exposure_for(camera_rgb: np.ndarray, white_balance: np.ndarray, percentile: float = 99.0) -> float:
"""Exposure placing the given percentile of the white-balanced luma at 0.9."""
luma = np.tensordot(np.array([0.25, 0.5, 0.25], dtype=F32),
camera_rgb * np.asarray(white_balance, dtype=F32)[:, None, None], axes=1)
return float(0.9 / max(np.percentile(luma, percentile), 1e-6))
def psnr(a: np.ndarray, b: np.ndarray) -> float:
mse = float(np.mean((a.astype(np.float64) - b.astype(np.float64)) ** 2))
return float("inf") if mse == 0 else 10 * np.log10(1.0 / mse)
def dncnn_luma(srgb: np.ndarray) -> np.ndarray:
"""Luma with the coefficients of native-lib.cpp preprocessNative (BT.601)."""
return (0.299 * srgb[0] + 0.587 * srgb[1] + 0.114 * srgb[2]).astype(F32)
def _gaussian_filter(image: np.ndarray, sigma: float = 1.5, radius: int = 5) -> np.ndarray:
x = np.arange(-radius, radius + 1)
kernel = np.exp(-0.5 * (x / sigma) ** 2)
kernel /= kernel.sum()
padded = np.pad(image, radius, mode="reflect")
rows = sum(k * padded[:, i:i + image.shape[1]] for i, k in enumerate(kernel))
return sum(k * rows[i:i + image.shape[0], :] for i, k in enumerate(kernel))
def ssim(a: np.ndarray, b: np.ndarray) -> float:
"""Single-scale SSIM (Gaussian 11x11, sigma 1.5) of two [H, W] images in [0, 1]."""
a = a.astype(np.float64)
b = b.astype(np.float64)
c1, c2 = 0.01 ** 2, 0.03 ** 2
mu_a, mu_b = _gaussian_filter(a), _gaussian_filter(b)
var_a = _gaussian_filter(a * a) - mu_a ** 2
var_b = _gaussian_filter(b * b) - mu_b ** 2
cov = _gaussian_filter(a * b) - mu_a * mu_b
value = ((2 * mu_a * mu_b + c1) * (2 * cov + c2)) / ((mu_a ** 2 + mu_b ** 2 + c1) * (var_a + var_b + c2))
return float(value.mean())
def _srgb_to_lab(srgb: np.ndarray) -> np.ndarray:
x = srgb.astype(np.float64)
linear = np.where(x <= 0.04045, x / 12.92, ((x + 0.055) / 1.055) ** 2.4)
m = np.array([[0.4124564, 0.3575761, 0.1804375],
[0.2126729, 0.7151522, 0.0721750],
[0.0193339, 0.1191920, 0.9503041]])
xyz = np.tensordot(m, linear, axes=1) / np.array([0.95047, 1.0, 1.08883])[:, None, None]
f = np.where(xyz > (6 / 29) ** 3, np.cbrt(xyz), xyz / (3 * (6 / 29) ** 2) + 4 / 29)
return np.stack([116 * f[1] - 16, 500 * (f[0] - f[1]), 200 * (f[1] - f[2])])
def ciede2000(srgb_a: np.ndarray, srgb_b: np.ndarray) -> float:
"""Mean CIEDE2000 (Sharma, Wu, Dalal 2005) between two sRGB images."""
l1, a1, b1 = _srgb_to_lab(srgb_a)
l2, a2, b2 = _srgb_to_lab(srgb_b)
c1 = np.hypot(a1, b1)
c2 = np.hypot(a2, b2)
c_mean = 0.5 * (c1 + c2)
g = 0.5 * (1 - np.sqrt(c_mean ** 7 / (c_mean ** 7 + 25.0 ** 7)))
a1p, a2p = (1 + g) * a1, (1 + g) * a2
c1p, c2p = np.hypot(a1p, b1), np.hypot(a2p, b2)
h1p = np.degrees(np.arctan2(b1, a1p)) % 360
h2p = np.degrees(np.arctan2(b2, a2p)) % 360
dlp = l2 - l1
dcp = c2p - c1p
dh = h2p - h1p
dh = np.where(c1p * c2p == 0, 0, np.where(dh > 180, dh - 360, np.where(dh < -180, dh + 360, dh)))
dhp = 2 * np.sqrt(c1p * c2p) * np.sin(np.radians(dh / 2))
lp_mean = 0.5 * (l1 + l2)
cp_mean = 0.5 * (c1p + c2p)
hsum = h1p + h2p
hp_mean = np.where(c1p * c2p == 0, hsum,
np.where(np.abs(h1p - h2p) <= 180, hsum / 2,
np.where(hsum < 360, (hsum + 360) / 2, (hsum - 360) / 2)))
t = (1 - 0.17 * np.cos(np.radians(hp_mean - 30)) + 0.24 * np.cos(np.radians(2 * hp_mean))
+ 0.32 * np.cos(np.radians(3 * hp_mean + 6)) - 0.20 * np.cos(np.radians(4 * hp_mean - 63)))
d_theta = 30 * np.exp(-(((hp_mean - 275) / 25) ** 2))
rc = 2 * np.sqrt(cp_mean ** 7 / (cp_mean ** 7 + 25.0 ** 7))
sl = 1 + 0.015 * (lp_mean - 50) ** 2 / np.sqrt(20 + (lp_mean - 50) ** 2)
sc = 1 + 0.045 * cp_mean
sh = 1 + 0.015 * cp_mean * t
rt = -np.sin(np.radians(2 * d_theta)) * rc
de = np.sqrt((dlp / sl) ** 2 + (dcp / sc) ** 2 + (dhp / sh) ** 2 + rt * (dcp / sc) * (dhp / sh))
return float(de.mean())
class DnCNN:
"""assets/dncnn.tflite: single-channel 256x256 blind denoiser on 8-bit sRGB luma / 255."""
PATCH = 256
OVERLAP = 32
def __init__(self, model_path: str):
from ai_edge_litert.interpreter import Interpreter
self.interpreter = Interpreter(model_path=model_path)
self.interpreter.allocate_tensors()
self.input = self.interpreter.get_input_details()[0]
self.output = self.interpreter.get_output_details()[0]
def denoise(self, luma: np.ndarray) -> np.ndarray:
"""luma [H, W] in [0, 1], quantised to 8 bit as the app does; overlapping patches, centre kept."""
quantised = np.round(np.clip(luma, 0, 1) * 255) / 255
h, w = quantised.shape
step = self.PATCH - 2 * self.OVERLAP
out = np.zeros_like(quantised, dtype=F32)
padded = np.pad(quantised, self.OVERLAP, mode="reflect")
for y in range(0, h, step):
for x in range(0, w, step):
patch = np.zeros((self.PATCH, self.PATCH), dtype=F32)
src = padded[y:y + self.PATCH, x:x + self.PATCH]
patch[:src.shape[0], :src.shape[1]] = src
self.interpreter.set_tensor(self.input["index"], patch.reshape(self.input["shape"]))
self.interpreter.invoke()
result = self.interpreter.get_tensor(self.output["index"]).reshape(self.PATCH, self.PATCH)
core = result[self.OVERLAP:self.OVERLAP + step, self.OVERLAP:self.OVERLAP + step]
hh, ww = min(step, h - y), min(step, w - x)
out[y:y + hh, x:x + ww] = core[:hh, :ww]
return out
+83
View File
@@ -0,0 +1,83 @@
"""Reader for PhotonDenoiseDump files (docs/photon-multiscale-denoise.md section 12.4).
Usage: uv run --with numpy python -I tools/photon_denoise/load_dump.py <stem-or-.json> [...]
Prints per-channel statistics of the dumped camera RGB, the noise profile, and the LSC gain
field resampled at the image the way it was applied (merge: whole-image UV bilinear,
green = mean of both greens; demosaic: Camera2 UV or DNG GainMap grid).
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
import numpy as np
def load(path: str) -> tuple[np.ndarray, dict]:
stem = Path(path).with_suffix("")
meta = json.loads(stem.with_suffix(".json").read_text())
raw = np.fromfile(stem.with_suffix(".rgba16f"), dtype="<f2")
rgba = raw.reshape(meta["height"], meta["width"], 4).astype(np.float32)
return np.moveaxis(rgba[..., :3], -1, 0), meta
def _bilinear(grid: np.ndarray, u: np.ndarray, v: np.ndarray) -> np.ndarray:
"""GL_LINEAR sampling with clamp-to-edge of grid [H, W] at texture coordinates u, v in [0, 1]."""
h, w = grid.shape
x = np.clip(u * w - 0.5, 0, w - 1)
y = np.clip(v * h - 0.5, 0, h - 1)
x0 = np.floor(x).astype(int)
y0 = np.floor(y).astype(int)
x1 = np.minimum(x0 + 1, w - 1)
y1 = np.minimum(y0 + 1, h - 1)
fx = x - x0
fy = y - y0
top = grid[y0[:, None], x0[None, :]] * (1 - fx)[None, :] + grid[y0[:, None], x1[None, :]] * fx[None, :]
bottom = grid[y1[:, None], x0[None, :]] * (1 - fx)[None, :] + grid[y1[:, None], x1[None, :]] * fx[None, :]
return top * (1 - fy)[:, None] + bottom * fy[:, None]
def gain_field(meta: dict) -> np.ndarray | None:
"""RGB gain [3, H, W] contained in the dumped pixels (section 3), or None."""
lsc = meta.get("lensShading")
if lsc is None:
return None
gains = np.asarray(lsc["gains"], dtype=np.float32).reshape(lsc["height"], lsc["width"], 4)
if lsc.get("dngGrid") is not None:
raise NotImplementedError("DNG GainMap grids are reproduced once a DNG-grid capture is dumped")
width, height = meta["fullWidth"], meta["fullHeight"]
xs = meta["originX"] + np.arange(meta["width"]) + 0.5
ys = meta["originY"] + np.arange(meta["height"]) + 0.5
u, v = xs / width, ys / height
channels = [gains[..., 0], 0.5 * (gains[..., 1] + gains[..., 2]), gains[..., 3]]
return np.stack([_bilinear(c, u, v) for c in channels])
def main() -> int:
for path in sys.argv[1:]:
rgb, meta = load(path)
print(f"{Path(path).name}: {meta['pipeline']} {meta['width']}x{meta['height']} "
f"origin=({meta['originX']},{meta['originY']}) full={meta['fullWidth']}x{meta['fullHeight']} "
f"cfa={meta['cfaPattern']} frames={meta['frameCount']} iso={meta['iso']}")
for c, name in enumerate("RGB"):
channel = rgb[c]
print(f" {name}: mean={channel.mean():.5f} min={channel.min():.5f} max={channel.max():.5f} "
f"finite={np.isfinite(channel).all()}")
print(f" WB={meta['whiteBalanceGains']} profile read={meta.get('profileRgbRead')} "
f"shot={meta.get('profileRgbShot')}")
gain = gain_field(meta)
if gain is None:
print(" LSC in pixels: none")
else:
lsc = meta["lensShading"]
print(f" LSC in pixels: {lsc['source']} map {lsc['width']}x{lsc['height']} "
f"gain R {gain[0].min():.3f}..{gain[0].max():.3f} "
f"G {gain[1].min():.3f}..{gain[1].max():.3f} B {gain[2].min():.3f}..{gain[2].max():.3f}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+277
View File
@@ -0,0 +1,277 @@
"""Model error of the profile x white-noise model (docs/photon-multiscale-denoise.md section 12.1).
Two denoise-input dumps of the same static scene with identical settings (tripod; for merge
pipelines two independent merges) are decomposed with the denoiser's pyramid. Their Laplacian
difference D_l = (L_l^A - L_l^B) / sqrt(2) cancels the scene and leaves one image's noise; its
variance per (component, level, phase, luma bin) is compared with the model of section 2.1.
The ratio is recorded in section 13; it never enters the algorithm.
Misalignment guard: the same-level Gaussian difference G_l^A - G_l^B is noise only when the
pair is aligned. Pixels where any component exceeds GUARD_SIGMAS robust standard deviations of
its luma bin (MAD, independent of the model under test) are excluded, dilated by 3 pixels.
Usage:
uv run --with numpy python -I tools/photon_denoise/model_error.py A.json B.json [C.json D.json ...]
uv run --with numpy python -I tools/photon_denoise/model_error.py --self-test
Each consecutive pair of dumps is one measurement; a dump is <stem>.{json,rgba16f,params.json}.
"""
from __future__ import annotations
import json
import sys
import warnings
from dataclasses import dataclass
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import compare_passes as cp # noqa: E402
import noise_model # noqa: E402
import photon_denoise as pd # noqa: E402
F32 = np.float32
BIN_COUNT = 12
BIN_MIN = 2.0 ** -10
BIN_MAX = 1.0
MID_GREY = 0.18
GUARD_SIGMAS = 4.0
GUARD_DILATION = 3
MIN_SAMPLES = 400
SELF_TEST_MIN_SIGNAL = 2.0 ** -7
COMPONENTS = ("Y", "Cb", "Cr")
@dataclass
class Dump:
rgb: np.ndarray
meta: dict
params: pd.Params
def load(path: str) -> Dump:
stem = Path(path)
stem = stem.with_suffix("") if stem.suffix == ".json" else stem
meta = json.loads(stem.with_suffix(".json").read_text())
raw = np.fromfile(stem.with_suffix(".rgba16f"), dtype="<f2").reshape(meta["height"], meta["width"], 4)
params = cp.params_from_json(json.loads(Path(f"{stem}.params.json").read_text()))
return Dump(np.moveaxis(raw[..., :3].astype(F32), -1, 0), meta, params)
def pyramid(rgb: np.ndarray, params: pd.Params) -> list[np.ndarray]:
sizes = pd.level_sizes(rgb.shape[1], rgb.shape[2], params.levels)
gaussians = [pd.analyze0(rgb, params)]
for level in range(params.levels):
gaussians.append(pd.down(gaussians[-1], sizes[level + 1]))
return gaussians
def luma_bins(mu: np.ndarray) -> np.ndarray:
out = np.full(mu.shape, -1, dtype=np.int64)
valid = (mu >= BIN_MIN) & (mu < BIN_MAX)
t = (np.log2(mu[valid]) - np.log2(BIN_MIN)) / (np.log2(BIN_MAX) - np.log2(BIN_MIN))
out[valid] = np.minimum((t * BIN_COUNT).astype(np.int64), BIN_COUNT - 1)
return out
def bin_centres() -> np.ndarray:
edges = np.exp2(np.linspace(np.log2(BIN_MIN), np.log2(BIN_MAX), BIN_COUNT + 1))
return np.sqrt(edges[:-1] * edges[1:])
def _dilate(mask: np.ndarray, radius: int) -> np.ndarray:
out = mask.copy()
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
out |= np.roll(np.roll(mask, dy, axis=0), dx, axis=1)
return out
@dataclass
class LevelError:
ratio: np.ndarray # [3, 4 phases, bins] measured / model variance (nan when too few samples)
samples: np.ndarray # [4, bins]
correlation: np.ndarray # [bins] measured Cb-Cr correlation
model_correlation: np.ndarray
excluded: float # fraction removed by the misalignment guard
def measure_pair(a: Dump, b: Dump) -> list[LevelError]:
if a.rgb.shape != b.rgb.shape:
raise ValueError("pair sizes differ")
params = a.params
ga, gb = pyramid(a.rgb, params), pyramid(b.rgb, params)
results = []
for level in range(params.levels):
shape = ga[level].shape[1:]
coarse_mean = F32(0.5) * (ga[level + 1] + gb[level + 1])
base = pd.up(coarse_mean, shape)
diff = ((ga[level] - pd.up(ga[level + 1], shape)) - (gb[level] - pd.up(gb[level + 1], shape))) / F32(np.sqrt(2))
_, _, noise = pd.band(ga[level], ga[level + 1], coarse_mean, level, params) # model at base
mu = base[0] / F32(params.scale)
bins = luma_bins(mu)
# Same-level Gaussian difference: a misaligned edge survives here, while the coarser
# level smooths a 1-pixel shift below detection. Truncating pure noise at 4 sigma
# removes 6e-5 of its samples and 0.07% of its variance, below the sampling error.
level_diff = ga[level] - gb[level]
flagged = np.zeros(shape, dtype=bool)
for b_index in range(BIN_COUNT):
m = bins == b_index
if m.sum() < MIN_SAMPLES:
continue
for k in range(3):
values = level_diff[k][m]
centre = np.median(values)
sigma = 1.4826 * np.median(np.abs(values - centre))
flagged[m] |= np.abs(values - centre) > GUARD_SIGMAS * max(sigma, 1e-30)
excluded = _dilate(flagged, GUARD_DILATION)
valid = (bins >= 0) & ~excluded & (noise[0] > 0)
yy, xx = np.mgrid[0:shape[0], 0:shape[1]]
phase = (yy & 1) * 2 + (xx & 1)
ratio = np.full((3, 4, BIN_COUNT), np.nan)
samples = np.zeros((4, BIN_COUNT))
correlation = np.full(BIN_COUNT, np.nan)
model_correlation = np.full(BIN_COUNT, np.nan)
for b_index in range(BIN_COUNT):
in_bin = valid & (bins == b_index)
for p in range(4):
m = in_bin & (phase == p)
n = int(m.sum())
samples[p, b_index] = n
if n < MIN_SAMPLES:
continue
for k in range(3):
ratio[k, p, b_index] = np.mean(diff[k][m] ** 2) / np.mean(noise[k][m])
if in_bin.sum() >= MIN_SAMPLES:
cb, cr = diff[1][in_bin], diff[2][in_bin]
correlation[b_index] = np.mean(cb * cr) / np.sqrt(np.mean(cb * cb) * np.mean(cr * cr))
model_correlation[b_index] = np.mean(noise[3][in_bin]) / np.sqrt(
np.mean(noise[1][in_bin]) * np.mean(noise[2][in_bin]))
results.append(LevelError(ratio, samples, correlation, model_correlation, float(excluded.mean())))
return results
def _mid_grey(values: np.ndarray, samples: np.ndarray) -> float:
"""Sample-weighted value of the measured bin nearest mid-grey; nan when none is measured."""
centres = bin_centres()
measured = np.isfinite(values)
if not measured.any():
return float("nan")
nearest = np.argmin(np.where(measured, np.abs(np.log(centres) - np.log(MID_GREY)), np.inf))
return float(values[nearest])
def report(label: str, a: Dump, errors: list[LevelError]) -> list[str]:
with warnings.catch_warnings():
# Bins without enough samples are nan by design; their means are nan as well.
warnings.simplefilter("ignore", RuntimeWarning)
return _report(label, a, errors)
def _report(label: str, a: Dump, errors: list[LevelError]) -> list[str]:
centres = bin_centres()
print(f"\n{label}: {a.meta['pipeline']} {a.meta['width']}x{a.meta['height']} iso={a.meta['iso']} "
f"frames={a.meta['frameCount']} levels={len(errors)}")
rows = []
for k, name in enumerate(COMPONENTS):
print(f" {name}: measured/model per level (phase mean), luma bins " +
" ".join(f"{c:.3g}" for c in centres))
mids = []
for level, error in enumerate(errors):
per_bin = np.nanmean(error.ratio[k], axis=0) if np.isfinite(error.ratio[k]).any() else \
np.full(BIN_COUNT, np.nan)
mids.append(_mid_grey(per_bin, error.samples.sum(axis=0)))
cells = " ".join(" - " if not np.isfinite(v) else f"{v:5.2f}" for v in per_bin)
phases = np.nanmean(error.ratio[k], axis=1)
print(f" L{level} [{cells}] phases={np.round(phases, 2).tolist()} excluded={error.excluded:.1%}")
rows.append((name, mids))
corr = [(_mid_grey(e.correlation, e.samples.sum(axis=0)), _mid_grey(e.model_correlation, e.samples.sum(axis=0)))
for e in errors]
print(" Cb-Cr correlation at mid-grey per level (measured / model): " +
", ".join(f"L{l} {m:+.2f}/{p:+.2f}" for l, (m, p) in enumerate(corr)))
lines = []
for name, mids in rows:
cells = " / ".join("—" if not np.isfinite(v) else f"{v:.2f}" for v in mids)
corr_cell = "; ".join(f"L{l} {m:+.2f}/{p:+.2f}" for l, (m, p) in enumerate(corr)) if name == "Cb" else ""
excluded = max(e.excluded for e in errors)
lines.append(f"| {a.meta['pipeline']} | {a.meta['iso']} | {name} | {cells} | {corr_cell} | "
f"帧数 {a.meta['frameCount']},错位剔除 ≤{excluded:.1%} |")
return lines
def self_test() -> bool:
"""White noise satisfies the model exactly: every ratio must be within max(5%, 4 standard errors).
B also contains a moving object (a bright patch absent from A): the guard must keep the
ratios unbiased. A sub-pixel or 1-pixel global shift is not emulated: its residue is of the
order of the noise per pixel, no statistical guard can separate it, and the capture protocol
(tripod, remote shutter) has to exclude it.
"""
rng = np.random.default_rng(11)
h, w = 1536, 2048
yy, xx = np.mgrid[0:h, 0:w]
luma = np.exp2(-8.0 + 7.5 * xx / w) * (0.9 + 0.1 * np.sin(yy / 23.0))
wb = np.array([2.0, 1.0, 1.6], dtype=F32)
clean = np.stack([luma * 1.05, luma, luma * 0.95]).astype(F32) / wb[:, None, None]
texture = 1 + 0.3 * (np.sin(xx / 3.1) * np.sin(yy / 2.7) > 0.6)
clean = (clean * texture[None]).astype(F32)
read = np.array([2e-5, 1.5e-5, 2.5e-5], dtype=F32)
shot = np.array([3e-4, 2.5e-4, 3.5e-4], dtype=F32)
def noisy(scene: np.ndarray) -> np.ndarray:
return pd.f16(scene + np.sqrt(read[:, None, None] + shot[:, None, None] * scene) *
rng.standard_normal(scene.shape).astype(F32))
moved = clean.copy()
moved[:, h // 4: h // 4 + 120, w // 3: w // 3 + 200] *= 2.5
levels = 5
kappa = noise_model.Kappa0.build(levels, levels)
params = pd.Params(4096.0, wb, read, shot, 1.0, 1.0, np.ones((levels, 3), dtype=F32), kappa.luma.astype(F32),
kappa.chroma.astype(F32), levels, levels, np.ones(levels, dtype=F32),
np.full(levels, 0.2, dtype=F32), np.full(levels, 2.5, dtype=F32), (16.919, 27.877),
(5.991, 13.816), 3, 4.0, 4.0, 1.0, 1.0, None)
meta = {"pipeline": "SELF_TEST", "width": w, "height": h, "iso": 0, "frameCount": 1}
errors = measure_pair(Dump(noisy(clean), meta, params), Dump(noisy(moved), meta, params))
report("self-test", Dump(clean, meta, params), errors)
# Allowed deviation per bin: 5%, or 4 standard errors of a variance estimate from n samples.
# Bins below SELF_TEST_MIN_SIGNAL are reported but not judged: there the coarse base's own
# noise exceeds the signal and the model's max(mu, 0) raises the predicted variance. That is
# a genuine model error of the denoiser in the deepest shadows, not an error of this tool.
judged = bin_centres() >= SELF_TEST_MIN_SIGNAL
worst = 0.0
corr_worst = 0.0
for e in errors:
tolerance = np.maximum(0.05, 4 * np.sqrt(2 / np.maximum(e.samples, 1)))
excess = np.abs(e.ratio - 1)[:, :, judged] / tolerance[None][:, :, judged]
worst = max(worst, float(np.nanmax(excess)) if np.isfinite(excess).any() else 0.0)
n_bin = e.samples.sum(axis=0)
corr_excess = (np.abs(e.correlation - e.model_correlation)
/ np.maximum(0.03, 4 / np.sqrt(np.maximum(n_bin, 1))))[judged]
corr_worst = max(corr_worst, float(np.nanmax(corr_excess)) if np.isfinite(corr_excess).any() else 0.0)
ok = worst <= 1.0 and corr_worst <= 1.0
print(f"self-test worst deviation {worst:.3f}x tolerance, Cb-Cr correlation {corr_worst:.3f}x tolerance: "
f"{'PASS' if ok else 'FAIL'}")
return ok
def main() -> int:
if sys.argv[1:] == ["--self-test"]:
return 0 if self_test() else 1
paths = sys.argv[1:]
if len(paths) < 2 or len(paths) % 2:
print(__doc__)
return 2
rows = []
for i in range(0, len(paths), 2):
a, b = load(paths[i]), load(paths[i + 1])
rows += report(f"{Path(paths[i]).name} vs {Path(paths[i + 1]).name}", a, measure_pair(a, b))
print("\n§13 rows:")
print("\n".join(rows))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+264
View File
@@ -0,0 +1,264 @@
"""Reference implementation of PhotonNoiseState and pyramid noise propagation.
This module is the executable specification for docs/photon-multiscale-denoise.md
sections 2 and 5. The Kotlin port (raw/denoise/PhotonNoiseState.kt and
PhotonNoisePropagation.kt) must reproduce these tables.
Conventions
-----------
* A spatial spectrum is 128 half-bin-centred samples of the 1D power spectrum,
omega_k = (k + 0.5) * 2*pi / 128 - pi (the convention already used by
DemosaicNoiseSpectrum). The 2D spectrum is the outer product P_x (x) P_y.
* The autocorrelation is r(d) = mean_k P(omega_k) cos(omega_k d), so r(0) =
mean(P). A spectrum normalised to unit mean carries no amplitude; a
non-normalised spectrum keeps its amplitude in r(0).
* Separable spectrum + separable filters => all propagation factorises into
1D quantities per axis.
"""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
SPECTRUM_SIZE = 128
MAX_LAG = 63
LUMA_TAPS = np.array([-1.0, 0.0, 9.0, 16.0, 9.0, 0.0, -1.0]) / 32.0
CHROMA_TAPS = np.array([1.0, 4.0, 6.0, 4.0, 1.0]) / 16.0
# Working YCbCr: Y = (R + 2G + B) / 4, Cb = B - G, Cr = R - G.
YCC_FROM_RGB = np.array(
[
[0.25, 0.5, 0.25],
[0.0, -1.0, 1.0],
[1.0, -1.0, 0.0],
]
)
def spectrum_frequencies() -> np.ndarray:
k = np.arange(SPECTRUM_SIZE, dtype=np.float64)
return (k + 0.5) * 2.0 * np.pi / SPECTRUM_SIZE - np.pi
def autocorrelation(spectrum: np.ndarray, max_lag: int = MAX_LAG) -> np.ndarray:
"""Autocorrelation r(d) for d = -max_lag..max_lag (index d + max_lag)."""
p = np.asarray(spectrum, dtype=np.float64)
if p.shape != (SPECTRUM_SIZE,) or np.any(~np.isfinite(p)) or np.any(p < 0):
raise ValueError("spectrum must be 128 finite non-negative samples")
lags = np.arange(-max_lag, max_lag + 1, dtype=np.float64)
return (p[None, :] * np.cos(np.outer(lags, spectrum_frequencies()))).mean(axis=1)
def _lag(r: np.ndarray, d: int) -> float:
half = (r.size - 1) // 2
return float(r[d + half]) if -half <= d <= half else 0.0
def decimate_autocorrelation(r: np.ndarray, taps: np.ndarray) -> np.ndarray:
"""r_{l+1}(d) = sum_m (h * h~)(m) r_l(2d - m): exact for G_{l+1} = down2(h * G_l)."""
hh = np.convolve(taps, taps[::-1])
hh_radius = (hh.size - 1) // 2
half = (r.size - 1) // 2
out = np.zeros_like(r)
for d in range(-half, half + 1):
acc = 0.0
for i, weight in enumerate(hh):
acc += weight * _lag(r, 2 * d - (i - hh_radius))
out[d + half] = acc
return out
def phase_kernel(taps: np.ndarray, phase: int) -> dict[int, float]:
"""a_phi(e): weight of G_l(p + e) in (up2(2h * down2(h * G_l)))(p), p = phase mod 2.
G_{l+1}(q) sits at G_l position 2q, so j = p - 2q has the parity of p and
a_phi(e) = sum_{j = phi mod 2} u(j) h(-j - e), u = 2h.
"""
radius = (taps.size - 1) // 2
kernel: dict[int, float] = {}
for j in range(-radius, radius + 1):
if (j - phase) % 2 != 0:
continue
u = 2.0 * taps[j + radius]
for i in range(-radius, radius + 1):
# h index = -j - e => e = -j - i
e = -j - i
kernel[e] = kernel.get(e, 0.0) + u * taps[i + radius]
return kernel
def laplacian_axis_terms(r: np.ndarray, taps: np.ndarray, phase: int) -> tuple[float, float, float]:
"""Per-axis (A0, A1, A2) with Var[L] = A0x A0y - 2 A1x A1y + A2x A2y."""
a = phase_kernel(taps, phase)
a0 = _lag(r, 0)
a1 = sum(w * _lag(r, e) for e, w in a.items())
a2 = sum(wi * wj * _lag(r, ei - ej) for ei, wi in a.items() for ej, wj in a.items())
return a0, a1, a2
@dataclass(frozen=True)
class PropagationTable:
"""kappa_gaussian[l]: Var[G_l] / sigma^2 ; kappa_laplacian[l, phase]: Var[L_l] / sigma^2.
phase = (y & 1) * 2 + (x & 1). sigma^2 is the unit-correlation variance of the
level-0 signal; a non-normalised spectrum keeps its amplitude inside kappa.
"""
kappa_gaussian: np.ndarray
kappa_laplacian: np.ndarray
def propagate(spectrum_x: np.ndarray, spectrum_y: np.ndarray, taps: np.ndarray, levels: int) -> PropagationTable:
rx = autocorrelation(spectrum_x)
ry = autocorrelation(spectrum_y)
kappa_g = np.zeros(levels + 1)
kappa_l = np.zeros((levels, 4))
for level in range(levels + 1):
kappa_g[level] = _lag(rx, 0) * _lag(ry, 0)
if level == levels:
break
tx = [laplacian_axis_terms(rx, taps, phase) for phase in (0, 1)]
ty = [laplacian_axis_terms(ry, taps, phase) for phase in (0, 1)]
for py in (0, 1):
for px in (0, 1):
a0x, a1x, a2x = tx[px]
a0y, a1y, a2y = ty[py]
kappa_l[level, py * 2 + px] = a0x * a0y - 2.0 * a1x * a1y + a2x * a2y
rx = decimate_autocorrelation(rx, taps)
ry = decimate_autocorrelation(ry, taps)
return PropagationTable(kappa_g, kappa_l)
@dataclass(frozen=True)
class NoiseState:
"""Section 2.1 model in normalised, un-white-balanced camera RGB.
read/shot/quadratic: per CFA source channel R, G, B.
transfer: T_c, 3x3 PSD contribution of source channel c to output RGB covariance.
"""
read: np.ndarray
shot: np.ndarray
quadratic: np.ndarray
transfer: np.ndarray # [3 source, 3, 3]
def source_variance(self, mu: np.ndarray, gain: np.ndarray, merge_read: float = 1.0,
merge_shot: float = 1.0) -> np.ndarray:
"""v_c = m_r g_c^2 r_c + m_s g_c s_c mu_c + q_c mu_c^2 (mu in the same domain as the coefficients)."""
mu = np.asarray(mu, dtype=np.float64)
gain = np.asarray(gain, dtype=np.float64)
return merge_read * gain * gain * self.read + merge_shot * gain * self.shot * mu + self.quadratic * mu * mu
def working_transfer(self, white_balance: np.ndarray, scale: float) -> np.ndarray:
"""T'_c = (K M W) T_c (K M W)^T in the working YCbCr domain."""
a = scale * YCC_FROM_RGB @ np.diag(white_balance)
return np.einsum("ij,cjk,lk->cil", a, self.transfer, a)
def working_covariance(self, mu_camera: np.ndarray, white_balance: np.ndarray, scale: float,
gain: np.ndarray | None = None) -> np.ndarray:
"""Point covariance Sigma(p) of working YCbCr for camera-RGB signal mu_camera."""
if gain is None:
gain = np.ones(3)
v = self.source_variance(mu_camera, gain)
return np.einsum("c,cij->ij", v, self.working_transfer(white_balance, scale))
# ------------------------------------------------- profile x white-noise model
#
# docs/photon-multiscale-denoise.md section 2: the denoiser's noise model is the RAW
# profile times the exact white-noise energy of the pyramid. The classes above (transfer
# matrices, measured spectra) belong to the abandoned propagation design and only serve
# validate_propagation.py, which verifies the propagation used for kappa0.
LUMA = 0
CHROMA = 1
@dataclass(frozen=True)
class MergeRatio:
"""Section 2.2: m_r, m_s of a weighted merge of frames transported to reference exposure."""
read: float
shot: float
@staticmethod
def single() -> "MergeRatio":
return MergeRatio(1.0, 1.0)
@staticmethod
def of(weights: np.ndarray, read_ratios: np.ndarray, shot_ratios: np.ndarray) -> "MergeRatio":
"""weights w_i; read_ratios r_i / r_ref and shot_ratios s_i / s_ref per frame."""
w = np.asarray(weights, dtype=np.float64)
if w.ndim != 1 or w.size == 0 or np.any(w < 0) or w.sum() <= 0:
raise ValueError("merge weights must be non-negative with a positive sum")
total = w.sum() ** 2
return MergeRatio(float(np.sum(w * w * read_ratios) / total), float(np.sum(w * w * shot_ratios) / total))
def working_point_covariance(read: np.ndarray, shot: np.ndarray, mu_camera: np.ndarray,
white_balance: np.ndarray, scale: float,
merge: MergeRatio = MergeRatio(1.0, 1.0)) -> np.ndarray:
"""A diag(m_r r_c + m_s s_c mu_c) A^T with A = K M W: independent source channels, no spatial process.
read/shot are the profile's per-channel coefficients (normalised, un-white-balanced camera
RGB, both greens averaged); mu_camera is the LSC-divided camera RGB signal.
"""
a = scale * YCC_FROM_RGB @ np.diag(white_balance)
source = merge.read * np.asarray(read) + merge.shot * np.asarray(shot) * np.maximum(mu_camera, 0.0)
return a @ np.diag(source) @ a.T
@dataclass(frozen=True)
class Kappa0:
"""White-noise Laplacian energy per (filter, level, phase): luma [levels, 4], chroma [levels, 4]."""
luma: np.ndarray
chroma: np.ndarray
@staticmethod
def build(luma_levels: int, chroma_levels: int) -> "Kappa0":
unit = np.ones(SPECTRUM_SIZE)
return Kappa0(
propagate(unit, unit, LUMA_TAPS, luma_levels).kappa_laplacian,
propagate(unit, unit, CHROMA_TAPS, chroma_levels).kappa_laplacian,
)
def to_json(self) -> dict:
return {"luma": self.luma.tolist(), "chroma": self.chroma.tolist(),
"luma_taps": LUMA_TAPS.tolist(), "chroma_taps": CHROMA_TAPS.tolist()}
@dataclass(frozen=True)
class LevelNoise:
"""Laplacian-band noise of one level and phase: Y variance and the Cb/Cr 2x2 covariance."""
luma_variance: float
chroma_covariance: np.ndarray
def level_noise(point_covariance: np.ndarray, kappa0: Kappa0, level: int, phase: int,
residual: np.ndarray | None = None) -> LevelNoise:
"""Section 2.1 for one level and phase.
residual: t^2 per component (Y, Cb, Cr) of an already denoised input (section 2.4); the
covariance scales as D Sigma D with D = diag(t). Y and Cb/Cr live in different pyramids,
so no Y-C cross term is defined.
"""
t = np.ones(3) if residual is None else np.sqrt(np.asarray(residual, dtype=np.float64))
scaled = point_covariance * np.outer(t, t)
return LevelNoise(
float(kappa0.luma[level, phase] * scaled[0, 0]),
kappa0.chroma[level, phase] * scaled[1:, 1:],
)
if __name__ == "__main__":
import json
import sys
luma_levels = int(sys.argv[1]) if len(sys.argv) > 1 else 5
chroma_levels = int(sys.argv[2]) if len(sys.argv) > 2 else 7
print(json.dumps(Kappa0.build(luma_levels, chroma_levels).to_json(), indent=2))
+648
View File
@@ -0,0 +1,648 @@
"""Reference implementation of the Photon multi-scale denoiser passes.
Executable specification for docs/photon-multiscale-denoise.md sections 2-8 and 10. Every
function mirrors one GLES pass in raw/denoise/PhotonDenoiseShaders.kt: arithmetic in float32
(highp), texture stores rounded to the storage format (RGBA16F -> float16, RGBA32F ->
float32). compare_passes.py feeds each pass with the GPU's own inputs and compares outputs.
Images are channel-first float32 arrays [C, H, W].
"""
from __future__ import annotations
from dataclasses import dataclass, field, replace
import numpy as np
import noise_model
F32 = np.float32
LUMA_TAPS = noise_model.LUMA_TAPS.astype(F32)
CHROMA_TAPS = noise_model.CHROMA_TAPS.astype(F32)
YCC_FROM_RGB = noise_model.YCC_FROM_RGB.astype(F32)
RGB_FROM_YCC = np.array([[1.0, -0.25, 0.75], [1.0, -0.25, -0.25], [1.0, 0.75, -0.25]], dtype=F32)
CLIP_LEVEL = F32(0.98) # section 6.5: camera RGB (LSC restored) at or above this carries no noise model
WINDOW_RADIUS = 2 # 5x5 luma window
BASE_RADIUS = 1.25 # luma window radius before anisotropic stretching
BILATERAL_SIGMA = 1.5
CENTRE_LOW = F32(6.0) # pilot: the window centre enters the energy only as a point of
CENTRE_HIGH = F32(10.0) # smoothstep(CENTRE_LOW, CENTRE_HIGH, |L| / sigma)
GAMMA_LOW = F32(0.25) # section 6.1: the gain exponent applies from smoothstep(GAMMA_LOW,
GAMMA_HIGH = F32(0.5) # GAMMA_HIGH, gain); below, the MMSE gain
PREFILTER_K = F32(2.5) # section 6.0: outlier distance from the 3x3 median, in L0 sigmas
PREFILTER_GUARD = 2 # at most this many same-signed 3x3 neighbours beyond PREFILTER_K
PREFILTER_FLAT = F32(3.0) # mean L0^2 of the 5x5 ring below PREFILTER_FLAT sigma^2
# Section 5.1 per-image strength table [levels, STRENGTH_BINS, 3] (Y, Cb, Cr).
STRENGTH_BINS = 8
STRENGTH_LOW = F32(-8.0) # log2(Y / K) of bin 0's lower edge; 1-stop bins
HIST_BUCKETS = 64 # log2(L^2 / N) histogram over [HIST_LOW, HIST_HIGH)
HIST_LOW = F32(-12.0)
HIST_HIGH = F32(8.0)
MIN_SAMPLES = 200
CHI2_MEDIAN = F32(0.45493642) # median of chi-square with one degree of freedom
MAX_STRENGTH = F32(4096.0)
FLAT_GATE = F32(0.5)
ESTIMATE_PASSES = 3 # each pass gates with the previous pass's luma strength
SPIKE = F32(1.5) # bound (both ways) relative to the median of the 5-bin neighbourhood
MAX_GROWTH = F32(2.0) # level-to-level growth used for an unmeasured level
def f16(x: np.ndarray) -> np.ndarray:
return x.astype(np.float16).astype(F32)
# ------------------------------------------------------------------ geometry
def mirror(i: np.ndarray, n: int) -> np.ndarray:
"""Reflect without edge repetition (period 2n - 2)."""
if n == 1:
return np.zeros_like(i)
period = 2 * n - 2
i = np.abs(i) % period
return np.where(i >= n, period - i, i)
def level_sizes(height: int, width: int, levels: int) -> list[tuple[int, int]]:
sizes = [(height, width)]
for _ in range(levels):
h, w = sizes[-1]
sizes.append(((h + 1) // 2, (w + 1) // 2))
return sizes
def taps_for(component: int) -> np.ndarray:
return LUMA_TAPS if component == 0 else CHROMA_TAPS
def down(fine: np.ndarray, coarse_shape: tuple[int, int]) -> np.ndarray:
"""G_{l+1}(y,x) = sum h_i h_j G_l(mirror(2y+i), mirror(2x+j)); Y with luma taps, Cb/Cr chroma."""
h, w = fine.shape[1:]
hc, wc = coarse_shape
out = np.zeros((fine.shape[0], hc, wc), dtype=F32)
for k in range(fine.shape[0]):
taps = taps_for(k)
r = taps.size // 2
ys = mirror(2 * np.arange(hc)[:, None] + np.arange(-r, r + 1)[None, :], h) # [hc, taps]
xs = mirror(2 * np.arange(wc)[:, None] + np.arange(-r, r + 1)[None, :], w)
rows = np.einsum("t,ytx->yx", taps, fine[k][ys, :]) # vertical first
out[k] = np.einsum("t,yxt->yx", taps, rows[:, xs]).astype(F32)
return out
def up(coarse: np.ndarray, fine_shape: tuple[int, int]) -> np.ndarray:
"""U(y,x) = sum over i with (y-i) even, j with (x-j) even of 2h_i 2h_j C(mirror((y-i)/2), mirror((x-j)/2))."""
hc, wc = coarse.shape[1:]
h, w = fine_shape
out = np.zeros((coarse.shape[0], h, w), dtype=F32)
for k in range(coarse.shape[0]):
taps = 2.0 * taps_for(k)
r = taps.size // 2
def weights(n_fine: int, n_coarse: int) -> np.ndarray:
mat = np.zeros((n_fine, n_coarse), dtype=F32)
for y in range(n_fine):
for i in range(-r, r + 1):
if (y - i) % 2:
continue
mat[y, mirror(np.array((y - i) // 2), n_coarse)] += taps[i + r]
return mat
wy, wx = weights(h, hc), weights(w, wc)
out[k] = (wy @ coarse[k] @ wx.T).astype(F32)
return out
# --------------------------------------------------------------- parameters
@dataclass
class Params:
"""Mirror of PhotonDenoiseParams (Kotlin); all levels share index l = 0 .. levels-1."""
scale: float # K
white_balance: np.ndarray # W [3], camera RGB -> white balanced
read: np.ndarray # profile read [3]
shot: np.ndarray # profile shot [3]
merge_read: float # section 2.2 nominal ratios (all frames accepted)
merge_shot: float
residual: np.ndarray # t^2 per level and component [levels, 3]
kappa_luma: np.ndarray # [levels, 4]
kappa_chroma: np.ndarray # [levels, 4]
levels: int
luma_levels: int
alpha: np.ndarray # [levels] luma Wiener over-subtraction
grain: np.ndarray # [levels] luma residual noise ratio t_l
outlier: np.ndarray # [levels] Huber distance d_l
gate_luma: tuple[float, float] # chi2_9 thresholds (low, high)
gate_chroma: tuple[float, float] # chi2_2 thresholds (low, high)
bilateral_levels: int
bilateral_luma: float # c_Y
bilateral_chroma: float # c_C
luma_strength: float
chroma_strength: float
lsc: "LensShading | None" = None
# Section 5.1 strength table [levels, STRENGTH_BINS, 3]; None: estimated from the image.
strength_table: np.ndarray | None = None
# Section 5.1 caps of the estimate per level at the image SNR; None: MAX_STRENGTH.
strength_cap_luma: np.ndarray | None = None
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)
def luma_grain(self, level: int) -> float:
t, s = float(self.grain[level]), self.luma_strength
return 1.0 - s * (1.0 - t) if s <= 1.0 else t * (2.0 - s)
def luma_alpha(self, level: int) -> float:
return float(self.alpha[level]) * max(self.luma_strength, 1.0) ** 2
def chroma_thresholds(self, low_high: tuple[float, float]) -> tuple[float, float]:
factor = max(self.chroma_strength, 1.0) ** 2
return low_high[0] * factor, low_high[1] * factor
# ------------------------------------------------------------- lens shading
@dataclass
class LensShading:
"""Gains contained in the input pixels (section 3): map [h, w, 4] as R, Ge, Go, B.
dng_grid: [originH, originV, spacingH, spacingV, boundsL, boundsT, boundsR, boundsB] or None
for Camera2 whole-image UV. origin/full place the processed image in the full frame.
"""
gains: np.ndarray
dng_grid: np.ndarray | None
origin: tuple[int, int] # (x, y)
full: tuple[int, int] # (width, height)
def lsc_gain(lsc: LensShading | None, shape: tuple[int, int], level: int) -> np.ndarray | None:
"""RGB gain [3, h, w] at the centres of level-l pixels; manual bilinear, clamp to edge.
A level-l pixel p covers level-0 position (p + 0.5) * 2^l - 0.5; its global centre is
origin + (p + 0.5) * 2^l.
"""
if lsc is None:
return None
step = F32(2 ** level)
gx = F32(lsc.origin[0]) + (np.arange(shape[1], dtype=F32) + F32(0.5)) * step
gy = F32(lsc.origin[1]) + (np.arange(shape[0], dtype=F32) + F32(0.5)) * step
mh, mw = lsc.gains.shape[:2]
if lsc.dng_grid is None:
u = gx / F32(lsc.full[0])
v = gy / F32(lsc.full[1])
else:
g = lsc.dng_grid.astype(F32)
u = (((gx - g[4]) / max(g[6] - g[4], 1.0) - g[0]) / g[2] + F32(0.5)) / F32(mw)
v = (((gy - g[5]) / max(g[7] - g[5], 1.0) - g[1]) / g[3] + F32(0.5)) / F32(mh)
x = np.clip(u * F32(mw) - F32(0.5), 0, mw - 1)
y = np.clip(v * F32(mh) - F32(0.5), 0, mh - 1)
x0 = np.floor(x).astype(int)
y0 = np.floor(y).astype(int)
x1 = np.minimum(x0 + 1, mw - 1)
y1 = np.minimum(y0 + 1, mh - 1)
fx = (x - x0).astype(F32)[None, :, None]
fy = (y - y0).astype(F32)[:, None, None]
m = lsc.gains.astype(F32)
top = m[y0][:, x0] * (1 - fx) + m[y0][:, x1] * fx
bottom = m[y1][:, x0] * (1 - fx) + m[y1][:, x1] * fx
g4 = top * (1 - fy) + bottom * fy # [h, w, 4]
return np.stack([g4[..., 0], F32(0.5) * (g4[..., 1] + g4[..., 2]), g4[..., 3]]).astype(F32)
# --------------------------------------------------------- merge variance map
@dataclass
class MergeMap:
"""Section 2.2 per-pixel merge ratios: map [h, w, 2] as (m_r, m_s) over the whole frame."""
ratios: np.ndarray
origin: tuple[int, int] # (x, y) of the processed image in the full frame
full: tuple[int, int] # (width, height)
def merge_ratio(params: Params, shape: tuple[int, int], level: int) -> tuple[np.ndarray, np.ndarray]:
"""(m_r, m_s) [h, w] at the centres of level-l pixels; manual bilinear of the whole-image map,
clamp to edge, exactly as lsc_gain's Camera2 mode."""
mm = params.merge_map
if mm is None:
return (np.full(shape, params.merge_read, dtype=F32), np.full(shape, params.merge_shot, dtype=F32))
step = F32(2 ** level)
gx = F32(mm.origin[0]) + (np.arange(shape[1], dtype=F32) + F32(0.5)) * step
gy = F32(mm.origin[1]) + (np.arange(shape[0], dtype=F32) + F32(0.5)) * step
mh, mw = mm.ratios.shape[:2]
x = np.clip(gx / F32(mm.full[0]) * F32(mw) - F32(0.5), 0, mw - 1)
y = np.clip(gy / F32(mm.full[1]) * F32(mh) - F32(0.5), 0, mh - 1)
x0 = np.floor(x).astype(int)
y0 = np.floor(y).astype(int)
x1 = np.minimum(x0 + 1, mw - 1)
y1 = np.minimum(y0 + 1, mh - 1)
fx = (x - x0).astype(F32)[None, :, None]
fy = (y - y0).astype(F32)[:, None, None]
m = mm.ratios.astype(F32)
top = m[y0][:, x0] * (1 - fx) + m[y0][:, x1] * fx
bottom = m[y1][:, x0] * (1 - fx) + m[y1][:, x1] * fx
r = (top * (1 - fy) + bottom * fy).astype(F32) # [h, w, 2]
return r[..., 0], r[..., 1]
# --------------------------------------------------------------------- passes
def analyze0(rgb: np.ndarray, params: Params) -> np.ndarray:
"""Camera RGB -> working YCbCr: K M (W rgb / g). Level 0 is never stored on the GPU."""
gains = lsc_gain(params.lsc, rgb.shape[1:], 0)
x = rgb if gains is None else rgb / gains
x = x * params.white_balance.astype(F32)[:, None, None]
return (F32(params.scale) * np.einsum("ij,jyx->iyx", YCC_FROM_RGB, x)).astype(F32)
def point_covariance(base: np.ndarray, params: Params, level: int) -> tuple[np.ndarray, np.ndarray]:
"""Section 2.1 point covariance [3, 3, H, W] of independent source noise at signal base."""
x_wb = np.einsum("ij,jyx->iyx", RGB_FROM_YCC, base) / F32(params.scale)
mu = np.maximum(x_wb / params.white_balance.astype(F32)[:, None, None], 0.0)
m_r, m_s = merge_ratio(params, base.shape[1:], level)
v = (m_r[None] * params.read.astype(F32)[:, None, None]
+ m_s[None] * params.shot.astype(F32)[:, None, None] * mu)
a = F32(params.scale) * YCC_FROM_RGB * params.white_balance.astype(F32)[None, :]
cov = np.einsum("ic,cyx,jc->ijyx", a, v, a).astype(F32)
return cov, mu
def model_noise(base: np.ndarray, level: int, params: Params) -> tuple[np.ndarray, np.ndarray]:
"""Section 2.1 (with 2.2, 2.4) noise (s2_Y, s2_Cb, s2_Cr, s_CbCr) at signal base without the
section 5.1 strength, zero where clipped; and the camera signal mu."""
shape = base.shape[1:]
cov, mu = point_covariance(base, params, level)
yy, xx = np.mgrid[0:shape[0], 0:shape[1]]
phase = (yy & 1) * 2 + (xx & 1)
kl = params.kappa_luma[level][phase].astype(F32)
kc = params.kappa_chroma[level][phase].astype(F32)
t = np.sqrt(params.residual[level]).astype(F32)
noise = np.stack([
kl * cov[0, 0] * t[0] * t[0],
kc * cov[1, 1] * t[1] * t[1],
kc * cov[2, 2] * t[2] * t[2],
kc * cov[1, 2] * t[1] * t[2],
]).astype(F32)
gains = lsc_gain(params.lsc, shape, level)
camera = mu if gains is None else mu * gains
clipped = np.any(camera >= CLIP_LEVEL, axis=0)
noise[:, clipped] = 0.0
return noise, mu
def strength_at(table: np.ndarray | None, level: int, base_y: np.ndarray, scale: float) -> np.ndarray:
"""Section 5.1 (S_Y, S_Cb, S_Cr) [3, H, W]: bins interpolated in log2 of the base luma."""
if table is None:
return np.ones((3,) + base_y.shape, dtype=F32)
x = np.log2(np.maximum(base_y / F32(scale), F32(1e-12))) - STRENGTH_LOW - F32(0.5)
x = np.clip(x, F32(0), F32(STRENGTH_BINS - 1)).astype(F32)
i0 = np.floor(x).astype(int)
i1 = np.minimum(i0 + 1, STRENGTH_BINS - 1)
f = (x - i0).astype(F32)
row = table[level].astype(F32)
return np.stack([row[i0, c] + f * (row[i1, c] - row[i0, c]) for c in range(3)]).astype(F32)
def band(fine: np.ndarray, noisy_coarse: np.ndarray, denoised_coarse: np.ndarray, level: int,
params: Params) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Band pass: (L, base, noise) with noise = (s2_Y, s2_Cb, s2_Cr, s_CbCr), sections 2.1, 5.1."""
shape = fine.shape[1:]
base = up(denoised_coarse, shape)
lap = fine - up(noisy_coarse, shape)
noise, _ = model_noise(base, level, params)
s = strength_at(params.strength_table, level, base[0], params.scale)
noise = (noise * np.stack([s[0], s[1], s[2], np.sqrt(s[1] * s[2])])).astype(F32)
return f16(lap), f16(base), noise
def strength_histogram(fine: np.ndarray, coarse: np.ndarray, level: int, params: Params,
gate_scale: float = 1.0) -> np.ndarray:
"""Section 5.1 steps 1-3 at one level: counts [STRENGTH_BINS, 3, HIST_BUCKETS] of
log2(L^2 / N) over flat sampled pixels. Level 0 samples every 4th pixel, level 1 every 2nd,
each 2x2 block of samples covering all four Bayer phases. The flat gate's noise is the model
luma noise times gate_scale (the previous pass's luma strength)."""
shape = fine.shape[1:]
stride = 4 if level == 0 else 2 if level == 1 else 1
qh, qw = (shape[0] + stride - 1) // stride, (shape[1] + stride - 1) // stride
qy, qx = np.mgrid[0:qh, 0:qw]
if stride > 1:
py, px = qy * stride + (qx & 1), qx * stride + (qy & 1)
else:
py, px = qy, qx
keep = (py < shape[0]) & (px < shape[1])
py, px = py[keep], px[keep]
base_full = up(coarse, shape)
lap = (fine - base_full)[:, py, px]
base = base_full[:, py, px]
noise_full, mu_full = model_noise(base_full, level, params)
noise = noise_full[:, py, px]
mu_g = mu_full[1][py, px]
cy, cx = py >> 1, px >> 1
ch, cw = coarse.shape[1:]
gx = (coarse[0][cy, mirror(cx + 1, cw)] - coarse[0][cy, mirror(cx - 1, cw)]) * F32(0.25)
gy = (coarse[0][mirror(cy + 1, ch), cx] - coarse[0][mirror(cy - 1, ch), cx]) * F32(0.25)
valid = (noise[0] > 0) & (noise[1] > 0) & (noise[2] > 0) & (mu_g > 0)
valid &= np.sqrt(gx * gx + gy * gy) < FLAT_GATE * np.sqrt(F32(gate_scale) * np.maximum(noise[0], F32(0)))
b = np.clip(np.floor(np.log2(np.maximum(base[0] / F32(params.scale), F32(1e-12))) - STRENGTH_LOW),
0, STRENGTH_BINS - 1).astype(int)
counts = np.zeros((STRENGTH_BINS, 3, HIST_BUCKETS), dtype=np.int64)
for c in range(3):
v = lap[c][valid] ** 2 / noise[c][valid]
k = np.floor((np.log2(np.maximum(v, F32(1e-30))) - HIST_LOW) * F32(HIST_BUCKETS / (HIST_HIGH - HIST_LOW)))
k = np.clip(k, 0, HIST_BUCKETS - 1).astype(int)
np.add.at(counts, (b[valid], c, k), 1)
return counts
def _median(values: np.ndarray) -> np.float32:
v = np.sort(values.astype(F32))
n = v.size
return v[n // 2] if n % 2 else (v[n // 2 - 1] + v[n // 2]) * F32(0.5)
def strength_resolve(counts: np.ndarray, params: Params) -> np.ndarray:
"""Section 5.1 step 4: histogram medians -> filled, spike-bounded, clamped and capped table."""
levels = counts.shape[0]
table = np.zeros((levels, STRENGTH_BINS, 3), dtype=F32)
width = F32((HIST_HIGH - HIST_LOW) / HIST_BUCKETS)
for c in range(3):
caps = params.strength_cap_luma if c == 0 else params.strength_cap_chroma
for level in range(levels):
measured = np.full(STRENGTH_BINS, -1.0, dtype=F32)
for b in range(STRENGTH_BINS):
h = counts[level, b, c]
n = int(h.sum())
if n < MIN_SAMPLES:
continue
target = F32(0.5) * F32(n)
cumulative = 0
for k in range(HIST_BUCKETS):
if cumulative + h[k] >= target:
f = (target - F32(cumulative)) / F32(h[k])
measured[b] = F32(2.0) ** (HIST_LOW + (F32(k) + f) * width) / CHI2_MEDIAN
break
cumulative += int(h[k])
known = np.flatnonzero(measured >= 0)
row = np.empty(STRENGTH_BINS, dtype=F32)
if known.size == 0:
if level == 0:
row[:] = 1.0
else:
# A level without samples continues the growth of the two levels above.
growth = F32(1.0)
if level >= 2:
upper, upper2 = table[level - 1, :, c], table[level - 2, :, c]
ratios = np.array([upper[b] / upper2[b] if upper2[b] > 0 else F32(1.0)
for b in range(STRENGTH_BINS)], dtype=F32)
growth = np.clip(_median(ratios), F32(1.0), MAX_GROWTH)
row = table[level - 1, :, c] * growth
else:
filled = np.empty(STRENGTH_BINS, dtype=F32)
for b in range(STRENGTH_BINS):
if measured[b] >= 0:
filled[b] = measured[b]
elif b <= known[0]:
filled[b] = measured[known[0]]
elif b >= known[-1]:
filled[b] = measured[known[-1]]
else:
hi = known[np.searchsorted(known, b)]
lo = known[np.searchsorted(known, b) - 1]
f = F32(b - lo) / F32(hi - lo)
filled[b] = measured[lo] + f * (measured[hi] - measured[lo])
# An isolated bin dominated by texture (high) or by few samples (either way) stands
# out from its neighbourhood.
for b in range(STRENGTH_BINS):
m = _median(filled[max(b - 2, 0):min(b + 3, STRENGTH_BINS)])
row[b] = min(max(filled[b], m / SPIKE), m * SPIKE)
cap = MAX_STRENGTH if caps is None else min(MAX_STRENGTH, F32(caps[level]))
table[level, :, c] = np.clip(row, F32(0), cap)
return table
def estimate_strength(g0: np.ndarray, gaussians: list[np.ndarray], params: Params) -> np.ndarray:
"""Section 5.1 table of the image; gaussians are the stored G_1 .. G_N. Every pass after the
first gates each level with the median luma strength of the previous pass."""
table = None
for _ in range(ESTIMATE_PASSES):
counts = np.stack([
strength_histogram(g0 if level == 0 else gaussians[level - 1], gaussians[level], level, params,
1.0 if table is None else float(_median(table[level, :, 0])))
for level in range(params.levels)
])
table = strength_resolve(counts, params)
return table
def _shift(image: np.ndarray, dy: int, dx: int) -> np.ndarray:
h, w = image.shape[-2:]
ys = mirror(np.arange(h) + dy, h)
xs = mirror(np.arange(w) + dx, w)
return image[..., ys[:, None], xs[None, :]]
def _structure(base_luma: np.ndarray, noise_luma: np.ndarray):
gx = 0.5 * (_shift(base_luma, 0, 1) - _shift(base_luma, 0, -1))
gy = 0.5 * (_shift(base_luma, 1, 0) - _shift(base_luma, -1, 0))
jxx = sum(_shift(gx * gx, dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)) / F32(9)
jxy = sum(_shift(gx * gy, dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)) / F32(9)
jyy = sum(_shift(gy * gy, dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)) / F32(9)
root = np.sqrt((jxx - jyy) ** 2 + 4 * jxy * jxy)
anisotropy = np.clip(root / (jxx + jyy + noise_luma + F32(1e-12)), 0, 1).astype(F32)
# Along the edge; a degenerate tensor (root == 0) has no orientation and is fixed at pi / 2,
# matching the shader (GLSL leaves atan(0, 0) undefined).
theta = np.where(root > 0, 0.5 * np.arctan2(2 * jxy, jxx - jyy) + F32(np.pi / 2), F32(np.pi / 2))
return anisotropy, np.cos(theta).astype(F32), np.sin(theta).astype(F32)
def _window_weights(lap_y, noise_y, anisotropy, cos_t, sin_t, outlier):
"""Yields (shifted index, weight) over the 5x5 window (section 6.1 steps 1-2)."""
r_par = F32(BASE_RADIUS) * (1 + anisotropy)
r_perp = F32(BASE_RADIUS) * (1 - F32(0.6) * anisotropy)
sigma = np.sqrt(noise_y)
for dy in range(-WINDOW_RADIUS, WINDOW_RADIUS + 1):
for dx in range(-WINDOW_RADIUS, WINDOW_RADIUS + 1):
d_par = dx * cos_t + dy * sin_t
d_perp = -dx * sin_t + dy * cos_t
spatial = np.exp(F32(-0.5) * (d_par * d_par / (r_par * r_par) + d_perp * d_perp / (r_perp * r_perp)))
diff = np.abs(_shift(lap_y, dy, dx) - lap_y)
limit = F32(outlier) * sigma
# min(1, d sigma / |diff|), except that the centre keeps weight 1 when sigma = 0.
huber = np.where(diff <= limit, F32(1), limit / np.maximum(diff, F32(1e-30)))
yield dy, dx, (spatial * huber).astype(F32)
def pilot(lap: np.ndarray, base: np.ndarray, noise: np.ndarray, level: int, params: Params) -> np.ndarray:
"""Luma pilot (s1, anisotropy, cos, sin), section 6.1 steps 1-3."""
lap_y, noise_y = lap[0], noise[0]
anisotropy, cos_t, sin_t = _structure(base[0], noise_y)
sigma = np.sqrt(noise_y)
centre = np.where(sigma > 0, _smoothstep(CENTRE_LOW, CENTRE_HIGH, np.abs(lap_y) / np.maximum(sigma, F32(1e-30))),
F32(1)).astype(F32)
num = np.zeros_like(lap_y)
den = np.zeros_like(lap_y)
for dy, dx, w in _window_weights(lap_y, noise_y, anisotropy, cos_t, sin_t, params.outlier[level]):
if dy == 0 and dx == 0:
w = (w * centre).astype(F32)
num += w * (_shift(lap_y, dy, dx) ** 2 - _shift(noise_y, dy, dx))
den += w
energy = np.maximum(num / den, 0)
alpha = F32(params.luma_alpha(level))
s1 = np.where(noise_y > 0, lap_y * energy / (energy + alpha * noise_y + F32(1e-30)), lap_y)
return f16(np.stack([s1, anisotropy, cos_t, sin_t]))
def _smoothstep(edge0: float, edge1: float, x: np.ndarray) -> np.ndarray:
t = np.clip((x - F32(edge0)) / F32(edge1 - edge0), 0, 1)
return t * t * (3 - 2 * t)
def final(lap: np.ndarray, base: np.ndarray, noise: np.ndarray, pilot_tex: np.ndarray | None, level: int,
params: Params) -> np.ndarray:
"""Denoised Gaussian level G~_l = base' + shrunk band (sections 6.1-6.2, 7.2-7.3)."""
lap_y, noise_y = lap[0], noise[0]
if level < params.luma_levels and params.luma_strength > 0:
s1, anisotropy, cos_t, sin_t = pilot_tex
num = np.zeros_like(lap_y)
den = np.zeros_like(lap_y)
for dy, dx, w in _window_weights(lap_y, noise_y, anisotropy, cos_t, sin_t, params.outlier[level]):
num += w * _shift(s1, dy, dx) ** 2
den += w
energy = num / den
alpha = F32(params.luma_alpha(level))
gamma = F32(1) if params.gamma is None else F32(params.gamma[level])
gain = energy / (energy + alpha * noise_y + F32(1e-30))
# Section 6.1: gain^gamma only where the gain shows detail; noise-only gains stay MMSE.
gain = gain + _smoothstep(GAMMA_LOW, GAMMA_HIGH, gain) * (gain ** gamma - gain)
shrunk = np.where(noise_y > 0, lap_y * gain, lap_y)
t = F32(params.luma_grain(level))
luma_band = shrunk + t * (lap_y - shrunk)
else:
luma_band = lap_y
chroma_band = lap[1:3]
if params.chroma_strength > 0:
gate_luma = pilot_tex[0] if pilot_tex is not None else lap_y
sum_l2 = sum(_shift(gate_luma * gate_luma, dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1))
sum_s2 = sum(_shift(noise_y, dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1))
luma_stat = np.where(sum_s2 > 0, F32(9) * sum_l2 / np.maximum(sum_s2, F32(1e-30)), F32(np.inf))
low, high = params.chroma_thresholds(params.gate_luma)
gate_y = _smoothstep(low, high, luma_stat)
s_cb, s_cr, s_x = noise[1], noise[2], noise[3]
det = s_cb * s_cr - s_x * s_x
cb, cr = lap[1], lap[2]
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 = np.maximum(gate_y, gate_c)
s = F32(min(params.chroma_strength, 1.0))
chroma_band = (s * gate + (1 - s)) * lap[1:3]
base_chroma = base[1:3]
if params.chroma_strength > 0 and level >= params.levels - params.bilateral_levels:
c_y = F32(params.bilateral_luma)
c_c = F32(params.bilateral_chroma * max(params.chroma_strength, 1.0) ** 2)
s_cb, s_cr, s_x = noise[1], noise[2], noise[3]
det = s_cb * s_cr - s_x * s_x
num = np.zeros_like(base_chroma)
den = np.zeros_like(lap_y)
for dy in range(-WINDOW_RADIUS, WINDOW_RADIUS + 1):
for dx in range(-WINDOW_RADIUS, WINDOW_RADIUS + 1):
spatial = F32(np.exp(-0.5 * (dx * dx + dy * dy) / BILATERAL_SIGMA ** 2))
dyl = _shift(base[0], dy, dx) - base[0]
luma_w = np.where(noise_y > 0, np.exp(-dyl * dyl / (2 * c_y * np.maximum(noise_y, F32(1e-30)))),
(dyl == 0).astype(F32))
dcb = _shift(base[1], dy, dx) - base[1]
dcr = _shift(base[2], dy, dx) - base[2]
d2 = np.where(det > 0, (s_cr * dcb * dcb - 2 * s_x * dcb * dcr + s_cb * dcr * dcr)
/ np.maximum(det, F32(1e-30)), F32(0))
w = (spatial * luma_w * np.exp(-d2 / (2 * c_c))).astype(F32)
num += w * _shift(base_chroma, dy, dx)
den += w
base_chroma = num / den
out = np.stack([base[0] + luma_band, base_chroma[0] + chroma_band[0], base_chroma[1] + chroma_band[1]])
return out.astype(F32)
def output(denoised0: np.ndarray, params: Params) -> np.ndarray:
"""Level-0 G~ -> camera RGB with LSC restored."""
x_wb = np.einsum("ij,jyx->iyx", RGB_FROM_YCC, denoised0) / F32(params.scale)
rgb = x_wb / params.white_balance.astype(F32)[:, None, None]
gains = lsc_gain(params.lsc, rgb.shape[1:], 0)
if gains is not None:
rgb = rgb * gains
return f16(rgb)
@dataclass
class Trace:
gaussians: list[np.ndarray] = field(default_factory=list) # G_1 .. G_N (stored f16)
bands: dict[int, tuple] = field(default_factory=dict) # level -> (L, base, noise)
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
output: np.ndarray | None = None
def _windows(image: np.ndarray, radius: int) -> np.ndarray:
"""[H, W, 2r+1, 2r+1] neighbourhoods, mirrored without edge repetition."""
side = 2 * radius + 1
return np.lib.stride_tricks.sliding_window_view(np.pad(image, radius, mode="reflect"), (side, side))
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)."""
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)
def run(rgb: np.ndarray, params: Params) -> Trace:
trace = Trace()
sizes = level_sizes(rgb.shape[1], rgb.shape[2], params.levels)
g0 = analyze0(rgb, params)
gaussians = [g0]
for level in range(params.levels):
gaussians.append(f16(down(gaussians[-1], sizes[level + 1])))
trace.gaussians = gaussians[1:]
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:
trace.prefilter = prefilter(g0, gaussians[1], params)
g0 = g0.copy()
g0[0] = g0[0] + trace.prefilter
denoised = gaussians[params.levels]
for level in range(params.levels - 1, -1, -1):
fine = g0 if level == 0 else gaussians[level]
lap, base, noise = band(fine, gaussians[level + 1], denoised, level, params)
trace.bands[level] = (lap, base, noise)
pilot_tex = None
if level < params.luma_levels and params.luma_strength > 0:
pilot_tex = pilot(lap, base, noise, level, params)
trace.pilots[level] = pilot_tex
result = final(lap, base, noise, pilot_tex, level, params)
denoised = f16(result) if level > 0 else result
trace.denoised[level] = denoised
trace.output = output(denoised, params)
return trace
+161
View File
@@ -0,0 +1,161 @@
"""Measured denoise strength per pyramid level × image SNR (docs/photon-multiscale-denoise.md
section 5.1): the offline reference the per-image estimate is validated against.
For every denoise-input dump of a pipeline the working-domain pyramid is built and each Laplacian
sample of a flat region is divided by its model standard deviation (section 2.1, from the dump's
own params). The robust variance of these normalized samples is measured / model, the strength the
denoiser should apply. Each dump yields one value per level, at its image SNR (section 5.1, MGC
FinishRaw's definition): S / sqrt(m_s s_G S + m_r r_G), S the mean green signal measured like
MGC EstimateSnr (central 3/4, every 8th row, squared mean of sqrt, LSC removed), r_G / s_G the
green profile and m the nominal merge ratios. The table columns are MGC's tuning nodes 5 / 20 / 40,
interpolated across the dumps of a pipeline in ln SNR and held at the nearest dump outside their
range, so covering all three nodes needs captures near each (high, middle and low ISO).
Flat: the coarse base's luma gradient across one level-l pixel is below half the model sigma. No
gate on the band itself: a bound in model sigmas would discard exactly the noise that exceeds the
model and bias the result low. The median absolute deviation tolerates the remaining texture.
Usage:
uv run --with numpy python -I tools/photon_denoise/strength_map.py <dump stem or .json> ...
Prints the table and writes photon_denoise_strength.json (pipeline -> snr, luma, chroma).
"""
from __future__ import annotations
import json
from dataclasses import replace
import sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import compare_passes as cp # noqa: E402
import photon_denoise as pd # noqa: E402
F32 = np.float32
LEVELS = 5
SNR_NODES = (5.0, 20.0, 40.0)
NODES = len(SNR_NODES)
MAX_SAMPLES = 400_000
MIN_SAMPLES = 100
def robust_variance(z: np.ndarray) -> float:
return float((1.4826 * np.median(np.abs(z - np.median(z)))) ** 2)
def image_snr(rgb: np.ndarray, params: pd.Params) -> tuple[float, float]:
"""(S, image SNR) as section 5.1 / MGC EstimateSnr."""
gains = pd.lsc_gain(params.lsc, rgb.shape[1:], 0)
green = rgb[1] if gains is None else rgb[1] / gains[1]
h, w = green.shape
crop = green[(h // 8) & -2:((h * 7) // 8) & -2:8, (w // 8) & -4:((w * 7) // 8) & -4]
signal = float(np.mean(np.sqrt(np.maximum(crop.astype(np.float64), 0.0))) ** 2)
variance = params.merge_shot * float(params.shot[1]) * signal + params.merge_read * float(params.read[1])
return signal, (signal / np.sqrt(variance) if variance > 0 else 0.0)
def samples(stem: Path, rng: np.random.Generator) -> tuple[float, float, list[dict[str, np.ndarray]]]:
"""(S, image SNR, per level: normalized luma / chroma band samples of flat pixels)."""
meta = json.loads(stem.with_suffix(".json").read_text())
raw = np.fromfile(stem.with_suffix(".rgba16f"), dtype="<f2").reshape(meta["height"], meta["width"], 4)
rgb = np.moveaxis(raw[..., :3].astype(F32), -1, 0)
# Measure against the section 2.1 model alone: dumps from builds that already apply a strength
# map carry it in their params.
params = replace(cp.params_from_json(json.loads(Path(f"{stem}.params.json").read_text())),
strength_table=None, strength_cap_luma=None, strength_cap_chroma=None)
signal, snr_image = image_snr(rgb, params)
# Unexposed areas (black borders outside the default crop) hold zeros, not noise.
dead = np.any(rgb <= 0, axis=0)
gaussians = [pd.analyze0(rgb, params)]
for _ in range(LEVELS):
shape = gaussians[-1].shape[1:]
gaussians.append(pd.down(gaussians[-1], ((shape[0] + 1) // 2, (shape[1] + 1) // 2)))
out = []
for level in range(LEVELS):
fine, coarse = gaussians[level], gaussians[level + 1]
lap, base, noise = pd.band(fine, coarse, coarse, level, params)
cov, _ = pd.point_covariance(base, params, level)
snr = base[0] / np.sqrt(np.maximum(cov[0, 0], 1e-30))
gy, gx = np.gradient(base[0])
sigma = np.sqrt(np.maximum(noise[0], 1e-30))
# A level-l pixel is excluded when any input pixel within 8 level-l pixels is dead.
step = 2 ** level
h, w = lap.shape[1:]
block = np.zeros((h, w), dtype=bool)
padded = np.pad(dead, ((0, h * step - dead.shape[0]), (0, w * step - dead.shape[1])))
block |= padded.reshape(h, step, w, step).any(axis=(1, 3))
for _ in range(8):
block = block | np.roll(block, 1, 0) | np.roll(block, -1, 0) | np.roll(block, 1, 1) | np.roll(block, -1, 1)
flat = ((np.hypot(gx, gy) < 0.5 * sigma) & ~block & (noise[0] > 0)
& (noise[1] > 0) & (snr > 0))
idx = np.flatnonzero(flat)
if idx.size > MAX_SAMPLES:
idx = rng.choice(idx, MAX_SAMPLES, replace=False)
z_luma = (lap[0] / sigma).ravel()[idx]
z_cb = (lap[1] / np.sqrt(np.maximum(noise[1], 1e-30))).ravel()[idx]
z_cr = (lap[2] / np.sqrt(np.maximum(noise[2], 1e-30))).ravel()[idx]
out.append({"snr": snr.ravel()[idx], "luma": z_luma, "chroma": np.concatenate([z_cb, z_cr]),
"chroma_snr": np.concatenate([snr.ravel()[idx]] * 2)})
return signal, snr_image, out
def measure(stems: list[Path]) -> dict:
rng = np.random.default_rng(1)
points = [] # (image SNR, luma [LEVELS], chroma [LEVELS], counts [LEVELS], stem, S)
for stem in stems:
signal, snr, levels = samples(stem, rng)
luma, chroma, counts = [], [], []
for d in levels:
n = d["luma"].size
luma.append(robust_variance(d["luma"]) if n >= MIN_SAMPLES else float("nan"))
chroma.append(robust_variance(d["chroma"]) if n >= MIN_SAMPLES else float("nan"))
counts.append(n)
points.append((snr, luma, chroma, counts, stem.name, signal))
points.sort(key=lambda p: p[0])
x = np.log([max(p[0], 1e-6) for p in points])
table = {"snr": list(SNR_NODES), "luma": [], "chroma": [], "dumps": [
{"stem": p[4], "signal": p[5], "imageSnr": p[0], "luma": p[1], "chroma": p[2], "count": p[3]}
for p in points]}
# A level a dump has too few flat samples for is left out of that level's interpolation; a
# level no dump measures takes the level above.
for key, index in (("luma", 1), ("chroma", 2)):
for level in range(LEVELS):
values = np.array([p[index][level] for p in points])
known = ~np.isnan(values)
if known.any():
table[key].append([float(np.interp(np.log(node), x[known], values[known])) for node in SNR_NODES])
else:
table[key].append(list(table[key][level - 1]))
return table
def main() -> int:
stems = [Path(a[:-5] if a.endswith(".json") else a) for a in sys.argv[1:]]
if not stems:
print(__doc__)
return 2
pipelines: dict[str, list[Path]] = {}
for stem in stems:
pipeline = json.loads(stem.with_suffix(".json").read_text())["pipeline"]
pipelines.setdefault(pipeline, []).append(stem)
result = {}
for pipeline, group in pipelines.items():
table = measure(group)
result[pipeline] = table
print(f"{pipeline} ({len(group)} dumps)")
for d in table["dumps"]:
print(f" {d['stem']}: S {d['signal']:.4f} image SNR {d['imageSnr']:.1f}")
print(" luma " + " ".join(f"{v:7.3f}" for v in d["luma"]) + " samples " + " ".join(map(str, d["count"])))
print(" chroma " + " ".join(f"{v:7.3f}" for v in d["chroma"]))
for key in ("luma", "chroma"):
print(f" {key} at SNR " + " / ".join(f"{s:g}" for s in table["snr"]))
for level in range(LEVELS):
print(f" L{level} " + " ".join(f"{v:7.3f}" for v in table[key][level]))
Path("photon_denoise_strength.json").write_text(json.dumps(result, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+338
View File
@@ -0,0 +1,338 @@
"""Offline tuning of the Photon denoiser (docs/photon-multiscale-denoise.md sections 6.4, 7.4, 12.2).
Clean reference: a base-ISO multi-frame capture of a static scene (tripod), binned 2x2.
Noisy inputs: captures of the same scene at the tuning ISO nodes, through the actual pipeline,
dumped at the denoiser input (debug.photon.denoise.dump: <stem>.{json,rgba16f,params.json}).
The denoiser output is binned 2x2 like the reference, matched in per-channel exposure, sent
through the fixed reference render (image_metrics.render) and compared.
Objective: mean sRGB PSNR over all crops of a node. Also reported: luma PSNR / SSIM (BT.601
luma, as DnCNN sees it), CIEDE2000, linear PSNR, the noisy input and the DnCNN luma baseline.
Search: coordinate descent over per-level luma parameters (α_l, t_l, d_l) and the chroma
parameters (gate thresholds, joint bilateral), starting from PhotonDenoiseTuning defaults.
Usage:
uv run --with numpy --with ai-edge-litert python -I tools/photon_denoise/tune.py cases.json [out.json]
uv run --with numpy --with ai-edge-litert python -I tools/photon_denoise/tune.py --self-test
cases.json: [{"clean": "<stem>", "noisy": ["<stem>", ...]}, ...]
"""
from __future__ import annotations
import copy
import json
import sys
from dataclasses import dataclass, field, replace
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import image_metrics as im # noqa: E402
import model_error # noqa: E402
import noise_model # noqa: E402
import photon_denoise as pd # noqa: E402
F32 = np.float32
CROP = 384
CROPS_PER_IMAGE = 4
ROUNDS = 2
DNCNN_MODEL = Path(__file__).resolve().parents[2] / "app/src/main/assets/dncnn.tflite"
ALPHA = (0.6, 0.8, 1.0, 1.25, 1.6, 2.0)
GRAIN = (0.0, 0.1, 0.2, 0.3, 0.45)
OUTLIER = (1.5, 2.5, 4.0)
GATE_SCALE = (0.5, 1.0, 2.0, 4.0)
BILATERAL_C = (1.0, 4.0, 16.0)
BILATERAL_LEVELS = (2, 3, 4)
GATE_LUMA = (16.919, 27.877)
GATE_CHROMA = (5.991, 13.816)
@dataclass
class Crop:
noisy: np.ndarray # [3, CROP, CROP] camera RGB at full resolution
clean: np.ndarray # [3, CROP/2, CROP/2] binned clean camera RGB
gain: np.ndarray # per-channel exposure match noisy -> clean
params: pd.Params # with the crop's LSC origin
white_balance: np.ndarray
exposure: float
@dataclass
class Node:
pipeline: str
n: float # §5 noise coordinate
crops: list[Crop] = field(default_factory=list)
def bin2(x: np.ndarray) -> np.ndarray:
h, w = x.shape[1] // 2 * 2, x.shape[2] // 2 * 2
x = x[:, :h, :w]
return 0.25 * (x[:, 0::2, 0::2] + x[:, 1::2, 0::2] + x[:, 0::2, 1::2] + x[:, 1::2, 1::2])
def noise_coordinate(params: pd.Params) -> float:
"""§5: n = sqrt(m v_Y(0.18)) / 0.18 from the profile."""
wb = np.asarray(params.white_balance, dtype=np.float64)
merge = noise_model.MergeRatio(float(params.merge_read), float(params.merge_shot))
cov = noise_model.working_point_covariance(params.read, params.shot, 0.18 / wb, wb, 1.0, merge)
return float(np.sqrt(cov[0, 0]) / 0.18)
def exposure_gain(noisy_binned: np.ndarray, clean: np.ndarray) -> np.ndarray:
"""Per-channel least-squares gain on unclipped pixels (ISO nodes differ in exposure)."""
gains = np.ones(3, dtype=F32)
for c in range(3):
valid = (clean[c] > 0.01) & (clean[c] < 0.9) & (noisy_binned[c] < 0.9)
gains[c] = float(np.sum(noisy_binned[c][valid] * clean[c][valid]) / np.sum(noisy_binned[c][valid] ** 2))
return gains
def crop_windows(height: int, width: int) -> list[tuple[int, int]]:
"""Deterministic grid of crop origins (even, inside the image)."""
side = int(np.ceil(np.sqrt(CROPS_PER_IMAGE)))
ys = np.linspace(0, height - CROP, side) if height > CROP else [0]
xs = np.linspace(0, width - CROP, side) if width > CROP else [0]
return [(int(y) // 2 * 2, int(x) // 2 * 2) for y in ys for x in xs][:CROPS_PER_IMAGE]
def with_origin(params: pd.Params, x: int, y: int) -> pd.Params:
"""Places a crop at (x, y) of the full frame for the whole-image LSC and merge maps."""
def shift(placed):
return None if placed is None else replace(placed, origin=(placed.origin[0] + x, placed.origin[1] + y))
return replace(params, lsc=shift(params.lsc), merge_map=shift(params.merge_map))
def make_crops(noisy_rgb: np.ndarray, clean_binned: np.ndarray, params: pd.Params,
white_balance: np.ndarray) -> list[Crop]:
gain = exposure_gain(bin2(noisy_rgb), clean_binned)
exposure = im.exposure_for(clean_binned, white_balance)
crops = []
for y, x in crop_windows(noisy_rgb.shape[1], noisy_rgb.shape[2]):
crops.append(Crop(
noisy=noisy_rgb[:, y:y + CROP, x:x + CROP],
clean=clean_binned[:, y // 2:(y + CROP) // 2, x // 2:(x + CROP) // 2],
gain=gain,
params=with_origin(params, x, y),
white_balance=white_balance,
exposure=exposure,
))
return crops
def load_nodes(cases_path: str) -> list[Node]:
nodes: dict[tuple[str, float], Node] = {}
for case in json.loads(Path(cases_path).read_text()):
clean = model_error.load(case["clean"])
clean_binned = bin2(clean.rgb)
for noisy_path in case["noisy"]:
noisy = model_error.load(noisy_path)
n = noise_coordinate(noisy.params)
key = (noisy.meta["pipeline"], round(n, 4))
node = nodes.setdefault(key, Node(noisy.meta["pipeline"], n))
node.crops += make_crops(noisy.rgb, clean_binned, noisy.params, clean.params.white_balance)
return sorted(nodes.values(), key=lambda node: (node.pipeline, node.n))
# ----------------------------------------------------------------- evaluation
@dataclass
class Tuning:
alpha: list[float]
grain: list[float]
outlier: list[float]
gate_luma_scale: float = 1.0
gate_chroma_scale: float = 1.0
bilateral_levels: int = 3
bilateral_luma: float = 4.0
bilateral_chroma: float = 4.0
@staticmethod
def defaults(levels: int) -> "Tuning":
alpha = [1.0, 1.0, 1.0, 1.2, 1.2, 1.2, 1.2][:levels]
grain = [0.0, 0.20, 0.15, 0.10, 0.10, 0.10, 0.10][:levels]
return Tuning(alpha, grain, [2.5] * levels)
def apply(self, params: pd.Params) -> pd.Params:
n = params.levels
return replace(
params,
alpha=np.asarray(self.alpha[:n], dtype=F32),
grain=np.asarray(self.grain[:n], dtype=F32),
outlier=np.asarray(self.outlier[:n], dtype=F32),
gate_luma=(GATE_LUMA[0] * self.gate_luma_scale, GATE_LUMA[1] * self.gate_luma_scale),
gate_chroma=(GATE_CHROMA[0] * self.gate_chroma_scale, GATE_CHROMA[1] * self.gate_chroma_scale),
bilateral_levels=self.bilateral_levels,
bilateral_luma=self.bilateral_luma,
bilateral_chroma=self.bilateral_chroma,
luma_strength=1.0,
chroma_strength=1.0,
)
def to_json(self) -> dict:
return {
"alpha": self.alpha, "grain": self.grain, "outlier": self.outlier,
"gateLuma": [GATE_LUMA[0] * self.gate_luma_scale, GATE_LUMA[1] * self.gate_luma_scale],
"gateChroma": [GATE_CHROMA[0] * self.gate_chroma_scale, GATE_CHROMA[1] * self.gate_chroma_scale],
"bilateralLevels": self.bilateral_levels,
"bilateralLuma": self.bilateral_luma,
"bilateralChroma": self.bilateral_chroma,
}
@dataclass
class Score:
psnr: float
luma_psnr: float
luma_ssim: float
delta_e: float
linear_psnr: float
def score(outputs: list[np.ndarray], crops: list[Crop]) -> Score:
values = []
for out, crop in zip(outputs, crops):
test = bin2(out) * crop.gain[:, None, None]
a = im.render(test, crop.white_balance, crop.exposure)
b = im.render(crop.clean, crop.white_balance, crop.exposure)
lin = test * np.asarray(crop.white_balance)[:, None, None] * crop.exposure
ref = crop.clean * np.asarray(crop.white_balance)[:, None, None] * crop.exposure
values.append((im.psnr(a, b), im.psnr(im.dncnn_luma(a), im.dncnn_luma(b)),
im.ssim(im.dncnn_luma(a), im.dncnn_luma(b)), im.ciede2000(a, b),
im.psnr(np.clip(lin, 0, 1), np.clip(ref, 0, 1))))
return Score(*np.mean(np.array(values), axis=0).tolist())
def run_denoiser(crops: list[Crop], tuning: Tuning) -> list[np.ndarray]:
return [pd.run(crop.noisy, tuning.apply(crop.params)).output for crop in crops]
def dncnn_baseline(crops: list[Crop], model: im.DnCNN) -> float:
"""DnCNN luma PSNR: denoises the rendered noisy luma (the app's 8-bit input)."""
values = []
for crop in crops:
full_render = im.render(crop.noisy * crop.gain[:, None, None], crop.white_balance, crop.exposure)
denoised = model.denoise(im.dncnn_luma(full_render))
binned = bin2(denoised[None])[0]
reference = im.dncnn_luma(im.render(crop.clean, crop.white_balance, crop.exposure))
values.append(im.psnr(binned, reference))
return float(np.mean(values))
def search(node: Node, levels: int, rounds: int = ROUNDS, grids: dict | None = None) -> tuple[Tuning, Score, Score]:
"""Coordinate descent on the node's crops; returns (tuning, default score, tuned score)."""
grids = grids or {}
best = Tuning.defaults(levels)
default_score = score(run_denoiser(node.crops, best), node.crops)
best_score = default_score
def attempt(candidate: Tuning) -> None:
nonlocal best, best_score
result = score(run_denoiser(node.crops, candidate), node.crops)
if result.psnr > best_score.psnr:
best, best_score = candidate, result
luma_levels = min(levels, node.crops[0].params.luma_levels)
for _ in range(rounds):
for level in range(luma_levels):
for name, values in (("alpha", grids.get("alpha", ALPHA)), ("grain", grids.get("grain", GRAIN)),
("outlier", grids.get("outlier", OUTLIER))):
base = best
for value in values:
candidate = copy.deepcopy(base)
getattr(candidate, name)[level] = value
attempt(candidate)
for name, values in (("gate_luma_scale", grids.get("gate", GATE_SCALE)),
("gate_chroma_scale", grids.get("gate", GATE_SCALE)),
("bilateral_levels", grids.get("bilateral_levels", BILATERAL_LEVELS)),
("bilateral_luma", grids.get("bilateral_c", BILATERAL_C)),
("bilateral_chroma", grids.get("bilateral_c", BILATERAL_C))):
base = best
for value in values:
attempt(replace(copy.deepcopy(base), **{name: value}))
return best, default_score, best_score
def noisy_score(crops: list[Crop]) -> Score:
return score([crop.noisy for crop in crops], crops)
def tune(nodes: list[Node], rounds: int = ROUNDS, grids: dict | None = None, dncnn: bool = True) -> dict:
model = im.DnCNN(str(DNCNN_MODEL)) if dncnn and DNCNN_MODEL.exists() else None
table: dict[str, dict] = {}
for node in nodes:
levels = node.crops[0].params.levels
tuning, default, tuned = search(node, levels, rounds, grids)
noisy = noisy_score(node.crops)
baseline = dncnn_baseline(node.crops, model) if model else float("nan")
print(f"{node.pipeline} n={node.n:.4f} crops={len(node.crops)}: sRGB PSNR noisy {noisy.psnr:.2f} "
f"default {default.psnr:.2f} tuned {tuned.psnr:.2f} | luma PSNR tuned {tuned.luma_psnr:.2f} "
f"DnCNN {baseline:.2f} | SSIM {tuned.luma_ssim:.4f} ΔE00 {tuned.delta_e:.3f} "
f"(noisy {noisy.delta_e:.3f})")
entry = tuning.to_json()
entry.update({"n": node.n, "psnrNoisy": noisy.psnr, "psnrDefault": default.psnr, "psnrTuned": tuned.psnr,
"lumaPsnr": tuned.luma_psnr, "lumaSsim": tuned.luma_ssim, "deltaE2000": tuned.delta_e,
"linearPsnr": tuned.linear_psnr, "dncnnLumaPsnr": baseline})
table.setdefault(node.pipeline, {"nodes": []})["nodes"].append(entry)
return table
# ------------------------------------------------------------------ self-test
def self_test() -> bool:
"""Synthetic clean scene, profile noise passed through a demosaic-like correlation (so the
white-noise model is wrong by design). Tuning must not lose to the defaults and both must
beat the noisy input clearly."""
rng = np.random.default_rng(5)
h, w = 768, 768
yy, xx = np.mgrid[0:h, 0:w]
wb = np.array([2.0, 1.0, 1.6], dtype=F32)
luma = np.exp2(-7.0 + 6.5 * xx / w) * (0.85 + 0.15 * np.sin(yy / 37.0))
texture = 1 + 0.25 * np.sin(xx / 4.3) * np.sin(yy / 5.1) + 0.2 * ((xx // 48 + yy // 48) % 2)
chroma = 0.15 * np.sin(yy / 90.0)
clean = np.stack([luma * (1 + chroma), luma, luma * (1 - chroma)]) * texture[None] / wb[:, None, None]
clean = clean.astype(F32)
read = np.array([4e-5, 3e-5, 5e-5], dtype=F32)
shot = np.array([8e-4, 6e-4, 9e-4], dtype=F32)
noise = np.sqrt(read[:, None, None] + shot[:, None, None] * clean) * rng.standard_normal(clean.shape).astype(F32)
taps = np.array([0.25, 0.5, 0.25], dtype=F32)
correlated = np.stack([pd.f16(np.einsum("t,tyx->yx", taps, np.stack([np.roll(c, s, 1) for s in (-1, 0, 1)])))
for c in noise]) * np.sqrt(8 / 3) # unit gain on variance after the blur pair
noisy = pd.f16(clean + correlated)
levels = 5
kappa = noise_model.Kappa0.build(levels, levels)
params = pd.Params(4096.0, wb, read, shot, 1.0, 1.0, np.ones((levels, 3), dtype=F32), kappa.luma.astype(F32),
kappa.chroma.astype(F32), levels, levels, np.ones(levels, dtype=F32),
np.full(levels, 0.2, dtype=F32), np.full(levels, 2.5, dtype=F32), GATE_LUMA, GATE_CHROMA,
3, 4.0, 4.0, 1.0, 1.0, None)
global CROP, CROPS_PER_IMAGE
CROP, CROPS_PER_IMAGE = 256, 4
node = Node("SELF_TEST", noise_coordinate(params))
node.crops = make_crops(noisy, bin2(clean), params, wb)
grids = {"alpha": (0.6, 1.0, 1.6), "grain": (0.1, 0.3), "outlier": (2.5,), "gate": (1.0, 2.0),
"bilateral_levels": (3,), "bilateral_c": (4.0,)}
table = tune([node], rounds=1, grids=grids, dncnn=True)
entry = table["SELF_TEST"]["nodes"][0]
ok = entry["psnrTuned"] >= entry["psnrDefault"] and entry["psnrDefault"] > entry["psnrNoisy"] + 3.0
json.dumps(table) # the table must serialise
print(f"self-test: noisy {entry['psnrNoisy']:.2f} default {entry['psnrDefault']:.2f} "
f"tuned {entry['psnrTuned']:.2f} DnCNN luma {entry['dncnnLumaPsnr']:.2f} -> {'PASS' if ok else 'FAIL'}")
return ok
def main() -> int:
if sys.argv[1:] == ["--self-test"]:
return 0 if self_test() else 1
if not sys.argv[1:]:
print(__doc__)
return 2
table = tune(load_nodes(sys.argv[1]))
output = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("photon_denoise_tuning.json")
output.write_text(json.dumps(table, indent=2))
print(f"tuning table written to {output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+122
View File
@@ -0,0 +1,122 @@
"""Gate of the section 2.2 per-pixel merge variance map (docs/photon-multiscale-denoise.md, step 9).
Synthetic merge: N frames of a flat signal with per-frame exposure ratios, global weights and
RAW/4 acceptance maps (a moving object rejected in most frames, soft edges). Each realization is
merged as y = sum w_i y_i / sum w_i with w_i(p) = g_i a_i(p), the acceptance sampled bilinearly at
the pixel, as the merge shaders do. The map is built by a numpy mirror of PhotonMergeNoise's two
kernels (RAW/4 sums, RAW/32 mean of ratios) and compared, per RAW/32 cell, with the measured
variance of the merged pixels. The signal is flat, so a cell's mean variance is linear in m and the
cell mean is the exact prediction.
Usage: uv run --with numpy python -I tools/photon_denoise/validate_merge_map.py
"""
from __future__ import annotations
import numpy as np
GRID_STEP = 4
MAP_CELLS = 8
TOLERANCE = 0.03
def bilinear(texture: np.ndarray, u: np.ndarray, v: np.ndarray) -> np.ndarray:
"""GL LINEAR sampling with clamp to edge at normalized (u, v)."""
h, w = texture.shape
x = np.clip(u * w - 0.5, 0, w - 1)
y = np.clip(v * h - 0.5, 0, h - 1)
x0, y0 = np.floor(x).astype(int), np.floor(y).astype(int)
x1, y1 = np.minimum(x0 + 1, w - 1), np.minimum(y0 + 1, h - 1)
fx, fy = x - x0, y - y0
top = texture[y0, x0] * (1 - fx) + texture[y0, x1] * fx
bottom = texture[y1, x0] * (1 - fx) + texture[y1, x1] * fx
return top * (1 - fy) + bottom * fy
def merge_map(acceptance: list[np.ndarray | None], weights, read_ratios, shot_ratios, width, height,
output_scale: float) -> np.ndarray:
"""Mirror of PhotonMergeNoise ACCUMULATE + REDUCE: [map_h, map_w, 2] of (m_r, m_s)."""
gw, gh = -(-width // GRID_STEP), -(-height // GRID_STEP)
gy, gx = np.mgrid[0:gh, 0:gw]
u, v = (gx + 0.5) / gw, (gy + 0.5) / gh
sums = np.zeros((3, gh, gw))
for a_tex, g, rr, rs in zip(acceptance, weights, read_ratios, shot_ratios):
a = np.ones((gh, gw)) if a_tex is None else np.clip(bilinear(a_tex, u, v), 0, 1)
w = g * a
sums += np.stack([w, w * w * rr, w * w * rs])
ratio = np.where(sums[0] > 0, sums[1:] / np.maximum(sums[0], 1e-30) ** 2, 1.0)
mw, mh = -(-gw // MAP_CELLS), -(-gh // MAP_CELLS)
out = np.zeros((mh, mw, 2))
for j in range(mh):
for i in range(mw):
block = ratio[:, j * MAP_CELLS:(j + 1) * MAP_CELLS, i * MAP_CELLS:(i + 1) * MAP_CELLS]
out[j, i] = block.reshape(2, -1).mean(axis=1)
return out * np.array([output_scale ** 2, output_scale])
def main() -> int:
rng = np.random.default_rng(5)
width, height = 512, 384
frames = 6
signal = 0.2
read, shot = 4e-5, 6e-4
exposure = np.array([1.0, 1.0, 0.8, 1.25, 1.0, 0.9]) # frame exposure scale to reference
weights = np.array([1.0, 0.9, 0.7, 1.0, 0.8, 0.6]) # global weights g_i
read_ratios = exposure ** 2 # read variance scales with gain²
shot_ratios = exposure
output_scale = 0.8
gw, gh = width // GRID_STEP, height // GRID_STEP
yy, xx = np.mgrid[0:gh, 0:gw]
acceptance: list[np.ndarray | None] = [None] # reference: no weight texture
for i in range(1, frames):
# Moving disc: rejected in this frame along its path, soft 6-cell edge.
cx, cy = gw * (0.3 + 0.08 * i), gh * 0.5
d = np.hypot(xx - cx, yy - cy)
a = np.clip((d - 14) / 6, 0, 1)
# A region rejected in every alternate frame: only the reference remains there.
a = np.minimum(a, np.clip((np.hypot(xx - gw * 0.15, yy - gh * 0.25) - 10) / 6, 0, 1))
a = a * (0.9 if i % 2 else 1.0) # partial acceptance elsewhere
acceptance.append(a.astype(np.float32))
predicted = merge_map(acceptance, weights, read_ratios, shot_ratios, width, height, output_scale)
py, px = np.mgrid[0:height, 0:width]
u, v = (px + 0.5) / width, (py + 0.5) / height
w = np.stack([weights[i] * (np.ones((height, width)) if acceptance[i] is None
else np.clip(bilinear(acceptance[i], u, v), 0, 1)) for i in range(frames)])
total = w.sum(axis=0)
total = np.where(total > 0, total, 1.0)
realizations = 160
acc = np.zeros((height, width))
for _ in range(realizations):
# Frame i at reference exposure: read variance read·ρ_r, shot variance shot·ρ_s·signal.
noise = rng.standard_normal((frames, height, width)) * np.sqrt(
read * read_ratios[:, None, None] + shot * shot_ratios[:, None, None] * signal)
merged = output_scale * (w * noise).sum(axis=0) / total
acc += merged ** 2
measured = acc / realizations
cell = GRID_STEP * MAP_CELLS
worst = 0.0
rows = []
for j in range(predicted.shape[0]):
for i in range(predicted.shape[1]):
block = measured[j * cell:(j + 1) * cell, i * cell:(i + 1) * cell]
# The output scale e applies to the signal too: shot variance at the output is
# e·m_s·shot·(output signal) with output signal = e·signal, read e²·m_r·read.
model = predicted[j, i, 0] * read + predicted[j, i, 1] * shot * (output_scale * signal)
ratio = block.mean() / model
worst = max(worst, abs(ratio - 1))
rows.append(ratio)
ratios = np.array(rows)
nominal = (weights ** 2 * read_ratios).sum() / weights.sum() ** 2
print(f"map {predicted.shape[1]}x{predicted.shape[0]} m_r range {predicted[..., 0].min():.4f}.."
f"{predicted[..., 0].max():.4f} (nominal {nominal * output_scale ** 2:.4f}, "
f"single frame {output_scale ** 2:.4f})")
print(f"measured/model per cell: mean {ratios.mean():.4f} min {ratios.min():.4f} max {ratios.max():.4f}")
ok = worst <= TOLERANCE
print(f"worst deviation {worst * 100:.2f}% (tolerance {TOLERANCE * 100:.0f}%): {'PASS' if ok else 'FAIL'}")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())
+102
View File
@@ -0,0 +1,102 @@
"""Gate for implementation step 1 (docs/photon-multiscale-denoise.md section 16).
White noise satisfies the profile x white-noise model exactly, so this checks the
implementation: independent per-channel Poisson-Gaussian noise (profile coefficients),
optionally merged from frames with unequal weights and exposure ratios, optionally scaled
by residual ratios, goes through white balance, the working YCbCr matrix and both pyramids.
Every level and phase is compared with level_noise(). Pass: Y/Cb/Cr variance ratios and
the Cb-Cr covariance (correlation units) within 0.03.
Run: uv run --with numpy python -I tools/photon_denoise/validate_model.py
"""
from __future__ import annotations
import sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import noise_model as nm # noqa: E402
from validate_propagation import laplacian_levels # noqa: E402
SIZE = 2048
LEVELS = 5
REALIZATIONS = 6
TOLERANCE = 0.03
SCALE = 4096.0
WHITE_BALANCE = np.array([2.0, 1.0, 1.6])
READ = np.array([4.0e-6, 3.0e-6, 5.0e-6])
SHOT = np.array([2.0e-4, 1.5e-4, 2.5e-4])
CASES = {
"single": dict(weights=np.array([1.0]), read_ratios=np.array([1.0]), shot_ratios=np.array([1.0]),
residual=None),
"merge4": dict(weights=np.array([1.0, 0.8, 0.6, 0.4]), read_ratios=np.array([1.0, 1.2, 0.9, 1.5]),
shot_ratios=np.array([1.0, 1.1, 0.95, 1.3]), residual=None),
"residual": dict(weights=np.array([1.0]), read_ratios=np.array([1.0]), shot_ratios=np.array([1.0]),
residual=np.array([0.5, 0.3, 0.2])),
}
SIGNALS = (np.array([0.02, 0.05, 0.03]), np.array([0.3, 0.2, 0.12]))
def simulate(rng: np.random.Generator, mu: np.ndarray, case: dict) -> np.ndarray:
"""Merged camera-RGB noise field [3, H, W] (signal removed: it carries no noise)."""
weights = case["weights"]
merged = np.zeros((3, SIZE, SIZE))
for w, rr, sr in zip(weights, case["read_ratios"], case["shot_ratios"]):
variance = READ * rr + SHOT * sr * mu
merged += w * np.sqrt(variance)[:, None, None] * rng.standard_normal((3, SIZE, SIZE))
return merged / weights.sum()
def main() -> int:
rng = np.random.default_rng(20261028)
kappa0 = nm.Kappa0.build(LEVELS, LEVELS)
worst = 0.0
for name, case in CASES.items():
merge = nm.MergeRatio.of(case["weights"], case["read_ratios"], case["shot_ratios"])
for mu in SIGNALS:
point = nm.working_point_covariance(READ, SHOT, mu, WHITE_BALANCE, SCALE, merge)
sums = np.zeros((LEVELS, 4, 3, 3))
for _ in range(REALIZATIONS):
noise = simulate(rng, mu, case)
ycc = np.einsum("ij,jyx->iyx", SCALE * nm.YCC_FROM_RGB @ np.diag(WHITE_BALANCE), noise)
if case["residual"] is not None:
ycc *= np.sqrt(case["residual"])[:, None, None]
luma = laplacian_levels(ycc[0], nm.LUMA_TAPS, LEVELS)
cb = laplacian_levels(ycc[1], nm.CHROMA_TAPS, LEVELS)
cr = laplacian_levels(ycc[2], nm.CHROMA_TAPS, LEVELS)
for level in range(LEVELS):
for phase, (py, px) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))):
y = luma[level][py::2, px::2].ravel()
b = cb[level][py::2, px::2].ravel()
r = cr[level][py::2, px::2].ravel()
sums[level, phase, 0, 0] += y.var()
sums[level, phase, 1:, 1:] += np.cov(np.stack([b, r]))
case_worst = 0.0
where = ""
for level in range(LEVELS):
for phase in range(4):
measured = sums[level, phase] / REALIZATIONS
model = nm.level_noise(point, kappa0, level, phase, case["residual"])
checks = {
"Y": measured[0, 0] / model.luma_variance - 1.0,
"Cb": measured[1, 1] / model.chroma_covariance[0, 0] - 1.0,
"Cr": measured[2, 2] / model.chroma_covariance[1, 1] - 1.0,
"Cb-Cr": (measured[1, 2] - model.chroma_covariance[0, 1])
/ np.sqrt(model.chroma_covariance[0, 0] * model.chroma_covariance[1, 1]),
}
for label, deviation in checks.items():
if abs(deviation) > case_worst:
case_worst = abs(deviation)
where = f"{label} L{level} p{phase} {deviation:+.4f}"
worst = max(worst, case_worst)
print(f"{name:<9} mu={mu} m=({merge.read:.4f},{merge.shot:.4f}) worst={case_worst:.4f} at {where}")
print(f"worst deviation {worst:.4f} (tolerance {TOLERANCE}) {'PASS' if worst <= TOLERANCE else 'FAIL'}")
return 0 if worst <= TOLERANCE else 1
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,143 @@
"""Gate for implementation step 1 (docs/photon-multiscale-denoise.md section 14).
Synthesises noise that obeys the section 2 model exactly (independent per-source
Poisson-Gaussian variance, separable spatial correlation, demosaic-like channel
mixing), builds both Laplacian pyramids and checks every level, phase and
working channel against the predicted variance. Pass: all ratios in 1 +/- 0.03.
Run: uv run --with numpy python -I tools/photon_denoise/validate_propagation.py
"""
from __future__ import annotations
import sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import noise_model as nm # noqa: E402
SIZE = 2048
REALIZATIONS = 8
LEVELS = 5
TOLERANCE = 0.03
def filter_periodic(image: np.ndarray, taps: np.ndarray, axis: int) -> np.ndarray:
radius = (taps.size - 1) // 2
out = np.zeros_like(image)
for i, weight in enumerate(taps):
if weight != 0.0:
out += weight * np.roll(image, radius - i, axis=axis)
return out
def blur(image: np.ndarray, taps: np.ndarray) -> np.ndarray:
return filter_periodic(filter_periodic(image, taps, 0), taps, 1)
def downsample(image: np.ndarray, taps: np.ndarray) -> np.ndarray:
return blur(image, taps)[::2, ::2]
def upsample(image: np.ndarray, taps: np.ndarray) -> np.ndarray:
up = np.zeros((image.shape[0] * 2, image.shape[1] * 2))
up[::2, ::2] = image
return blur(up, 2.0 * taps)
def laplacian_levels(image: np.ndarray, taps: np.ndarray, levels: int) -> list[np.ndarray]:
bands = []
g = image
for _ in range(levels):
coarse = downsample(g, taps)
bands.append(g - upsample(coarse, taps))
g = coarse
bands.append(g)
return bands
def phase_variance(band: np.ndarray) -> np.ndarray:
return np.array([band[py::2, px::2].var() for py in (0, 1) for px in (0, 1)])
def main() -> int:
rng = np.random.default_rng(20261028)
# Demosaic-like spatial correlation, different per axis (A2: separable, not isotropic).
fx = np.array([0.15, 0.7, 0.15])
fy = np.array([0.1, 0.25, 0.5, 0.25, 0.1])
w = nm.spectrum_frequencies()
def power(taps: np.ndarray) -> np.ndarray:
radius = (taps.size - 1) // 2
response = sum(t * np.exp(-1j * w * (i - radius)) for i, t in enumerate(taps))
return np.abs(response) ** 2
px, py = power(fx), power(fy)
# Normalise to unit mean; the amplitude goes to the coefficients.
ax, ay = px.mean(), py.mean()
px, py = px / ax, py / ay
fx, fy = fx / np.sqrt(ax), fy / np.sqrt(ay)
# Source-channel model and a demosaic-like mixing B: output_rgb = B @ source.
state_mu = np.array([0.12, 0.25, 0.08])
read = np.array([2.0e-5, 1.5e-5, 2.5e-5])
shot = np.array([4.0e-4, 3.0e-4, 5.0e-4])
quadratic = np.array([1.0e-4, 0.0, 2.0e-4])
mix = np.array([[0.8, 0.2, 0.0], [0.1, 0.85, 0.05], [0.0, 0.25, 0.75]])
transfer = np.stack([np.outer(mix[:, c], mix[:, c]) for c in range(3)])
state = nm.NoiseState(read, shot, quadratic, transfer)
white_balance = np.array([2.0, 1.0, 1.6])
scale = 4096.0
sigma = state.working_covariance(state_mu, white_balance, scale)
tables = {
"Y": nm.propagate(px, py, nm.LUMA_TAPS, LEVELS),
"C": nm.propagate(px, py, nm.CHROMA_TAPS, LEVELS),
}
source_sigma = np.sqrt(state.source_variance(state_mu, np.ones(3)))
to_working = scale * nm.YCC_FROM_RGB @ np.diag(white_balance) @ mix
sums = {key: np.zeros((LEVELS, 4, 3, 3)) for key in tables}
for _ in range(REALIZATIONS):
source = np.empty((3, SIZE, SIZE))
for c in range(3):
white = rng.standard_normal((SIZE, SIZE))
source[c] = source_sigma[c] * filter_periodic(filter_periodic(white, fy, 0), fx, 1)
working = np.einsum("ij,jyx->iyx", to_working, source)
for key, taps in (("Y", nm.LUMA_TAPS), ("C", nm.CHROMA_TAPS)):
bands = [laplacian_levels(working[i], taps, LEVELS) for i in range(3)]
for level in range(LEVELS):
for phase, (py_, px_) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))):
stack = np.stack([b[level][py_::2, px_::2].ravel() for b in bands])
sums[key][level, phase] += np.cov(stack)
worst = 0.0
print("level phase channel check")
for key, channels in (("Y", [(0, 0)]), ("C", [(1, 1), (2, 2), (1, 2)])):
table = tables[key]
for level in range(LEVELS):
for phase in range(4):
measured = sums[key][level, phase] / REALIZATIONS
kappa = table.kappa_laplacian[level, phase]
for i, j in channels:
predicted = kappa * sigma[i, j]
name = "YCbCr"[0] if i == 0 else ["", "Cb", "Cr"][i] + ("" if i == j else "-Cr")
if i == j:
deviation = measured[i, j] / predicted - 1.0
label = f"ratio {1.0 + deviation:.4f}"
else:
# A small cross-covariance has an unstable ratio; compare it in
# correlation-coefficient units instead.
scale_ij = kappa * np.sqrt(sigma[i, i] * sigma[j, j])
deviation = (measured[i, j] - predicted) / scale_ij
label = f"rho pred {predicted / scale_ij:+.4f} err {deviation:+.4f}"
worst = max(worst, abs(deviation))
print(f"{key}{level} {phase} {name:<6} {label}")
print(f"worst deviation {worst:.4f} (tolerance {TOLERANCE})")
return 0 if worst <= TOLERANCE else 1
if __name__ == "__main__":
raise SystemExit(main())