# 修订记录

修订记录列出了各文档版本间发生的主要更改。下表列出了每次文档更新的技术内容。

| 版本 | 修订日期   | 修订说明                                   |
| ---- | ---------- | ------------------------------------------ |
| V0.1 | 2023-03-25 | 第一次汇总完成（Cmodel阶段）               |
| V0.2 | 2024-01-12 | 整体结构汇总完成                           |
| V0.3 | 2024-03-09 | 更新参数列表和说明                         |
| V0.4 | 2024-04-09 | 调整文档格式                               |
| V0.5 | 2024-05-09 | 更新参数说明及调试流程图                   |
| V1.0 | 2024-06-17 | 补充3A调试说明，调整部分文字表述           |
| V1.1 | 2024-09-04 | 修正格式错误，完善AE/AWB/WDR ISP模块功能描 |

# X5 ISP introduction

## Overview

本文档介绍了Horizon Sunrise X5 图像处理器的测试和调试方案，详细说明了静态图像和动态视频图像质量系统化的调试方法。调试效果会受到CMOS sensor、镜头光学性能、模组结构及图像处理器等因素的影响，因此实际调试中需要结合硬件和项目具体需求采用适合的调试方案。

图像质量测试需要贯穿在整个项目开发周期中，分不同阶段进行针对性的图像质量调优。项目开发中至少要进行两轮比较全面的图像质量评估及调试；图像评估测试需要借助标准的实验室环境对图像质量进行精确的客观评估，实验室环境需要包含可调照度及色温的设备来满足不同光照条件下的测试评估。

本文档包含了客观图像质量测试的相关描述，客观图像质量测试可以较为精确的对图像进行定量分析。部分调试需要在特定的光照条件下进行，可以通过与竞品摄像头进行客观数据对比进行针对性的优化调试。

主观调试需要针对实际场景进行测试，测试中需要使用已调试的效果参数进行多场景的测试，并针对测试结果进行细节优化。对于有特殊应用的摄像头产品，因其应用的特殊性需要针对其特定的产品使用环境进行针对性的优化调试；

文档后续章节具体介绍调试测试方法、调试流程、数据分析及如何通过数据测试分析进行ISP参数调优。

Horizon Sunrise X5可以支持3种模式：Linear，HDR和Native-WDR-lin。文档中主要介绍Linear 模式的图像调试，如非Linear模式的调试方法会进行特别的说明。

## ISP Pipeline

![](_static/_images/isp_tuning/image2.png)

Figure 1.2‑1算法模块流程图

图中，背景为黄色的模块代表在RAW域进行处理，背景红色的模块代表在RGB域处理，背景蓝色的模块代表在YUV域处理，背景为浅紫色的内容代表AE/AWB的统计计算。虚线引出的四个位置为AE/AWB的统计位置可选的统计位置，可按实际需求切换。

# ISP Tuning Overview

## Tuning procedure

### Tuning equipment

Horizon X5 ISP图像质量的调试需基于实际的应用场景来准备相应的仪器，以保证调试能够顺利进行。以下为Horizon Sunrise X5 ISP进行典型场景调试所需要的实验室设备仪器：

- 24 X-Rite Color 图卡

- Edmund optics Opal diffusing glass

- ISO12233 图卡

- ISO15739 图卡

- 2个可调照度的立式灯箱

- 三角架及摄像头模组固定支架

- 标准可调色温灯箱

- Studio scene

- 光照度计

- 曝光测试仪器

- DNP灯箱

- 36阶透射式HDR测试仪器

### Tuning in Phases

ISP参数校正流程主要包含三个阶段：

- 第一阶段：需要确认CMOS sensor能够正确的进行初始化，获取正确的RAW信息，进行特性参数配置；

- 第二阶段：ISP相关的算法模块基于Sensor特性进行效果优化调试；

- 第三阶段：系统化的测试评估，系统化综合调试满足各场景的图像质量需求。

Figure 2.1-1 为三个调试阶段的流程图

![](_static/_images/isp_tuning/image3.png)

Figure 2.1‑1 ISP tuning process

### Phase 1-Sensor Dependent Calibration

Hobotplayer 是一个集显示与采集数据功能一体的可视化工具，调试时用来采集Raw图和yuv数据。在调试的初期需要使用Calibration tool对sensor进行特性配置。根据各个模块调试的需求采集相应的Raw 图，通过Calibration tool标定sensor的静态调试参数。静态Raw图的采集工具Hobotplayer 和客观参数标定工具Calibration tool的使用请见《X5-Calibration tool工具指南》。

Sensor特性配置和光学特性校正需要使用到如下模块：

- Black Level Subtraction

- De-Companding (frontend/FE) LUTs. For WDR PWL mode

- Noise profile (NP)

- Green Equalization(GE)

- Dynamic dead pixel correction (Dynamic DPC)

- Auto-exposure (AE)

- Lens shading correction (LSC)

- Auto-white balance (AWB)

- Gamma

- Color correction matrix (CCM)

- Chromatic aberration correction (CAC)

- Purple fringe correction (PF)

### Phase 2-Algorithem

第二个阶段的调试依赖调试的CMOS sensor特性及选定的ISP算法模式，并对相应的参数依据光照条件进行参数的优化。这个阶段的调试主要通过动态调试工具VTunerClinet进行实现，VTunerClinet的使用请见《X5-VtunerClient工具指南》。基于对以下模块的系统化调试来对图像质量按场景需求进行优化。

- Stitching

- 2DNR

- 3DNR

- Demosaic

- WDR（LTM）

- Color noise reduction（CNR）

- Edge Enhanced

- ISP modules

### Phase 3-Fine tuning

因前面两个阶段调试的参数可能不能覆盖到所有场景，导致部分场景出现不适合或不能接受的图像效果, 需要在第三阶段针对一些特定的场景进行细节优化。一般来说，这个阶段的调试需要使用到不同亮度及不同色温的光照条件。需要在不同光照环境下进行对应的测试，来评估调试的参数是否能覆盖足够多的真实场景。图像效果的分析需要结合主观和客观两方面进行综合评估。对于这些需要调试的场景，在重新调试参数前需要先对当前图像质量和参数进行分析对应后再进行。通过反复测试及调试确定调试方向，找到改善问题的关键参数后再进行适当优化。

在第三阶段通常需要调试的ISP模块如下：

- 2DNR 强度

- 3DNR 强度

- CNR 强度

- WDR 强度

- CCM模块色彩饱和度强度

- Demosaic

- EE 强度

**注：在整个三个阶段的调试过程中需要注意，初始化之后的任何修改都可能影响到后续模块的效果，如色彩还原、降噪效果及图像细节等，如[Figure2.1-2](#figure2_1_2)。相应的解决方法是按照图示的方式进行迭代调试。例如若需要调试Black level Subtraction模块，因为BLS是ISP pipeline中的第一个模块，会影响到颜色和噪声/细节，所有其他的模块都需要重新调试。**

![](_static/_images/isp_tuning/image4.png)

Figure 2.1‑2 Tuning cycles

## System Requirement for ISP tuning

调试前需要对相关的设备及环境信息进行核实确认：

### ISP Information

- 产品应用场景及画质需求

- ISP调试结果交付方式

- ISP图像处理框图

- 图像处理的应用模式：Linear，HDR，Native-WDR-lin等

- 数据输入的格式及bit位深

- 待调画面的分辨率与帧率

- 所调试sensor的Color pattern mode

- 是否需要使用OTP参数

- 是否具备内置ISP

### Sensor Configuration Information

- 高动态模式（HDR），sensor曝光比及曝光时间的限定信息

- 宽动态模式（WDR），sensor的规格书资料及其解压节点信息

- Sensor可设置的曝光和增益范围

- Sensor支持的帧率和分辨率

- Sensor输出的数据格式

- Sensor raw原始数据结构

### Sensor Optical Information

- 模组个体硬件性能一致性评估

- 红外截止滤光片的特性

- 黑电平的温漂及是否随模拟增益变化

### ISP Modes

调试过程致力于确定ISP图像处理中各模块参数的最佳值。这些参数会保存在相应的文件中，从调试工具Calibration Tool和VTunerClinet中可以获取相应的参数文件。主要调试参数文件说明如下：

| **文件名** | **描述** |
|:--:|:--:|
| Sensor_Calibration.XML | 模组的标定文件，包含BLC、LSC、CCM、WB、NoiseProfile等同模组本身特性相关需要基于模组RAW数据标定得到的数据 |
|   Sensor_Tuning.json   | ISP Pipeline中的各模块的调试参数配置，包含Manual和Auto模式下的参数配置和模组标定参数 |

Table 2.2‑1 ISP初始调试配置文件说明

### Tuning Tools (Calibration Tool/VTunerClient)

Horizon X5 ISP通过两个工具来辅助效果调试，静态校正工具Calibration Tool和动态调试工具 VTunerClient。

#### Calibration Tool

Calibration Tool用于生成static calibration file，在参数集成时要用到这个文件，一般命名为sensorName.json或sensorName.xml。该文件包含了一些与lens和sensor相关的tuning参数，例如black level，shading lookup tables，以及AWB算法中开放用于tuning的参数。

Tuning第一阶段的目标主要就是通过Calibration Tool去校准得到static calibration file。这个工具在之后的阶段里也有可能会用于修正之前的校准错误或问题。

![](_static/_images/isp_tuning/image5.png)

Figure 2.2‑1 Calibration Tool主界面

在使用Calibration Tool的时，可按照界面中的序号进行，逐个模块进行标定。也可以单独运行其中的单个模块进行参数标定。标定完成后，通过XML Generator生成的对应的static calibration file。.

#### VTunerClient

VTunerClient可以用来修改各个模块的效果参数，修改参数后的效果会实时的在Hobotplayer工具显示的画面上体现出效果变化。在VTunerClient的调试界面上，效果参数是按照功能模块进行分类的，在对应的模块中可以进行参数的修改。VTunerClient导入Calibration Tool校正得到的效果文件后会调整对应模块的参数。调试完成后可以保存当前的调试参数.json文件。VTunerClient界面如Figure 2.2‑2 。

![](_static/_images/isp_tuning/image6.png)

Figure 2.2‑2 VTunerClient 调试界面

### Hobotplayer

Hobotplayer是用来实时显示设备画面的工具，也用于保存不同数据格式图像数据，例如RAW，YUV，BMP，JPG。Hobotplayer的界面如**Figure 2.2‑3**，页面参数说明见 Table 2.2-2。在Init_config内设置正确的设备IP和端口后点击左侧功能栏的connect按钮即可看到数据流。若要dump raw需要勾选raw_en，然后在raw_num栏输入大于0的自然数，再勾选save_raw框。

![](_static/_images/isp_tuning/image7.png)

**Figure 2.2‑3** Hobotplayer**界面**

| **模块**                                  | **功能**              | **说明**                                                     |
| ----------------------------------------- | --------------------- | ------------------------------------------------------------ |
| version select  (part 1 in  Figure 2.2 3) | 选择平台              | 选择对应的平台                                               |
| network  (part 2 in  Figure 2.2 3)        | 网络连接/断开         | -                                                            |
| mode-select  (part 3 in  Figure 2.2 3)    | 网络传输/静态显示切换 | 实时数据流选dynamic-display  打开静态数据选static-display    |
| image-options  (part 4 in  Figure 2.2 3)  | 显示图片的信息和帧号  | -                                                            |
| save-config  (part 5 in  Figure 2.2 3)    | 保存raw或者yuv        | 先在raw_num/yuv_num栏输入数字后勾选save_raw/ save/yuv即可保存 |
| raw-channel  (part 6 in  Figure 2.2 3)    | 分通道显示raw图       | 勾选raw_en后可看到raw图，一般使用raw_l_win                   |
| init_config  (part 7 in  Figure 2.2 3)    | 配置网络和端口号      | 开发板网络IP                                                 |
| Apply  (part 8 in  Figure 2.2 3)          | 确认配置              | -                                                            |

Table 2.2-2 Hobotplayer 初始配置界面说明

# ISP Tuning Modules

## Auto-Exposure (AE)

### Overview

自动曝光(Auto-Exposure，AE)是通过调整图像的亮度，来准确还原当前场景的亮度。尽管AE在表征Sensor的特性中扮演次要的角色，但其在整个ISP调试过程中属于最基础的关键模块，可以使用VTunerClinet 分三个步骤来对AE做调整。

- 第一阶段：调试其它模块时，可以手动设定AE。这依赖于每个模块对曝光的要求，具体要求在每个模块的调试文档中会有详细的说明。

- 第二阶段：参照客观指标要求，在实验室中对大部分场景AE参数进行校正。

- 第三阶段：微调AE参数以适合所有场景。主要调整依据增益动态变化的参数。

### Tuning Theory

下图是AE处理的流程图：

![](./_static/_images/isp_tuning/image8.jpeg)

Figure 3.1‑1 AE处理流程图

**统计位置**

Pipeline中AE有4个统计位置，如 Figure 3.1-2 所示。

![](_static/_images/isp_tuning/image9.png)

Figure 3.1‑2 AE统计数据节点

**统计数据存储与处理**

ISP 自动曝光控制的通用统计模块将整个图像分割为 32×32 块，并计算每个通道（R、GR、GB、B）的平均值。这些平均值作为统计数据输出，用于实现自动曝光。

对于32×32统计阵列内的每个子块，输出1个32 位的统计数据，其中包含 R、GR、GB 和 B 通道的平均值，统计数据的数据结构如下图所示。如果是HDR mode的sensor，统计数据处理计算过程中，会将每个Block的亮度值与HDR ratio做倍乘。

![](./_static/_images/isp_tuning/image10.png)

Figure 3.1‑3 AE/AWB统计数据存储格式

以linear模式3840x2160分辨率的图像为例，32×32个窗格在图中的分布情况如下图所示

![](./_static/_images/isp_tuning/image11.png)

#### Metering Mode

自动曝光（AE）的测光功能是将图像分为多个块，并统计每个块的亮度进行计算得到图像的实际亮度。统计网格覆盖了整个图像，用于收集曝光相关的统计数据。通过配置不同数量的感兴趣区域（Region of Interest，ROI）及对应每个ROI的权重，可以调整AE的测光模式以适应不同的应用场景。

以下是不同AE测光模式：

- (默认) 平均测光。在此模式下，图像被分为32 x 32个块，图像亮度为所有块的平均亮度。

- ROI测光。在此模式下，图像被分为多个块。块的数量由roiNumber指定。图像亮度由平均测光模式测量的图像平均亮度和根据roiWeight指定权重的所有ROI的平均亮度决定。roiWeight的值越大，对ROI平均亮度的重视程度越高。

ROI测光包括如下操作：

- ROI配置。在初始化时，默认最多可以配置25个ROI区域。这些区域可以根据场景的需求来选择。例如要拍摄的主体位于画面的中心，则可以将中心区域设置为ROI，以确保主体曝光准确；

- 权重分配。每个ROI区域和非ROI区域的权重可以单独配置。权重决定了该区域在计算总体曝光时的影响程度。例如，对于重要的区域可以设置更高的权重，以确保这些区域在曝光计算中占有更大的比重。

- 区域重叠处理：当ROI区域与32x32的block块存在重叠时，系统会根据block块落在ROI区域中的比例来进行权重的叠加。这意味着，如果一个block块只有一部分覆盖了ROI区域，那么它在曝光计算中的权重会按照覆盖的比例来调整。

调试相关参数见下表

| **Parameter**     | **Type**                                                     | **Range**                                             | **Description**                                              | **Default**  **Value** |
| ----------------- | ------------------------------------------------------------ | ----------------------------------------------------- | ------------------------------------------------------------ | ---------------------- |
| roiNumber         | uint8_t                                                      | [0, 25]                                               | The number of ROI  regions.                                  | 0                      |
| roiWeight         | float                                                        | (0, 1)                                                | The weight of the  average brightness of the ROI area, which is weighted against the overall  average brightness of the entire image during metering. | 0.5                    |
| roiWindow         | 类型：Vsi3ARoiWindow_t[25*5]  where Vsi3ARoiWindow_t{float32_t fx;  float32_t fy;  float32_t fw;  float32_t fh;  float32_t weight} | Weight:[0, 255];  Others:changes with  the image size | The ROI window position and size.  l   fx: the starting position of each ROI in the horizontal direction.  l   fy: the starting position of each ROI in the vertical direction.  l   fw: the width of each ROI.  l   fh: the height of each ROI.  l weight: the weight of each ROI. | [0, 0, 100, 100, 1]    |
| expV2WindowWeight | float[32*32]                                                 | [0, 255]                                              | The weight of every block in the image.                      | 1                      |

Table 3.1‑1统计窗口ROI配置

通过这种灵活的配置和权重分配，AE测光能够适应各种复杂的应用条件，从而实现更准确的自动曝光。这对于提高图像质量，尤其是在动态变化的环境中，是非常重要的。

#### Scene Adaption

自适应AE是一种智能曝光技术，用于在背光或低光场景下基于场景评估调整目标平均亮度。

要使用自适应AE，首先需要启用场景评估。自适应AE处理后的设定点值由自适应AE处理前的设定点值和压缩的设定点值按targetFilter权重共同决定。基础的自适应AE参数见 Table 3.1-2：

| **Parameter** | **Type** | **Range**                                                    | **Description**                                              | **Default Value**                  |
| ------------- | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------------------------- |
| semMode       | enum     | {CAMDEV_AE_SCENE_EVALUATION_FIX,   CAMDEV_AE_SCENE_EVALUATION_ADAPTIVE} | Whether to enable the scene evaluation  function.  Value range:  l CAMDEV_AE_SCENE_EVALUATION_FIX:  disable scene evaluation.  l CAMDEV_AE_SCENE_EVALUATION_ADAPTIVE:  enable scene evaluation. | CAMDEV_AE_SC  ENE_EVALUATIO  N_FIX |
| targetFilter  | float    | (0,1)                                                        | The weight to get the setPoint value  after adaptive AE.  The greater the parameter value, the  more contribution the setPoint value before the processing of adaptive AE  make to the setPoint value after the processing of adaptive AE. | 0.5                                |

Table 3.1‑2 基础自适应AE参数

**背光场景补偿**

关键参数见 Table 3.1-3。

| **Parameter**  | **Type** | **Range** | **Description**                                              | **Default**  **Value** |
| -------------- | -------- | --------- | ------------------------------------------------------------ | ---------------------- |
| wdrContrastMin | float    | (0, 255)  | The threshold c1 for determining normal exposure.  If the brightness of the current frame  is less than c1, the exposure is normal. | 10                     |
| wdrContrastMax | float    | (0, 255)  | The threshold c2 for determining strong  backlight.  If the brightness of the current frame  is greater than c2, the backlight is strong.   If the brightness is less than c2 but  greater than c1, the backlight is mild. | 110                    |

Table 3.1‑3 背光补偿参数

如果降低wdrContrastMin和wdrContrastMax，即减少逆光限制的最小值和最大值，图像中的低亮度区域将显著变亮，接近设定点，但高亮度区域可能会过曝。

如果提高wdrContrastMin和wdrContrastMax，即增加逆光限制的最小值和最大值，图像的整体亮度将接近设定点，图像中的低亮度区域将略微变亮并保持相对暗淡。

**低光场景补偿**

当前帧的低光级别取决于帧的曝光。曝光越大，照明条件越暗，设定点需要压缩得越多。

在低光条件下拍摄的照片往往噪点较多。如果设定点过大，AE调整后的图像会更亮，噪点也会被放大。因此，对于较低的环境亮度，设定点应适当压缩。AE支持动态调节HDR/Linear两种模式在暗光环境下收敛目标值，以优化暗光环境下图像的画面表现。两种模式的调试方法类似，动态调整后暗光环境下AE收敛的目标值变化形式见下图（以Linear模式为例）。

![](_static/_images/isp_tuning/image12.png)

Figure 3.1‑4 AE低光补偿逻辑示意图

Table3.1-4 列出了在线性模式和HDR模式下调整暗光条件下目标亮度的参数。

| **Parameter**         | **Type** | **Range** | **Description**                                              | **Default**  **Value**          |
| --------------------- | -------- | --------- | ------------------------------------------------------------ | ------------------------------- |
| lowlightLinearLevel   | uint32_t | [0,16]    | The number of nodes in the Gain /  Repress array in linear mode. | 4                               |
| lowlightLinearRepress | float[5] | [0,1]     | The array of compression ratios for the  target brightness that varies with the gain in linear mode. | [1.0, 0.8, 0.6,0.4, 0.4]        |
| lowlightLinearGain    | float[5] | [0,255]   | The array of key node values of the  total gain of the sensor in linear mode. | [4.0, 8.0, 16.0, 32.0, 100.0]   |
| lowlightHdrLevel      | uint32_t | [0,16]    | The number of nodes in the Gain /  Repress array in HDR mode. | 4                               |
| lowlightHdrRepress    | float[5] | [0,1]     | The array of compression ratios for the  target brightness that varies with gain in HDR mode. | [1.0, 0.8, 0.8,0.8, 0.8]        |
| lowlightHdrGain       | float[5] | [0,255]   | The array of key node values of the  total gain of the sensor in HDR mode. | [4.0, 8.0,  16.0, 32.0,  100.0] |

Table 3.1‑4 低光补偿参数

可以设置lowlight{X}Level（X=Linear或HDR）参数来控制亮度级别的数量。

lowlight{X}Gain（X=Linear或HDR数组的第n个（n=1到16）元素表示第n个亮度级别的曝光值。随着n的增加，曝光增加，环境亮度降低。

设定点的压缩比由lowlight{X}Repress（X=Linear或HDR）控制。元素索引越大，压缩级别越高。

![](_static/_images/isp_tuning/image13.png)

Figure 3.1‑5 低光场景target值随Gain关系图

#### Damp Control

Damp Control是用于控制AE收敛状态的功能，通过调整对应的参数，控制AE的收敛速度，使帧之间的曝光更平滑。[Table 3.1-5](#Table3_1_5) 列出了与AE阻尼相关的参数。

| **Parameter**  | **Type** | **Range** | **Description**                                              | **Default**  **Value** |
| -------------- | -------- | --------- | ------------------------------------------------------------ | ---------------------- |
| dampOver       | float    | (0,1)     | A value that affects the convergence  speed of AE, when AE is transitioning from an overexposed state.  The smaller the value, the faster the  convergence. | 0.7                    |
| dampUnder      | float    | (0,1)     | A value that affects the convergence  speed of AE, when AE is transitioning from an underexposed state.  The smaller the value, the faster the  convergence. | 0.7                    |
| dampOverGain   | float    | (0,128)   | A value that controls the exponent of  the damping factor when AE is transitioning from an overexposure state.  The greater the value, the faster the  convergence. | 1                      |
| dampUnderGain  | float    | (0,16)    | A value that controls the exponent of  the damping factor when AE is transitioning from an underexposure state.  The greater the value, the faster the  convergence. | 1                      |
| dampOverRatio  | float    | (1,4)     | The threshold for the AE convergence  towards the target mean luminance in the overexposure direction.   The greater the value, the smaller the  fast convergence range.  Within this threshold and the target  mean luminance, the convergence is gradual. | 2                      |
| dampUnderRatio | float    | (0,1)     | The threshold for the AE convergence  towards the target mean luminance in the underexposure direction.   The smaller the value, the smaller the  fast convergence range.  Within this threshold and the target  mean luminance, the convergence is gradual. | 0.5                    |

Table 3.1‑5 AE阻尼参数

dampOverRatio和dampOverGain这两个参数通常用于控制系统响应的速度和稳定性。减少 dampOver或增加 dampOverGain ，AE 在高光条件下更快地收敛；减少 dampUnder或增加 dampUnderGain，AE 在低光条件下更快地收敛。增加 dampOverRatio，高光条件下快速收敛范围变小；减少 dampUnderRatio，低光条件下快速收敛范围变小。各参数关系示意图如下。

![](_static/_images/isp_tuning/image14.png)

Figure 3.1‑6 AE damp示意图

因此，如果需求快速收敛，建议将dampOverRatio调整得小一些，同时将dampOverGain调整得大一些。这样的配置会使系统更快地响应变化，但同时也要注意不要过度调整，以免引起系统的不稳定。在实际应用中，需要根据系统的具体响应和性能进行微调，以达到最佳的系统性能。

#### Anti-Flicker

Anti-flicker(防闪烁)功能用于减少由人造光源（如荧光灯和LED灯）引起的图像闪烁，通过检测光源频率并根据检测到的频率设置防闪烁模式，确保相机的曝光时间与环境光源的频率同步，目前，anti-flicker支持以下三种状态：

- 50赫兹（Hz）：适用于大多数欧洲国家和亚洲部分地区的电源频率。

- 60赫兹（Hz）：适用于美国和部分美洲国家的电源频率。

- 客制化Flicker：用户可以根据自己的需要设置特定的光源频率。这对于那些标准电源频率不是50Hz或60Hz的特殊环境非常有用。用户应根据自己的具体需求和环境条件选择合适的Anti-flicker设置。关键参数见Table 3.1‑6

| **Parameter**   | **Type** | **Range**                                                    | **Description**                                              | **Default**  **Value**  |
| --------------- | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ----------------------- |
| antiFlickerMode | enum     | AMDEV_FLIKER_PERIOD_OFF/CAMDEV_FLIKER_PERIOD_50Hz/CAMDEV_FLIKER_PERIOD_60Hz/CAMDEV_FLIKER_PERIOD_USER_DEFINED | The anti-flicker mode.  Value range:  l (Default)AMDEV_FLIKER_PERIOD_OFF: disable anti-flicker  l CAMDEV_FLIKER_PERIOD_50Hz: the anti-flicker mode for  lights whose flickering frequency is 50 Hz.  l CAMDEV_FLIKER_PERIOD_60Hz: the anti-flicker mode for  lights whose flickering frequency is 60 Hz.  l CAMDEV_FLIKER_PERIOD_USER_DEFINED: the anti-flicker  mode for userdefined light flickering frequency. | AMDEV_FLIKER_PERIOD_OFF |

Table 3.1‑6 Anti-Flicker 配置参数

#### Motion Detection

运动检测在自动曝光（AE）算法中是一个重要的功能，特别是在环境亮度剧烈变化或相机快速移动的情况下，避免因为环境变化过快而导致的曝光抖动。具体流程如下：

- 当环境亮度或相机位置快速变化时，如果系统检测到连续的帧之间亮度变化超过预设的阈值（motionThreshold），它会判断场景正在快速变化，AE会进入“lock”状态，即暂时锁定当前的曝光设置。

- 一旦环境稳定，AE会退出“lock”状态，重新开始自适应曝光调整，以适应新的环境亮度。

用户可以根据自己的需求调整AE算法的参数，例如调整曝光锁定的灵敏度或曝光调整的速度。AE运动检测处理流程见下图。

![](_static/_images/isp_tuning/image15.jpeg)

Figure 3.1‑7 AE Motion Detection处理流程

AE运动检测的关键参数见下表Table 3.1-7

| **Parameter**   | **Type** | **Range** | **Description**                                              | **Default**  **Value** |
| --------------- | -------- | --------- | ------------------------------------------------------------ | ---------------------- |
| motionFilter    | Float    | (0,1)     | The damping factor when calculating motion  vectors.  The larger the value is, the more likely the  current frame is considered to be in motion.  This parameter controls the cumulative calculation  of motion vectors.   A greater value of motionFilter means the change  of motion vectors is smoother but less timely updated. This may result in the  case where the motion amplitude of the current frame is significant, but is  not detected by the motion detection functionality. | 0.5                    |
| motionThreshold | Float    | (0,1)     | The threshold for determining whether the system  is in motion.   When the motion vector exceeds this threshold, the  current frame is considered to be in motion.  This parameter determines the sensitivity of  motion detection. You can reduce its value to improve the sensitivity.   A more sensitive motion detection means that even  slight movement of objects in the image during exposure time will be  considered as motion. | 0.7                    |

Table 3.1‑7 AE Motion Detection控制参数

#### Exposure Decomposition Table

曝光分解表提供与曝光相关的参数，包括曝光时间 (exposureTime)、数字增益 (dGain)、模拟增益 (aGain) 和图像信号处理增益 (ispGain)。通过使用 expDecomposeCustom 和 expTableNum，可以启用并定义曝光分解表，然后获取与曝光相关的参数。分解曝光量用到的曝光时间步长和Gain步长，在Sensor驱动中配置。关键参数见下表。

| **Parameter**      | **Type**                 | **Range**                       | **Description**                                              | **Default**  **Value** |
| ------------------ | ------------------------ | ------------------------------- | ------------------------------------------------------------ | ---------------------- |
| aGain              | float32_t[expTableNum-1] | based on sensor   limited value | Sensor analog gain array                                     | 1                      |
| dGain              | float32_t[expTableNum-1] | based on sensor   limited value | Sensor digital gain array                                    | 1                      |
| ispGain            | float32_t[expTableNum-1] | (0,255)                         | ISP gain array                                               | 1                      |
| exposureTime       | float32_t[expTableNum-1] | based on sensor   limited value | Exposure time array.                                         | 0.01                   |
| expTableNum        | uint_8                   | [0,8]                           | The number of nodes in the exposure   decomposition table.   | 0                      |
| expDecomposeCustom | bool                     | {true, false}                   | Whether to customize exposure   decomposition scheme within the sensor driver. | false                  |

Table 3.1‑8 AE基础曝光配置参数

以下是通过查找表来解释分解过程的方式。首先，我们定义下述公式：

New exposure=exposureTime\* dGain\*aGain\*ispDgain

下面的表格是一个曝光分解表的示例。

| **Parameter**   |      | e0* a0* d0* i0<Exposure<  e1* a0* d0* i0 |      | e1* a0* d0* i0<Exposure<  e1* a1* d0* i0 |      | e1* a1* d0* i0<Exposure<  e1* a1* d1* i0 |      | e1* a1* d1* i0<Exposure<  e1* a1* d1* i1 |      |
| --------------- | ---- | ---------------------------------------- | ---- | ---------------------------------------- | ---- | ---------------------------------------- | ---- | ---------------------------------------- | ---- |
| Exposure   time | e0   | Exposure/ a0* d0* i0                     | e1   | e1                                       | e1   | e1                                       | e1   | e1                                       | e1   |
| aGain           | a0   | a0                                       | a0   | Exposure/ e1* d0* i0                     | a1   | a1                                       | a1   | a1                                       | a1   |
| dGain           | d0   | d0                                       | d0   | d0                                       | d0   | Exposure/ e1* a1* i0                     | d1   | d1                                       | d1   |
| ispGain         | i0   | i0                                       | i0   | i0                                       | i0   | i0                                       | i0   | Exposure/ e1* a1* d1                     | i1   |

Table 3.1‑9 AE 曝光表示例

上图展示了一个通用的曝光分解表。在此示例中，仅列出了两个级别作为说明，所有其他级别之间的曝光参数分解模式都遵循这两个级别展示的模式。当曝光落在两个级别之间时，首先增加曝光时间，然后依次增加 aGain、dGain 和 ispGain。

实际生效的曝光配置受曝光参数和软件驱动配置两方面的影响，若配置的曝光表范围在软件驱动配置的范围内，将按照曝光表的配置下发曝光参数；若配置的曝光表范围大于软件驱动配置的范围，将会按照驱动配置的范围下发曝光参数，并且向用户侧报warning。例如驱动配置的曝光时间范围是5ms~20ms，若曝光表配置的曝光时间范围是10ms~20ms，那么实际生效的曝光时间将按曝光表的范围进行下发，最小曝光时间为10ms，最大曝光时间为20ms，软件侧不会报错。若此时曝光表配置的曝光时间范围是1ms~30ms，那么实际生效的最小曝光时间为5ms，最大曝光时间为20ms，且软件侧会提示曝光表越界的warning。增益设置也同理。曝光表配置时建议与软件驱动配置的范围一致，避免出现曝光效果不符预期的情况。

### Tuning during phase one

在调试第一阶段，Black Level和AWB模块需要设定符合条件的值（具体值可参考各模块的详细说明）。在ISP pipeline一些前端模块的调试过程中，对AE要求不高，不一定达到准确的曝光值。针对这种对AE要求不高的模块，可以通过VTunerClinet使能Manual AE来控制图片的亮度。

### Fine tuning AE phase two

完成下表中的先决条件设定后，AE调试可以作为第二阶段调试的初始值。

| **先决条件** | **状态 / 值** |
|:--:|:--:|
|       Sensor driver       |                      Fully tested                       |
|        Black level        |                          Tuned                          |
|       Lens shading        |                          Tuned                          |
|            WDR            |                        Disabled                         |
|       Initial gamma       |                           Set                           |
| Set initial AE_LDR_Target | Objectively chosen according to the output gamma chosen |

Table 3.1‑10 AE 第二阶段先决条件

**调试流程**

调试流程如Figure 3.1‑5所示：

![](_static/_images/isp_tuning/image16.png)

Figure 3.1‑8 AE第二阶段流程图

在实验室环境中检查AE的初始表现。将ColorChecker置于1500lux环境中，确保ColorChecker占比在30% ~ 50%（如下图所示）。拍图并通过Imatest的ColorChecker功能分析灰度值，也可以通过Adobe Photoshop 或者 GIMP手动分析ColorChecker 中的灰度值。

![](_static/_images/isp_tuning/image17.png)

Figure 3.1‑9 ColorChecker 占比

- **使用Imatest分析：**

Imatest 功能会输出exposure error 和 density response and curve fit测量指标。f-stop值在-0.25 ~ 0.25 间都是可以接受的。建议测量得到的f-stop值在 -0.1 ~ 0之间。

![](_static/_images/isp_tuning/image18.png)

Figure 3.1‑10曝光测量指标

- **使用Photoshop或GIMP分析：**

使用ROI选择工具选取ColorChecker中的每个灰块中的部分区域。对每个Patch而言，定义好选择区域后，使用intensity/luminance 直方图来计算所选区域的均值。

![](_static/_images/isp_tuning/image19.png)

Figure 3.1‑11灰块像素均值测量

对8-bit直方图而言，每个灰块像素均值的可接受范围值如下表格。一般来讲，期望测量得到得灰块像素的平均值在理想值-10 ~ 10区间都是可以的。最好的状态是图片轻微欠曝，与理想值的差值在 -5 ~0 之间。

| **Patch编号** | **理想值** | **最小值** | **最大值** |
| :-----------: | :--------: | :--------: | :--------: |
|      19       |    240     |    230     |    250     |
|      22       |    122     |    112     |    132     |
|      24       |     40     |     30     |     50     |

Table 3.1‑11 ColorChecker灰块的推荐值

**注：Patch 22反映的是18%灰的值**

以上内容给概述了AE控制以及影响AE算法的因素。

### Fine tuning AE phase three

**实验室实景调试**

完成AE的第一阶段和第二阶段的调试后，可在实验室实景灯箱中进行第三阶段主观调试。第三阶段的调试过程中，可依据需求或喜好来增加和减少曝光。这样做的目的主要是尽可能真实的还原实际场景并提高输出图片的主观接受度。在低光条件下，对清晰度和噪声的平衡尤为突出。AE要以具体需求为导向，这主要是由于整个相机系统要以实际应用为主，手机、监控和工业相机等不同应用领域都有各自的特殊要求。

第三阶段的调试主要包含两个LUT表，分别是LowLightLinearGain和LowLightLinearRepress。这个两个LUT表实现了在不同照度下动态改变AE目标亮度的功能。调试的主要流程如Figure 3.1‑9。

![](_static/_images/isp_tuning/image20.png)

Figure 3.1‑12 AE第三阶段调试流程

首先需要在实景灯箱中进行验证测试，实景灯箱应尽量模拟实际环境，灯箱中需要包含图像测试卡、不同色彩及带不同纹理的实物。亮度的控制可以通过能调节亮度的灯箱来控制，照度范围应囊括不同的亮度段，大致可分为高亮（3000lux以上）、中亮（100 ~3000lux）和低亮（0 ~ 100lux）。在不同的亮度条件下，分别拍摄照片并通过第二阶段中提到的工具（Imatest、Photoshop和GIMP）来分析和确认当前亮度下的曝光值是否在需求的接受范围内。

创建了7个节点来定义不同照度范围，这是远远不够的，还需要进一步对AE在不同照度下做验证。针对每个照度下AE验证，需要通过Imatest/Photoshop/GIMP来分析每个灰块的亮度值。在测试中如仍发现存有落在曝光范围外的值，则需重复上述校准步骤。在优化的过程中，不可能兼顾所有的场景，会存在参数及节点重叠或冲突的问题，这种情况需要根据具体的需求做取舍。

注：在调整AE参数时，为避免更改模块中查找表中的先前参数，调整应以周期为单位进行调整（逐亮度或逐个Gain）。在第三阶段中，调试应从调制有关所有系统参数最低的增益开始， 不只是AE模块。 然后递增增益，逐增益调整所有相关的系统参数。

**场景测试**

完成所有实验室调试后，最后需要在真实场景中进行调试。这么做主要是发现实验室条件与设备实际应用环境间的差异。在对实验室调试效果分析前，需要拍摄涵盖比较多样目标的场景照片，需要捕获各种照明和天气条件下图片，用来对比色彩和纹理还原表现。使用参考相机调试及同时拍摄相同的场景，然后可以将调试相机图像与参考相机的图像进行比较，可以更直观的发现调试相机与参考机的特点及需要优化的方向。

在对采集的图像进行主观分析时，需重点关注实验室调试失败的地方。可能是由于曝光欠佳或噪声过多导致的。将参考相机输出的图像视为最低可接受质量，通过不断迭代先前调试的参数，直到场景范围符合标准为止。

**其它调试信息**

如果图像仍然存在较多噪声，可以尝试将动态范围向高亮区域移动，以降低曝光。如果噪声不是问题，则最好使用WDR补偿和校正低亮区域同时能够保留高光部分的信息。

## Auto-White Balance (AWB)

### Overview

色温随可见光的光谱成分变化而变化，在低色温光源下，白色物体偏红，在高色温光源下，白色物体偏蓝。人眼可根据大脑的记忆来判断，识别物体的真实颜色，AWB 算法的功能是降低外界光源对物体真实颜色的影响，使得我们采集的颜色信息转变为在理想日光光源下的无偏色信息。

### Tuning Theory

自动白平衡（AWB）模块用于自动调整图像的白平衡。AWB作用于RAW域，当启用AWB时，ISP硬件将帧划分为32 x 32块，AWB算法基于硬件统计数据计算出对应的Rgain和Bgain增益值，将所有32 x 32块的点形成校准的色温曲线。AWB算法基于图像中出现“近白”像素假设，检测到近白像素，测量块的点与光源的校准点（R_Gain, B_Gain）之间的距离。选择距离最短的两个光源作为主要和次要光源。然后确定块的权重。最终，图像的AWB增益值是所有块的加权R增益和B增益的平均值。

AWB系统框图如下图所示：

![](_static/_images/isp_tuning/image21.png)

Figure 3.2‑1 AWB处理流程

AWB基础调试参数如下表

| **Parameter**             | **Type**  | **Range**                                  | **Description**                                              | **Default**  **Value** |
| ------------------------- | --------- | ------------------------------------------ | ------------------------------------------------------------ | ---------------------- |
| enable                    | bool      | {true,false}                               | Whether to enable AWB.                                       | true                   |
| confidenceThre  shold[10] | float32_t | [0,3]                                      | The radius threshold of a light source.   If the distance between the (R_Gain, B_Gain) of a  white block and the (R_Gain, B_Gain) of light source exceeds the threshold,  the white block is assumed to be only under the light source. Or else, it is  assumed to be under mixed light sources. | 3 for each   member    |
| mode                      | enum      | {CAMDEV_AWB_MODE,CAMDEV_AWB_METEDATA_MODE} | Selects the AWB mode.  l CAMDEV_AWB_MODE:  default AWB   algorithm on the sensor.  l CAMDEV_AWB_METEDATA_MODE:  custom AWB algorithm on the sensor. | CAMDEV_AWB_MODE        |

Table 3.2‑1 AWB基础调试参数

#### Statistics

AWB Statistics模块将整个帧划分为32x32子块, 计算每个子块中R,Gr,Rb,B 4个Bayer像素的平均值。RAW数据来源可以设定成Expand, LSC，AWB Gain, WDR，其中一个。

![](_static/_images/isp_tuning/image9.png)

Figure 3.2‑2 AWB统计数据节点

#### Solid Color Correction

纯色校正用于避免图像中出现大面积纯色（如黄色、绿色和蓝色）时色温判断出现偏差，影像画面的白平衡表现。例如在晴天户外拍摄大面积的绿色草地时画面偏蓝，就是因为大面积的绿色场景使色温统计落到了中色温区域。为了能获得准确的白平衡表现，ISP提供了统计落点映射和统计落点扣除两种逻辑用于纯色场景校正。

**统计落点映射**

统计落点映射的思路是将标记的统计区域内的落点权重，映射到标准光源上，从而提高标准光源在当前场景的统计权重，在WB计算时将更多采用标准光源的数据。

校正过程如下：

1.  通过调整confoundPointXRg和confoundPointXBg（X = CWF/TL84/D65），校准D50光源下绿色、黄色或蓝色纯色块的R增益和B增益。

2.  通过将customPositionXEnable（X = CWF/TL84/D65）设置为true，启用纯色校正。

3.  通过设置confoundPointXThreshold（X = CWF/TL84/D65），配置三种纯色块的范围阈值。范围阈值是白块的（R_Gain, B_Gain）与纯色中心点的（R_Gain, B_Gain）之间的距离。

- 阈值过高可能导致CWF、TL84或D65光源下的白块被误判为D50光源下的绿色、黄色或蓝色纯色块。

- 阈值过低可能导致图像中D50光源下的绿色、黄色或蓝色纯色块被误判为（CWF/TL84/D65）光源下的白块。

  对于范围阈值的调试，需根据应用场景做适当调整。

4.  检查每个白块是否在D50光源下校准的蓝色、黄色或绿色范围内。

5.  如果所有白块都在校准范围内，则将当前白块的光源更改为D50光源。后续的光源概率、色温偏好和低光颜色校正基于校正后的D50光源。

相关参数见下表。

| **Parameter**              | **Type**  | **Range**    | **Description**                                              | **Default**  **Value** |
| -------------------------- | --------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| customPositionCwfEnable    | bool      | {true,false} | Whether to enable pure green block correction.               | false                  |
| confoundPointCwfRg         | float32_t | (0,4)        | The R gain of the calibrated green color block.  The parameter is used to adjust the R Gain  calibration value of the green block under the D50 light source. | 1.0                    |
| confoundPointCwfBg         | float32_t | (0,4)        | The B gain of the calibrated green color block.  The parameter is used to adjust the B Gain  calibration value of the green block under the D50 light source. | 1.0                    |
| confoundPointCwfThreshold  | float32_t | (0,3)        | The threshold value for judging whether a block is  a green block.  If the (R_Gain, B_Gain) point of a block does not  exceeds the threshold, the block is assumed to be a green block. | 2.0                    |
| customPositionTl84Enable   | bool      | {true,false} | Whether to enable pure yellow block correction.              | false                  |
| confoundPointTl84Rg        | float32_t | (0,4)        | The R gain of the calibrated yellow color block.  The parameter is used to adjust the R gain  calibration value of the yellow block under the D50 light source. | 1.0                    |
| confoundPointTl84Bg        | float32_t | (0,4)        | The B gain of the calibrated yellow color block.  The parameter is used to adjust the B gain  calibration value of the yellow block under the D50 light source. | 1.0                    |
| confoundPointTl84Threshold | float32_t | (0,3)        | The threshold value for judging whether the  certainblock is a yellow block.  If the (R_Gain, B_Gain) point of a certain block  does not exceeds the threshold, the block is assumed as a yellow block. | 2.0                    |
| customPositionD65Enable    | bool      | {true,false} | Whether to enable pure blue block correction.                | false                  |
| confoundPointD65Rg         | float32_t | (0,4)        | The R gain of the calibrated blue color block.  The parameter is used to adjust the R gain  calibration value of the blue block under the D50 light source. | 1.0                    |
| confoundPointD65Bg         | float32_t | (0,4)        | The B gain of the calibrated blue color block.  The parameter is used to adjust the B gain  calibration value of the blue block under the D50 light source. | 1.0                    |
| confoundPointD65Threshold  | float32_t | (0,3)        | The threshold value for judging whether the  certainblock is a blue block.  If the (R_Gain, B_Gain) point of a certain block  does not exceeds the threshold, the block is assumed as a blue block. | 2.0                    |

Table 3.2‑2 AWB统计点映射参数

**统计落点扣除功能**

上述的统计落点映射，通过提高标准光源的统计权重以校准颜色，在部分场景中受统计落点分散和映射后标准光源权重仍较低的影响，可能仍会有白平衡校准不完全的问题，为了能适应更广泛的纯色场景校正，ISP提供了统计落点扣除功能。

落点扣除功能的作用是将confoundPositionCustom:rg/bg对应统计位置附近的统计落点进行权重调整，现阶段支持最多25个统计区域的扣除，统计区域范围由confoundPositionCustom:threshold决定，数值越大囊括的范围越大，区域内落点的统计权重由confoundPositionCustom:weight决定，按下式计算

![image-20240905205326202](./_static/_images/isp_tuning/image-20240905205326202.png)

weight_new 为区域内落点参与AWB统计时实际生效的权重。

校正过程如下：

1.  在出现偏色问题的场景，使用hobotplayer抓取一张bmp/jpg图；

2.  保持拍摄位置不变，打开vtuner的AWB tool工具，点击load Image按钮导入拍摄的bmp/jpg图像；

3.  在AWB tool显示的窗口中，点击图像中纯色区域，能够在AWB统计落点图上看到点击区域的统计落点(见下图黄色落点)，在AWB tool左侧会显示该落点对应的Rgain/Bgain数值；

4.  将confoundPositionCustom:confoundPositionEnable置为true，confoundPositionCustom:rg/bg输入纯色区域的Rgain/Bgain值，先将confoundPositionCustom:weight置为0，调整confoundPositionCustom:threshold值观察画面白平衡的恢复情况，threshold调试时需注意不要覆盖到标准光源的标定点，导致在正常拍摄场景的白平衡出现问题，一般建议设置小于0.5。若白平衡校正强度过大，适当提高weight或者减小threshold的值，让白平衡表现正常；

5.  若白平衡未完全校正，需扣除多个统计落点，重复操作4直至覆盖所有需要调整的统计区域。

    ![20240904-151916](_static/_images/isp_tuning/image22.jpeg)

Figure 3.2‑3 AWBtool统计点数据获取

AWB落点扣除功能相关的调试参数见下表。

| **Parameter**                                 | **Type**  | **Range**    | **Description**                                              | **Default**  **Value** |
| --------------------------------------------- | --------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| confoundPositionCustom:confoundPositionEnable | bool      | {true,false} | Whether to enable AWB confoundPosition correction.           | false                  |
| confoundPositionCustom:Index                  | int       | [0,24]       | The index of AWB confoundPosition correction  parameters     | 0                      |
| confoundPositionCustom:rg                     | float32_t | (0,4)        | The Rgain center of the solid color block                    | 1.0                    |
| confoundPositionCustom:bg                     | float32_t | (0,4)        | The Bgain center of the solid color block                    | 1.0                    |
| confoundPositionCustom:threshold              | float32_t | (0,3)        | The range of solid color blocks.                             | 0.3                    |
| confoundPositionCustom:weight                 | float32_t | [0,1]        | The degree of removal of solid color blocks.   When Weight = 0, this solid color block is  completely excluded from the expected calculation of the overall AWB gain;   When Weight = 1, this solid color block is  completely included in the expected calculation of AWB gain;   When Weight = 0.5, the contribution of the Rgain  and Bgain of this solid color block to the overall AWB gain result is halved  compared to the white point of non-solid color blocks. | 0.1                    |

Table 3.2‑3 AWB统计点扣除参数

#### Light Source Probability

光源概率参数给每个光源（D65、D50、D75、CWF、TL84、A或F12）提供了18个曝光级别，采用增益倍数表示，存储在brightnessLevel\[18\]数组的18个元素内并按升序排列。光源在每个曝光级别下都有其概率，光源的概率影响块的R增益和B增益的权重。

光源的排布顺序与AWB标定时的色温顺序对应，如果需要调整某个光源在某个曝光范围内的概率值，先按照Calibration tool导出的标定文件内AWB模块的光源排布顺序，找到该光源对应那组光源概率参数，再更改该光源在需要调整的曝光范围内的weight值。weight值越大，在该曝光条件下AWB统计数据时对应光源的权重就越高。

光源概率相关的参数见下表。

| **Parameter**          | **Type**  | **Range**    | **Description**                                              | **Default**  **Value** |
| ---------------------- | --------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| lightWeightLevelEnable | bool      | {true,false} | Whether to enable light source probability to  adjust the weights of the (R_Gain, B_Gain) values of image blocks falling  under different light sources based on the brightness of the current frame.  Set the parameter to true to enable light source  probability. | false                  |
| brightnessLevel        | Float[18] | [0,17]       | The exposure values of a light source.   The index of the array represents the exposure  level. | 1                      |
| weight                 | Float[18] | [0,17]       | Light source probability.  Increasing the element value of index j (j = 0 to  17) in the weight array of a light source can effectively increase the  probability of detecting the light source at an exposure level of  brightnesslevel[j]. | 1                      |

Table 3.2‑4 光源概率参数

#### Color Correction

颜色校正用于在低光条件下校正图像的色彩偏差。

光源概率参数给每个光源（D65、D50、D75、CWF、TL84、A或F12）提供了18个曝光级别，采用增益倍数表示，曝光量和R和B通道增益分别通过brightnessLevel、grayRgain和grayBgain进行配置，brightnessLevel需按升序排列。根据环境条件确定曝光级别和主要光源，从grayBgain和grayRgain中插值出所需的白块在当前主要光源下的R和B增益调整。

光源的排布顺序与AWB标定时的色温顺序对应，如果需要调整某个光源在某个曝光范围内的概率值，先按照Calibration tool导出的标定文件内AWB模块的光源排布顺序，找到该光源对应那组光源概率参数，再更改该光源在需要调整的曝光范围内的grayRgain和grayBgain，以实现不同曝光级别下对色彩的调整。

下表提供了颜色校正参数的详细信息。

| **Parameter**        | **Type**  | **Range**    | **Description**                                              | **Default**  **Value** |
| -------------------- | --------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| preferenceGainEnable | bool      | {true,false} | Whether to enable color correction to correct the  bias caused by different light intensities.  Set the parameter to true to enable color  correction. | false                  |
| brightnessLevel      | float[18] | [0,17]       | The exposure value of a light source. The index of  thearray represents the exposure level.  The higher the exposure amount, the lower the  environmental brightness. | 1                      |
| grayBgain            | float[18] | (0,512)      | The gains of the blue channel relative to the  value 256.  The index of the array represents the exposure  level. | 256                    |
| grayRgain            | float[18] | (0,512)      | The gains of the red channel relative to the value  256.  The index of the array represents the exposure  level. | 256                    |
| useCcoffset          | bool      | {true,false} | Whether to add offsets to color correction matrix  (CCM).    | true                   |
| useCcmatrix          | bool      | {true,false} | Whether to use CCM for further color correction.             | true                   |

Table 3.2‑5 颜色校正参数

#### Color Temperature Preference

色温偏好允许您在保持整体良好调整的AWB的同时，根据不同色温调整图像色调，使其偏向红/黄色或蓝/紫色。在识别出当前环境对应的色温后，特定色温光源后，色温偏好功能通过偏好增益乘以原始R增益和B增益值。此部分色彩偏好调整仅与环境色温相关，与曝光量无关，若要结合曝光量进行精细化调整请使用3.2.2.4节的色彩校正功能。

与色温偏好相关的参数如下。

| **Parameter**     | **Type** | **Range**    | **Description**                                              | **Default**  **Value** |
| ----------------- | -------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| temperatureEnable | bool     | {true,false} | Whether to enable the color temperature preference  feature.  Set this parameter to true to enable color  temperature preference | false                  |
| preferenceA       | uint16_t | (0,512)      | The color preference of the low temperature light,  which is implemented by modifying R gain.  Increasing the parameter value results in a redder  image under light A. | 256                    |
| preferenceCwf     | uint16_t | (0,512)      | The color preference of the middle temperature  light, which is implemented by modifying R gain under CWF light.  Increasing the parameter value results in a redder  image. | 256                    |
| preferenceD65     | uint16_t | (0,512)      | The color preference of the high temperature  light, which is implemented by modifying B gain.  Increasing the parameter value results in a bluer  image under D65 light. | 256                    |

Table 3.2‑6 色彩偏好参数

#### Face AWB

面部AWB的工作原理如下：

1.  获取面部区域的ROI中的R增益和B增益值。

2.  基于面部颜色偏好调整获取的R增益和B增益值。

3.  计算调整后的R增益和B增益值的平均值，以获得面部区域的平均R增益和B增益值。

4.  加权面部区域的平均R增益和B增益值，以获得整个图像的R增益和B增益。

与面部AWB相关的参数如下

| **Parameter** | **Type** | **Range**    | **Description**                                              | **Default**  **Value** |
| ------------- | -------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| faceAwbEnable | bool     | {true,false} | Whether to enable face AWB.  You mustfirstset this parameter to true to enable  face AWB | false                  |
| faceAwbRoiNum | uint8_t  | [0,1]        | The number of face ROIs.                                     | 0                      |
| faceWeight    | uint32_t | [0,1]        | The proportion of face AWB in the overall AWB gain  calculation.  The greater the parameter value, the greater the  impact of the AWB gain of the face area on that of the entire image, and the  more purplish the image.  This is because the R gain and B gain of the face  area are higher than that of the white blocks. | 0.5                    |
| faceAwbRg     | uint32_t | (0,256)      | The preference for the R gain in the face AWB.  The greater the parameter value, the redder the  face area and the entire image after AWB processing. | 256                    |
| faceAwbBg     | uint32_t | (0,256)      | The preference for the B gain in the face AWB.  The greater the parameter value, the bluer the  face area and the entire image after AWB processing. | 256                    |

Table 3.2‑7 面部AWB参数

#### ROI AWB

ROI AWB的工作原理如下：

1.  获取ROI的R增益和B增益值。

2.  计算获得的R增益和B增益值的平均值，以获得ROI的平均R增益和B增益值。

3.  加权平均R增益和B增益值，以获得整个图像的AWB增益。

ROI AWB参数的详细信息如下。

| **Parameter** | **Type**                                                     | **Range**                                                    | **Description**                                              | **Default**  **Value** |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------------- |
| roiNumber     | uint8_t                                                      | [0,25]                                                       | The number of ROI regions for ROI AWB.  You should set this parameter to be greater than 0  to enable ROI AWB. | 0                      |
| roiWeight     | float32_t                                                    | [0,1]                                                        | The weight that the AWB gain calculated by the ROI  AWB function contributes to the AWB gain.  The greater the parameter value, the greater the  impact of the AWB gain in the ROI area on the total AWB gain. | 0.5                    |
| roiWindow     | Vsi3ARoiWindow_t[25*5]  where Vsi3ARoiWindow_t{   float32_t fx;   float32_t fy;   float32_t fw;   float32_t fh;   float32_t weight} | Weight:[0, 255];   For other members, the range changes with the image size | The ROI window information, including:  l fx:  the horizontal start location.  l fy:  the vertical start location.  l w:  the width of the ROI window.  l h:  the height of the ROI window.  l weight:  the weight of the ROI. | [0,0,100,100,1]        |

Table 3.2‑8 ROI AWB参数

#### AWB Damp Control

为了避免曝光突然变化(例如从暗室变为晴天户外)引起的AWB波动，AWB需要快速响反应，而在曝光变化不明显时，AWB需保持稳定的数值。AWB阻尼用于平滑变化以避免过冲或抖动。阻尼越大，收敛越稳定越慢。AWB收敛可以通过AWB阻尼系数进行控制。

| **Parameter**    | **Type** | **Range**    | **Description**                                              | **Default**  **Value** |
| ---------------- | -------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| useDamping       | bool     | {true,false} | Whether to enable damping.  You must first set this parameter to true to  enable AWB damping. | true                   |
| useManuDampCoeff | bool     | {true,false} | Whether to set the damping coefficient manually.  If it is set to false, the AWB automatically  calculates manuDampCoeff according to the variations of exposure. | false                  |
| manuDampCoeff    | float    | (0,1)        | AWB damping coefficient.  The greater the coefficient, the smoother the AWB  convergence, reducing color changes between frames. | 0.5                    |

Table 3.2‑9 ROI AWB参数

白平衡各通道校正由AWB统计信息和算法基于静态校正结果完成的。该校正结果不会在帧数据中更新，而是作为配置的一部分在下一帧更新。

#### AWB Locking and Unlocking

外部环境色温的变化可能会导致AWB锁定状态的改变。

Table 3.2‑11列出了调整AWB锁定阈值的相关参数。一旦阈值大于0，AWB锁定功能即启用。参数值过大或过小可能导致AWB锁定或解锁状态保持不变，AWB处理后的图像颜色不准确。

| **Parameter**           | **Type**  | **Range** | **Description**                                              | **Default**  **Value** |
| ----------------------- | --------- | --------- | ------------------------------------------------------------ | ---------------------- |
| awbEnterUnlockThreshold | float32_t | [0,0.2]   | The threshold for the AWB to enter the unlocked  state.  The greater the threshold value is, the harder for  the AWB to be locked. | 0                      |
| awbEnterLockThreshold   | float32_t | [0,0.2]   | The threshold for the AWB to enter the locked  state.  The greater the threshold value is, the easier for  the AWB to be locked. | 0                      |

Table 3.2‑10 ROI AWB参数

### Tuning during phase one

**调试前置准备工作**

| **Parameter name** | **Description** |
|:--:|:--:|
|    Black level     |                            Tuned                             |
|    Lens shading    |                            Tuned                             |
|        CCM         |                            Tuned                             |
|       GAMMA        |                            Tuned                             |
|  Manual exposure   | -0:25 \< exposure error \< 0:25 (f-stops). This can be verified through Imatest. |

Table 3.2‑11 AWB第一阶段准备条件

#### Calibration images

![\\10.103.42.17\a02-x5\A070-X5-Sensor\A073-SC230AI\SC230-客观\Case2-correct\A_LSC_BG-2.png](_static/_images/isp_tuning/image23.png)

Figure 3.2‑4校正AWB 背板图

使用的CalbrationTool通过采集标准灯箱不同色温下ColorChecker和灯箱壁的RAW，来进行WB标定。具体详细标定方法参见《X5-Calibration tool工具指南》中有关AWB标定的部分。通过对采集到不同色温下RAW图进行标定计算以标定普朗克曲线图。

尽可能拍摄多种色温的Raw data灰卡或灯箱壁数据，如下表所列，其中D50和CWF光源是必不可少的，并且至少包含5个光源，算法计算出的结果才能够覆盖更多的场景。

**注：在采集RAW数据的时候使用照度计（例如：Minolta CL-200A）记录色温值。**

| **Illuminant** | **Color 3DNRature** | **Planckian/non-Planckian** |
| :------------: | :-----------------: | :-------------------------: |
|      10K       |       10000K        |          Planckian          |
|      D75       |        7500K        |          Planckian          |
|      D65       |        6500K        |          Planckian          |
|      D50       |        5000K        |          Planckian          |
|      CWF       |        4150K        |    Non-Planckian (Extra)    |
|      D40       |        4000K        |          Planckian          |
|      TL84      |        3800K        |          Planckian          |
|      TL83      |        2800K        |          Planckian          |
|       A        |        2800K        |          Planckian          |
|       H        |        2300K        |          Planckian          |

Table 3.2‑12 AWB标定色温列表

在进行基于普朗克曲线的标定时，确实需要注意一些关键点来确保准确性，特别是在选择白域时。以下是一些重要的步骤和注意事项：

1.  白域选择。在Calibration工具中，需要手动拖动框的位置来选择白域，尽量包含所有拍摄的灰卡点，这些点是用于校准的关键参考。同时注意避免将框拖得过大，以免包含不必要的区域，这可能会影响自动白平衡（AWB）的准确性。

2.  距离控制。框的大小应该紧密地围绕灰卡点，不要离这些点太远。过大的框可能会捕捉到额外的颜色信息，导致AWB不准确。

3.  标定处理。在使用的采集到的RAW进行标定时，务必将RAW通过CalibrationTool中Lens Shading Correction模块进行减除BLS和LSC的处理。若不做的LSC，则加载的LSC为0的配置。

#### Tuning verification using Imatest

通过Imatest中的Colorcheck选项运行ColorChecker图像。 可以测试出一系列图表中的颜色信息，用于颜色分析，获取色块20-22的色相饱和度值（HSV）并将其平均。

另外：可以参考数值来判断AWB效果，最终表现取决于图像传感器的质量和客户要求。

![](_static/_images/isp_tuning/image24.png)

Figure 3.2‑5 Imatest颜色分析窗口

| **AWB quality** | **6,500K (HSV)** | **4,000K (HSV)** | **2,700K (HSV)** |
| :-------------: | :--------------: | :--------------: | :--------------: |
|      Great      |     \<0.025      |     \<0.035      |     \<0.030      |
|      Good       |  0.025 - 0.050   |  0.035 - 0.060   |  0.030 - 0.065   |
|      Fair       |  0.050 - 0.100   |  0.060 - 0.110   |  0.065 - 0.160   |
|      Poor       |     \>0.100      |     \>0.110      |     \>0.160      |

Table 3.2‑13 AWB HSV数据参考

### Fine tuning AWB phase three

可以在第三阶段完成AWB其它可配置参数的调整。

#### Tuning color preference model

AWB算法在进行gain补偿时为每个颜色通道生成一个增益值，该增益值将使灰色对象还原成灰色。在AWB最终作用前，允许根据preference gain模块调整AWB最终要补偿的增益，以达到更好的或符合主观喜好的色偏，此增益每个颜色通道8位精度值，使用3个CCT值划分色温范围。各个色温下的增益默认为256。

#### Temperature Weight

在AWB参数配置中，可以通过调整自定义不同色温的权重值，下图给出了一个权重设置的例子。

![G:\X5文档\output (1).png](_static/_images/isp_tuning/image25.png)

Figure 3.2‑6 AWB色温权重设置

#### AWB verify

参照《VTunerTool 使用手册》中对该部分的介绍，用校正后AWB数据验证图像白平衡效果。

![](_static/_images/isp_tuning/image26.png)

Figure 3.2‑7 AWB Vertify示例

## High Dynamic Range（DOL2）

### Overview

现实场景的动态范围远高于低成本CMOS图像传感器的可用动态范围。因此，图像传感器捕获小范围（LDR）并将其映射到传感器的可用输出范围。传感器值范围以上或以下的辐照度水平将在传感器中被裁剪为黑色或白色。

HDR是将不同曝光的两帧图片拼接成一帧数据。由这种方式产生的单帧数据的精度比原始帧中任何一帧数据精度都要高。从根本上讲，这种算法是利用短曝光完整保留高亮部分信息，长曝光在不引入过多噪声的情况下完整保留低亮部分的信息，从而提高摄像机系统的动态范围。

HDR模块在无需访问 DDR情况下，将两个 12/16 位帧拼接成一个 20 位帧，从而捕捉图像更多的信息（明亮和暗区域）。WDR 模块将增强的 20 位帧缩减回 12 位，保留比原始线性帧更多的内容。不同曝光之间的比例由曝光时间和曝光增益决定。对于DOL2模式，我们可以选择将所有曝光调整到短曝光饱和水平，或长曝光对齐。

HDR模块包含下面的子功能：

> • Pre-Process Module (BLS, AWB, DG)
>
> • Histogram Statistics
>
> • Combine Module
>
> • Deghost

### Tuning theory

HDR 模块的主要基本算法流程：两帧HDR情况下，长帧和短帧经过预处理阶段，然后经过中间的运动检测阶段，最后合成一个高动态范围的图像。预处理阶段包括几个模块，主要是 BLC、DGain（细节增益）、AWB，它们会计算出图像的灰度亮度值，然后经过运动检测去重影，最后合并出高动态范围的图像。

DOL2整体处理流程图如下所示：

![](_static/_images/isp_tuning/image27.jpeg)

Figure 3.3‑1 HDR 处理流程图

#### BLC

HDR模式预处理中的BLC模块，可分别设定不同曝光帧BLC 4个通道的值。

下表列出了HDR预处理bls参数。

| **Parameter** | **Type** | **Range** | **Description**                              | **Default**  **Value** |
| ------------- | -------- | --------- | -------------------------------------------- | ---------------------- |
| bls[4]        | int      | [0,4095]  | BLS values in R, Gr, Gb, and B channels. nan | [0,0,0,0]              |

Table 3.3‑1 HDR BLS配置参数

#### Digital Gain

HDR模式预处理中的Dgain模块，可分别设定不同曝光帧Dgain 4个通道的值。用于提升RAW图的亮度。下表列出了HDR预处理参数。

| **Parameter** | **Type**    | **Range**    | **Description**                                              | **Default**  **Value**                                       |
| ------------- | ----------- | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| dgainEnable   | bool        | {true,false} | true: enables the digital gain function.  false: disables the digital gain function. | [0,0,0,0]                                                    |
| dgain         | Float[4][4] | /            | The digital gains, in the following format:  [[l_r, l_b, l_gr, l_gb],  [s_r, s_b, s_gr, s_gb],  [vs_r, vs_b, vs_gr, vs_gb],  [e3_r, e3_b, e3_gr, e3_gb]]. | [[1.0, 1.0, 1.0, 1.0],  [1.0, 1.0, 1.0, 1.0],  [1.0, 1.0, 1.0, 1.0],  [1.0, 1.0, 1.0, 1.0]] |

Table 3.3‑2 HDR DGain配置参数

#### Combine Module

在HDR Stitch线性模式下，我们可以将长曝光帧合并到短曝光帧中，或者反过来。

例如：一个基础帧称为Fbase，还有一个要合并的曝光帧称为Fin。Fbase和Fin通过加权因子W和曝光比率R 进行组合， 具体计算公式如下

![image-20240905205937117](./_static/_images/isp_tuning/image-20240905205937117.png)

HDR两帧融合模式，存在两种不同组合模式，实际combine参数中存在两种不同的配置。

**线性组合**

在线性模式下，我们可以将较长的曝光合并到较短的曝光中，反之亦然。为了方便起见，我们假设基准帧为B，要合并的曝光帧为E。有两个重要的参数可以影响合并结果，一个是比率，另一个是传输范围。如果启用了Deghost功能，则会添加Motion_factor。比率用于乘以E，因此如果B是较短的帧，则比率将小于1。因此，比率表示12位小数部分。否则，比率是一个8位整数，带有4位小数部分。

**非线性组合**

在合并短曝光帧到组合长曝光帧数据时，使用非线性模式。通常它们之间存在很大的灵敏度差距。短曝光帧噪声水平会很大，即使是长曝光帧的饱和水平也不能在一个线性尺度中混合。

![](_static/_images/isp_tuning/image28.png)

Figure 3.3‑2 HDR Combine处理说明

下表为HDR Combine相关参数的说明。

| **Parameter** | **Type**    | **Range**   | **Description**                                              | **Default**  **Value**                             |
| ------------- | ----------- | ----------- | ------------------------------------------------------------ | -------------------------------------------------- |
| bypassSelect  | int         | [0,2]       | 0: outputs only long frames.  1: outputs only short frames.  2: outputs only very short frames. | 0                                                  |
| colorWeight   | int[3]      | [0,255]     | The color weights, in format [stitchColorWeight0,  stitchColorWeight1, stitchColorWeight2] where:  l   stitchColorWeight0: the weight for the  channel with the greatest value  l   stitchColorWeight1: the weight for the  channels with in-between values  l   stitchColorWeight2: the weight for the  channel with the smallest value  The weights must meet the following  requirement:stitchColorWeight0 + stitchColorWeight1× 2+  stitchColorWeight2= 256  The greater the stitchColorWeight0, the   easier it is to combine short frames at the  saturation point of the corresponding channel.  If the short-frame noise is very large,  stitchColorWeight0 can be reduced and   the other weights can be increased.  For noise reduction, this parameter has a lower  priority than transRange. | [255,0,1]                                          |
| stitchingMode | int         | [0,1]       | 0: linear stitching mode.  1: non-linear stitching mode.     | 0                                                  |
| baseFrame     | int         | [0,1]       | 0: based on S frames.  1: based on L frames.                 | 0                                                  |
| ratio         | float[2]    | [1.0,256.0] | The exposure ratios, in the following format:  [long/short, short/very short]. | [16.0,16.0]                                        |
| transRange    | float[4][2] | [0.0,1.1]   | The start and end values of each composite  interval, where two frames overlap.  The value must be in the following format:   [[L+S_ref(L)_start, L+S_ref(L)_end],  [LS+VS_ref(LS)_start,  LS+VS_ref(LS)_end],[L+S_ref(S)_start, L+S+ref(S)_end],[LS+VS_ref(VS)_start,   LS+VS_ref(VS)_end]].  If the pixels of the reference frame are lower  than the start value, the composite frame pixels are longer frames.  If the pixels of the reference frame are higher  than the end value, the composite frame pixels are short frames.  If the pixels of the reference frame are within  the interval, the composite frame pixels are a fusion of the long and short  frames. | [[0.2, 0.9],  [0.0, 0.9],  [0.95, 1.0],  [0, 0.1]] |

Table 3.3‑3 HDR Combine参数说明

#### Deghost Module

由于短曝光和长曝光不同时捕获，如果场景中有运动物体，则合并结果图像中可能会出现Ghost，因此添加了运动检测功能。运动检测应检测运动区域，并用短曝光图像替换运动区域。由于传感器是线性的，L应等于ratioLS\*S，否则可能会出现运动物体。使用Motion_factor标记像素的运动程度，并参与多重曝光合并的计算。

![](_static/_images/isp_tuning/image29.png)

Figure 3.3‑3运动伪影示例

Deghost模块依据motionValue和motionFactor关系，可分别调整 lower threhold 和 过暗区域 lower threhold的值。

| **Parameter**               | **Type** | **Range**     | **Description**                                              | **Default Value** |
| --------------------------- | -------- | ------------- | ------------------------------------------------------------ | ----------------- |
| extentBit                   | Int[2]   | [-1,8]        | The value of the extended bits, in format  [L/S merge, LS/VS merge].  0 to 8: The extended bits are set to the   specified value.  -1: (Recommended) The extend bit is   automatically calculated according to the ratio. | [-1,1]            |
| motionEnable                | bool[2]  | {true, false} | true: enables  deghost.   false: disables  deghost.          | [false, false]    |
| motionWeight                | int[2]   | [0, 1024]     | The weights of the moving area.                              | [0,0]             |
| motionWeightShorter         | int      | [0, 1024]     | The weight of shorter frames in the moving area.             | 473               |
| motionSatThreshold          | int      | [0, 1024]     | The saturation threshold for motion detection.               | 4096              |
| motionWeightUpdateThreshold | int      | [0,8191]      | The weight update threshold.                                 | 1024              |
| motionLowerThresholdLs      | int[4]   | [0,2047]      | The motion detection thresholds in [gr, r, b, gb]  order.  It is recommended to increase the parameter values  as the shorter-frame gain increases. | [16,16,16,16]     |
| motionLowerThresholdLsvs    | int[4]   | [0, 4095]     | The motion detection thresholds in [gr, r, b, gb]  order.  It is recommended to increase the parameter values  as the shorter-frame gain increases. | [16,16,16,16]     |
| motionUpperThresholdLs      | int[4]   | [0, 4095]     | The motion detection thresholds in [gr, r, b, gb] order.  It is recommended to increase the parameter values  as the shorter-frame gain increases. | [120,120,120,120] |
| motionUpperThresholdLsvs    | int[4]   | [0, 4095]     | The motion detection thresholds in [gr, r, b, gb]  order.  It is recommended to increase the parameter values  as the shorter-frame gain increases. | [120,120,120,120] |
| darkLowerThresholdLs        | int[4]   | [0, 4095]     | The dark area thresholds in [gr, r, b, gb] order.  It is recommended to increase the parameter values  as the shorter-frame gain increases. | [16,16,16,16]     |
| darkLowerThresholdLsvs      | int[4]   | [0, 4095]     | The dark area thresholds in [gr, r, b, gb] order.  It is recommended to increase the parameter values  as the shorter-frame gain increases. | [16,16,16,16]     |
| darkUpperThresholdLs        | int[4]   | [0, 4095]     | The dark area thresholds in [gr, r, b, gb] order.  It is recommended to increase the parameter values  as the shorter-frame gain increases. | [256,256,256,256] |
| darkUpperThresholdLsvs      | int[4]   | [0, 4095]     | The dark area thresholds in [gr, r, b, gb] order.  It is recommended to increase the parameter values  as the shorter-frame gain increases. | [256,256,256,256] |
| dpfLConfig.div              | float    | [1.0, 64.0]   | The division factor.  A greater value leads to less denoise strength. | 0                 |

Table 3.3‑4 HDR Deghost 调试参数说明

**MotionDetection**

运动判断基准假设是传感器线性的。Long frame应该符合 ratio \* short frame 这个判断标准，否则可能就会存在motion。算法中用一个 motion value 值计算Long frame 和ratio \* short frame 的值。再用一个最大最小值标准化的区间，去计算motion factor 的值。这个区间是设置的参数里面的 motion lower threshold 和 motion upper threshold 区间，算法会算出 motion factor 值，以此来估计一下它是否是运动。

判定是否为运动存在两个标准：

1.  阈值判定。低于这个 lower threshold设为0，高于upper threshold会设为1024。低于thr_low判定为静止区域，高于thr_high判定为运动区。

2.  过暗区域信息替代。short 帧中的一些区域可能太暗，导致静止区域不匹配线性的规律。或者太暗的地方亮度值太低，没有可用的信息，所以即使是一个运动区域，也不能使用短曝光来去替代它。

![](_static/_images/isp_tuning/image30.png)

Figure 3.3‑4 Motion Factor作用曲线图

## Compand

### Overview

 Compand 模块完成数据的压缩和解压缩，由expand和compress两个子模块组成。Expand子模块可以将输入数据（12~20位）扩展为20位原始数据；Compress子模块可以将20位原始数据压缩为输出数据（12~20位）。

### Tuning Theory

 Expand Curve中X和Y用于输入和输出的曲线节点。在内部，这些值被分到两个RAM表，分别用于X、Y分量，每个表包含64个值。每个内存行可以通过ISP_COMPAND_EXPAND_x_ADDR寄存器单独寻址，并且可以使用相关的ISP_COMPAND_EXPAND_x_WRITE_DATA寄存器读取或写入其值。下表展示了compand模块相关的曲线图示例。

![](_static/_images/isp_tuning/image31.png)

Figure 3.4‑1 Compand 模块相关曲线图

相关调试参数如下

| **Parameter**        | **Type** | **Range**     | **Description**                                              | **Default Value**                                            |
| -------------------- | -------- | ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| expandEnable         | bool     | {true, false} | Enable expand in the compand module                          | false                                                        |
| expandCurveX[64]     | int[64]  | [0,24]        | x stands for the distance in expand curve  Distance_n = 1  << expand_px_n | -                                                            |
| expandCurveY[64]     | int[64]  | [0, 1048576]  | y stands for the value                                       | -                                                            |
| expandUseOutYCurve   | bool     | {true, false} | false: Use the built-in fixed formula to calculate  y using the configured x  true: Use the manual configured y value | false                                                        |
| compressEnable       | bool     | {true, false} | Enable compress in the compand module                        | false                                                        |
| compress CurveX[64]  | int[64]  | [0,24]        | x stands for the distance in expand curve  Distance_n = 1 << compress_px_n | [20, 18, 14, 20, 18, 14, 20,  18, 14, 13, 20, 18, 14,20, 18, 14, 13, 20, 18, 14, 20, 18, 14, 13, 20, 18,14,  13, 15] |
| compress CurveY[64]  | int[64]  | [0, 1048576]  | y stands for the value                                       | [ 8192, 14640, 16256, 16352,  29232, 32464, 32672, 32768, 58576, 65024, 65440, 65744, 117360, 130272,  131072, 234320, 260128, 261744, 467824, 519456, 522672, 524288, 937264,  1040512, 1046960, 1871312, 2077792, 2090704, 2097152, 3749056, 4162048, 4187856, 7485216, 8311168, 8362800,  8388608, 14996256, 16648160, 16751408, 16777216, 16777216 ] |
| compressUseOutYCurve | bool     | {true, false} | false: Use the built-in fixed formula to calculate  y using the configured x  true: Use the manual configured y value | false                                                        |

Table 3.4‑1 Expand调试参数说明

### Expand Phase One Tuning

按照的《X5-Calibration tool工具指南》文档中对应章节的说明进行参数的标定，得到Expand模块的参数值。

## Black Level Substraction

### Overview

Black Level Substranction是pipeline中第一个需要调试的模块，其它所有模块依赖于black level校正。因此这个模块是最基础的模块之一，在初始校正后很少去重新修改它。调试过程如下：

- 第一阶段-通过CalibrationTool标定不同Gain下的black level的值。

- 第二阶段-不需要调试，除非之前调试的效果较差。

- 第三阶段-不需要调试，除非之前调试的效果较差。

### Tuning Theory

图像传感器的黑电平根据温度、模拟增益、曝光时间而变化。大多数传感器制造商不提供有关温度的信息。因此在ISP中黑电平只与analog gain关联。BLS模块参数包含在VTunerClient中Black Level Substraction中。

| **Parameter** | **Type** | **Range**  | **Description**                          | **Default Value** |
|----|----|----|----|----|
| bls\[4\]      | int      | \[0,4095\] | BLS values in R, Gr, Gb, and B channels. | \[0,0,0,0\]       |

Table 3.5‑1 BLC参数

### Black level Phase One Tuning

按照的《X5-Calibration tool工具指南》文档中相应章节的说明进行参数的标定，得到不同Gain下对应4通道的Black Level的值。

## RGB InfraredRadiation

### Overview

RGBIR模块处理4x4 RGBIR数据模式。它将RGBIR数据转换为RGB Bayer数据和IR数据，以供后续ISP Pipeline处理。

调试过程如下：

- 第一阶段-使用VtunerClient标定IR分量。

- 第二阶段-调整高亮区域IR分量减除比列。

- 第三阶段-调整后端ISP Pipeline模块参数，调整方法同RGGB Patttern的模式

### Tuning theory

传统的COMS图像传感器使用Bayer方案作为颜色滤光片阵列（CFA）。像素的颜色信息是根据光的特定波长确定的。RGB-IR技术使用RGB-IR CFA，基于Bayer格式将部分像素修改为IR像素，只允许红外光通过。

在处理RGB-IR数据，需要将4x4的RGBIR模式恢复为RGGB模式，并提取出IR通道以供后续处理。RGBIR 模块的内部处理相当于一个小型pipeline，具有以下功能：

- Pattern normalize (归一化)

- Black level subtraction (BLS)

- DPCC RGBIR (坏点校正)

- De-noise and upscale IR channel to full resolution (降噪，IR通道升频至全分辨率)

- Interpolate G channel to full resolution (插值 G 通道至全分辨率)

- Interpolate B&R channel at R&B&G channel(在 R&B&G 通道处插值 B&R 通道)

- Remove IR component(去除IR分量)

- Down sample to RGB Bayer(下采样至RGB Bayer)

- Revert to normal RGB(恢复到正常RGB)

RGBIR PipeLine可整体表达为Figure 3.6‑1的形式**。**

![](_static/_images/isp_tuning/image32.png)

Figure 3.6‑1 RGBIR 处理流程图

RGBIR模式调试使用的参数如下。

| **Parameter** | **Type**  | **Range**     | **Description**                                              | **Default Value**                                            |
| ------------- | --------- | ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| enable        | bool      | {true, false} | Enable the RGBIR module.                                     | false                                                        |
| irThreshold   | int       | [0,4095]      | Infrared channel de-saturation curve.                        | 4095                                                         |
| lThreshold    | int       | [0,4095]      | Remove IR. When light > I_threshold_start, the  weight curve drops, gets smaller.  When light > I_threshold_end, weight = 0 | 4095                                                         |
| dpccTh[4]     | Int[4]    | [0, 65535]    | DPCC abs(center_pixel - avg) > th as defect  point, 0~4095, 4095 as not DPCC | [4095, 4095,4095, 4095]                                      |
| dpccMidTh[4]  | Int[4]    | [0, 65535]    | FFF000                                                       | [4095, 4095,4095, 4095]                                      |
| ccMatrix[12]  | float[12] | [-4.0, 4.0]   | 3*4 color conversion  matrix                                 | [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,  0.0, 0.0, 0.0, 1.0, 0.0] |
| gain[3]       | float[3]  | [0.0, 4.0]    | WB gain                                                      | [1.0, 1.0, 1.0]                                              |

Table 3.6‑1 RGBIR调试参数

#### RGBIR BLS

黑电平补偿是通过校准获得的黑电平偏移值进行减法运算的过程。这个偏移值用于校正图像或信号中的基线黑电平变化。

| **Parameter** | **Type** | **Range** | **Description** | **Default Value** |
|----|----|----|----|----|
| bls\[4\]      | int      | \[0,4095\] | BLS values in R, Gr, Gb, and B channels. | \[0,0,0,0\]       |

Table 3.6‑2 RGBIR BLC调试参数

#### RGBIR DPCC

DPCC在RGBIR模块之后，因此由于插值而导致的RGBIR模块中的坏点会扩散，因此RGBIR模块必须包括DPCC模块来纠正这些坏点。

DPCC模块包含两部分参数Dpcc_threshold和Dpcc_median_threshold，参数释义见Table 3.6‑1。DPCC参数必须根据坏点的值进行调整。如果调整过小，会对图像造成损坏。

#### RGBIR Remove IR

由于RGBIR传感器中的每个通道都包含一个红外（IR）成分，因此需要减去每个通道的IR成分，以恢复其为正常的RGB。

一个3x4矩阵的值是根据传感器的感应曲线确定的。通常使用以下矩阵，其中前三列是单位矩阵，最后一列是-1，用于减除R/G/B通道IR分量的比例。

![](_static/_images/isp_tuning/image33.png)

Figure 3.6‑2 RGBIR IR Remove处理矩阵

例如，原始R通道去除IR分量的计算方式为：

![image-20240905210224880](./_static/_images/isp_tuning/image-20240905210224880.png)

3x4矩阵中的最后1列，是决定IR减除比例的。不同减除比例的结果见Figure 3.6‑3。

![](_static/_images/isp_tuning/image34.png)

Figure 3.6‑3 RGBIR IR Remove差异配置效果图

#### Highlight IR Desaturation

当处理颜色彩饱和区域时，例如天空或高光区域，若直接应用原始矩阵处理，目标颜色会偏移原色彩。因为这些饱和区域各颜色通道的变化量不是线性的。

可通过设置阈值Th_l和Th_h，根据当前区域的亮度确定其是否处于过饱和区域，调整矩阵中R/G/B三个通道中IR系数，适当降低红外分量去除的比例，以减弱红外（IR）值并避免过饱和带来的影响。这有助于避免解决过度饱和引起的失真或不良影响。

对饱和区及向饱和的过渡区处理流程如下

![](_static/_images/isp_tuning/image35.png)

Figure 3.6‑4 RGBIR高光处理流程图

## Lens Shading Correction

### Overview

Shading是由于镜头成像时光轴中心与外围区域亮度不均匀导致的画面暗角现象。使用Lens shading模块可以校正图像的这种问题。同时，也可以校正色彩均匀性（chroma shading），对于图像最终的颜色还原非常重要。

Shading的表现与模组特性相关，取决于制造商组装光学器件的工艺及红外滤光片的性能。此外，不同的光照也会影响chroma shading，有时候也会因为Ir cut滤光片无法做出准确的波长截止而导致问题。

下面提供了模块调整的概述：

- 第一阶段：在实验室标准光源下标定Lens shading，通过Calibration tool来完成。

- 第二阶段：无需调整，除非其他模块导致shading校正出现不良问题。

- 第三阶段：无需调整，除非其他模块导致shading校正出现不良问题或实际应用场景中出现标定光源没有覆盖到的场景。

### Tuning Theory

LSC模块可以校正空间或非对称失真的shading，映射整张图片做校正。LSC矫正数据包含Bayer 4个通道的矫正值。阴影校正算法的目标是在校正后实现整个画面的亮度和颜色均匀性。因此，每个输入像素PIN(x, y)都要乘以校正因子F(x, y)。校正因子是一个固定点数，整数部分为4位，小数部分为10位，有效范围为\[1.0,15.999\]。校正因子取决于像素在画面内的坐标和像素的颜色。

根据以下公式计算校正后的像素值PCOR(x, y)：

![image-20240905210442084](./_static/_images/isp_tuning/image-20240905210442084.png)

为了提高校正功能的精确性，在 x 和 y 维度上被分割为32个区域。下图概述了镜头阴影校正区域分布情况。

![](_static/_images/isp_tuning/image36.png)

Figure 3.7‑1 LSC区域划分

每个区域的坐标是可编程的。此外，每个区域和每个颜色分量的镜头阴影校正参数也是可编程的。每个坐标适用于每个颜色分量。

在每个扇区内，校正函数F(x,y)可以表示为其四个边缘处离散校正值之间的双线性插值函数。这种插值是由硬件在图像数据处理过程中实时执行的。

**Shading关键参数**

LSC模块参数包含在VTunerClient中Lens Shading Correction中。

| **Parameter**     | **Type**       | **Range**     | **Description**                                              | **Default Value**                                            |
| ----------------- | -------------- | ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| enable            | bool           | {true, false} | Enable the LSC module                                        | false                                                        |
| matrix[4][33][33] | int[4][33][33] | [1024, 16383] | The gain of LSC, in R, Gr, Gb, B order.                      | All set to 1024                                              |
| xSize[32]         | int[32]        | [0, width/2]  | X stands for diffs  The sum of 32 elements is equal to the width of  the image | 1080p:  [60, 60, 60, 60, 60, 60, 60,  60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60,  60, 60, 60, 60, 60, 60] |
| ySize[16]         | int[16]        | [0, height/2] | Y stands for diffs  The sum of 16 or 32 elements is equal to the  height of the image  Currently only 16 elements is supported. | [34, 34, 34, 33, 34, 34, 34,  33, 34, 34, 34, 33, 34, 34, 34, 33] |

Table 3.7‑1 LSC调试参数

**静态校正关键参数**

LSC静态标定可以支持多组色温的校正表，最少需标定高、中、低3个色温的shading校正表。

| **Parameter name** | **Description** |
|:--:|:--:|
|  Shading_ls_d65\_\[R/Gr/Gb/B\]  |  Shading_ls_d65\_\[ R/Gr/Gb/B\] D65 Shading表  |
|  Shading_ls_d50\_\[R/Gr/Gb/B\]  |  Shading_ls_d65\_\[ R/Gr/Gb/B\] D50Shading表   |
| Shading_ls_tl84\_\[ R/Gr/Gb/B\] | Shading_ls_tl84\_\[ R/Gr/Gb/B\] TL84 Shading表 |
|  Shading_ls_cwf\_\[R/Gr/Gb/B\]  |  Shading_ls_d65\_\[ R/Gr/Gb/B\] CWF Shading表  |
|  Shading_ls_a\_\[ R/Gr/Gb/B\]   |    Shading_ls_a\_\[ R/Gr/Gb/B\] A Shading表    |
|   Shading_ls_h\_\[R/Gr/Gb/B\]   |   Shading_ls_d65\_\[ R/Gr/Gb/B\] H Shading表   |

Table 3.7‑2 Mesh-based lens shading Static calibration参数

**注：\[R / Gr /Gb/ B\]表示Bayer域每个颜色通单独的标签/参数**

Lens shading 生成的最大增益值是可配置的，最大增益支持到16倍，对镜头补偿的最大值可在使用calibration tool校准时进行配置。

### Tuning during phase one

由于Shading的标定依赖模组的特性，在完成Table3.7-3中先决条件后，可进入调试流程。按照的《X5-Calibration tool工具指南》文档中对应章节的说明进行参数的标定。

| **Prerequisite** |  **Status / value**   |
| :--------------: | :-------------------: |
|   Black level    |         Tuned         |
|   Gamma FE/BE    | Tuned(仅限Native WDR) |

Table 3.7‑3 Shading 标定先决条件

### Fine tuning lens shading phase three

Shading校正在pipeline中属于前端的模块，在phase three模块基本参数已经调整完毕，仅需要依据实际应用场景要求在更多的场景来验证并微调参数。

**调试过程**

在 Auto 模式下，通过修改strength来控制校正的强度，strength是根据gain梯度来匹配的，在不同的gain梯度下面，找到当前场景正确的shading strength设定值。

在gain较小时（场景亮度较高）不需要降低强度，随着光亮降低和gain的增加，图像噪声会起来，此时为了整体效果特别是边角噪声，shading 强度可以降低。特殊情况下，为了图像表现也可以将强度设置为“0”（边角亮度较低）。

此外，2DNR模块具有针对shading去噪功能，可以与shading强度结合。如果2DNR强度设定值在不造成图像模糊情况下，无法消除所有角落的噪声，则需要降低shading的强度来抑制噪声。

Shading强度调整时应根据主观分析可见噪声量来决定，为了得到每个增益下的正确强度值，需要调整环境亮度来使gain达到不同的梯度。

**Shaing主观场景调试方法**

1.  将摄像头置于studio的环境中，边角最好是灰色平面区域，确保当前增益为1x gain，当前应该是所有亮度下shading表现最好的一组，因此图像效果很好，边角噪声较小，因此当前gain梯度下强度可以设置shading强度到最大值。在高倍gain及环境亮度较低时，需要判断边角噪声的大小，根据以上介绍的调试方法来决定shading强度。

![](_static/_images/isp_tuning/image37.png)

Figure 3.7‑2 ISP Gain 0, 1000 lux场景

2.  降低环境亮度，gain增加让shading 强度达到下一个梯度，主观评估噪声量来决定当前状态的强度值，同样设定到shading strength对应的gain档位里，重复以上操作为所有gain 档位调试出匹配的shading 强度值。

![](_static/_images/isp_tuning/image38.png)

Figure 3.7‑3 ISP Gain 3, 500 lux 场景.

例如在光照为（500 lux）的场景，增益值大约为3x。此时，图像中的噪点开始增加，因此，对于增益为3的情况下，稍微降低shading强度值是可以接受的。

![](_static/_images/isp_tuning/image39.png)

Figure 3.7‑4 ISP max gain, 20 lux-max strength

![](_static/_images/isp_tuning/image40.png)

Figure 3.7‑5 Max gain – low strength

当在20 lux的弱光条件下，此时往往能达到最大增益。Figure 3.7‑4显示最大shading矫正强度的图像效果，Figure 3.7‑5是适当降低shading强度后的图像效果。从结果来看降低Shading强度可以降低图像噪声，同时角落的亮度出现一定程度降低，但仍能获得场景内的对象信息。调试时要根据实际需求，对边角亮度和噪声表现做折中，以获得更适配需求的画质表现。

## Digital Gain

### Overview

数字增益(Digital Gain)主要用于提升画面亮度。输入像素值与增益值相乘，作为Digital Gain的输出。输入RGB Bayer数据的每个色彩分量都与相应的DIGITAL_GAIN_x寄存器的增益值相乘。增益值为256对应于1.0的因子，因此颜色分量和增益的乘积将向右移动8位（四舍五入）

### Tuning Theory

Digital Gain作用的计算方式:

![](_static/_images/isp_tuning/image41.png)

Figure 3.8‑1 Digital Gain计算方式

Digital Gain相关的参数如下

| **Parameter** | **Type** | **Range**    | **Description**                | **Default**  **Value** |
| ------------- | -------- | ------------ | ------------------------------ | ---------------------- |
| enable        | bool     | {true,false} | Whether to enable Dgain module | true                   |
| digitalGainR  | float    | [1.0,255.0]  | R gain                         | 1.0                    |
| digitalGainGr | float    | [1.0,255.0]  | Gr gain                        | 1.0                    |
| digitalGainGb | float    | [1.0,255.0]  | Gb gain                        | 1.0                    |
| digitalGainB  | float    | [1.0,255.0]  | B gain                         | 1.0                    |

Table 3.8‑1 Digital Gain调试参数

## WDR

### Overview

宽动态范围（WDR, Wide Dynamic Range）技术是一种先进的图像处理方法，其优势在于能够显著提升图像中的局部对比度和全局对比度，使得图像细节更加丰富，特别是在高动态范围的场景中，如背光环境或阴影较多的区域。

### Tuning Theory

WDR是一种结合全局和局部色调映射的方法，用于将位宽压缩到12位，并增强图像的可见度。模块的核心功能是处理图像的最小单元，即16x16像素的块。根据输入图像的分辨率大小，整个图像被细分为多个这样的块。

为了在块之间实现平滑的视觉过渡，WDR模块采用双边滤波器（biliteral filter）进行插值处理。这种滤波器能够在保持边缘清晰的同时，平滑色彩空间中的细微变化，从而在块与块之间创建无缝连接。

WDR处理中实现对不同亮度区域的处理强度进行控制。模块可以独立地调整低亮度（low）、高亮度（high）和全局（global）的处理强度，以达到最佳的图像效果。在高动态范围（HDR）的数字重叠（DOL）模式下，WDR依赖于长短帧的曝光比率来优化图像。

此外，WDR模块提供了两种不同的平滑强度（smoothing strength）配置模式：

**全局模式：**所有的块都使用相同的平滑强度，这有助于在整个图像上实现一致的视觉效果。

**局部模式：**平滑强度可以根据块与块之间的亮度和内容差异进行调整。这意味着在图像的不同区域可以应用不同的处理强度，以更好地处理局部的光照变化。

通过上述方法，WDR模块能够有效地调整图像中的局部和全局对比度，特别是在背光场景或阴影区域，能够提供更加清晰和细腻的图像细节。

数据处理大致流程图：

![](_static/_images/isp_tuning/image42.png)

Figure 3.9‑1 WDR处理流程图

#### Preprocessing

在图像处理中，特别是在宽动态范围（WDR）技术的应用中，原始图像数据的预处理是至关重要的步骤，预处理流程图如下。

![](_static/_images/isp_tuning/image43.png)

Figure 3.9‑2 WDR预处理图

以下是对输入原始图像进行预处理的两个关键步骤的详细描述：

1.  Luma值计算。预处理的第一步是计算亮度（luma）值。这涉及到以下子步骤：

&nbsp;

1)  使用3x3的像素窗口，首先计算红色（R）、绿色（G）、蓝色（B）值的加权平均值。

2)  计算R/G/B值的最大值和最小值的加权。

3)  将上述两个计算结果与输入的原始数据结合，得到最终的luma值。

&nbsp;

2.  Pre-Gamma映射。对luma值应用pre-gamma映射和low_strength模块进行进一步处理。Pre-Gamma LUT这是一个包含65个bin的查找表，用于扩展灰度值，使其更加分散，从而增强图像的动态范围。Low_Strength这是一个可配置的参数，用于控制图像暗区的亮度。参数值越大，暗区的亮度信息越丰富，使得全局亮度提高。

在完成上述预处理步骤后，将对luma值进行全局和局部统计。

**全局统计**：计算整幅图像的平均值和均方差，以获取图像的整体亮度和对比度信息。

**局部统计**：将图像划分为16x16像素的块，并为每个块单独计算局部曲线。这包括计算每个块的平均值和直方图，后者是通过将20位灰度值分成64个区间并使用直方图LUT进行配置来实现的。

这些预处理步骤为WDR算法提供了必要的数据，以优化图像的局部和全局对比度，特别是在高动态范围的场景中，如背光或阴影区域。

| **Parameter**      | **Type** | **Range** | **Description**                                              | **Default**  **Value** |
| ------------------ | -------- | --------- | ------------------------------------------------------------ | ---------------------- |
| wdrLightnessWeight | int      | [0,128]   | max_rgb_weight                                               | 128                    |
| wdrColorWeight[3]  | Int[3]   | [0,128]   | [gray_weight, lightness_weight, raw_weight]  gray_weight + lightness_weight + raw_weight = 128 | [128,0,0]              |

Table 3.9‑1 WDR 预处理调试参数

#### Local Histogram Equalization and Smoothing

基于直方图LUT，可以得到每个块的直方图统计量。对直方图统计量进行归一化可以得到局部直方图曲线。为了防止过度拉伸造成的裁剪或严重噪声，将对局部曲线进行一维高斯平滑处理。平滑指数为平滑等级，平滑指数越高，平滑强度越高。不同平滑等级的图像效果示例如下

![](_static/_images/isp_tuning/image44.png)

Figure 3.8‑3 flat level平滑效果图例

有两种计算模式计算平滑等级：

1.  手动模式。所有块直接使用flat_level的值。

2.  半自动模式。flat_level作为起始平滑级别，根据局部直方图信息和可配置的ISP_WDR5_LUT_FLAT_LEVEL_WRITE_DATA计算出每个块平坦索引。

局部平滑计算相关参数如下。

| **Parameter**       | **Type**   | **Range**    | **Description**                                              | **Default**  **Value**                                       |
| ------------------- | ---------- | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| flatMode            | bool       | {true,false} | Strength adjustment mode for local contrast  enhancement.  false: Manual mode  true: Auto mode (manual part + automatic  incremental part) | false                                                        |
| flatLevel           | int        | [0,15]       | Manual strength of local contrast enhancement   The higher the value, the lower the manual  strength. | 5                                                            |
| flatLevelInc[4][17] | int[4][17] | [0,15]       | Automatic incremental strength of local contrast  enhancement  The higher the value, the lower the automatic  incremental strength. | [[3, 2, 1, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0],  [5, 4, 3, 2, 1, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0],  [7, 6, 5, 4, 3, 2, 1, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0],  [10, 10, 9, 8, 7, 6, 5, 4,   3, 2, 1, 0, 0, 0, 0, 0, 0]] |
| darkAttentionLevel  | int        | [0,14]       | The level of attention to dark areas.  The higher the value, the less attention to the  dark area. | 0                                                            |

Table 3.9‑2 WDR LTM 调试参数

#### Combination of Local Curve and Global Curve

在局部曲线和全局曲线的合并过程中，最重要的是权重的计算。当contrast = 1023时，局部曲线权重为1，全局曲线权重为0，仅局部曲线生效；当contrast = 0时，局部曲线权重为0，全局曲线权重为1，仅全局曲线生效；当contrast在(0,1023)内时，局部曲线和全局曲线按各自比例进行合并。一般来说，使用局部曲线能提高图像对比度，使用全局曲线能展现更多暗区细节，调试过程中按实际需求选择适当的合并比例。

![](_static/_images/isp_tuning/image45.png)

Figure 3.8‑4 local curve与global curve合并效果示例

若entropyEnable使能，则会利用每个块的熵和contrast计算全局曲线和局部曲线的合并强度，然后用gamma_down_lut插值计算出的强度。最后，用上述强度合并局部曲线和全局曲线。

| **Parameter** | **Type** | **Range** | **Description** | **Default Value** |
|----|----|----|----|----|
| enable          | bool     | {true,false}    | Enable/disable the WDR module                                | false             |
| strength        | int      | \[0,128\]       | As a fixed value of 128 when stitching is disabled, and as a variable value between 0~128 when stitching is enabled (0-base frame without WDR5, 128-stitching frame with WDR5). | 128               |
| highStrength    | int      | \[0,128\]       | The larger the value, the richer the highlight information and the darker the global brightness. | 0                 |
| lowStrength     | int      | \[0,256\]       | The larger the value, the richer the lowlight information and the brighter the global brightness. | 256               |
| contrast        | int      | \[-1023, 1023\] | The larger the value, the stronger the local contrast.       | 0                 |
| entropyEnable   | bool     | {true,false}    | true: Entropy information participates in block classification | false             |
| entropySlope    | int      | \[0,1023\]      | The larger the base, the smaller the slope, and the stronger the local contrast. | 0                 |
| entropyBase     | int      | \[0,1023\]      | The larger the base, the smaller the slope, and the stronger the local contrast. | 0                 |
| wdrLumaThr      | int      | \[0,1023\]      | Threshold of dark and bright area. entropyEnable=1: the parameter is invalid | 64                |
| fixedWeight     | int      | \[0,1023\]      | Manual weight of global curve                                | 0                 |
| flatLevelGlobal | int      | \[0,15\]        | Strength of auto global contrast enhancement The higher the value, the lower the strength. | 5                 |

Table 3.9‑3 WDR Strength 调试参数

#### Curve Adjustment

在目前的ISP中，WB、CCM和Gamma三个模块对色彩有显著影响，由于CCM校准与Gamma绑定，Gamma应保持正常开启，以保证色彩的准确性。但在图像亮度方面，WDR和Gamma均会提高图像亮度，若不进行适当调整图像很容易过曝。因而在WDR模块内添加了Degamma函数，用、于适当抑制亮度，避免输出的图像过亮。

WDR可以合理分配灰度级别，同时提升暗部亮度和抑制亮区亮度，使图像中的所有像素都分布在可视范围内。maxGain和minGain限制了不同亮度的像素允许使用的增益，避免出现局部过亮并抑制暗区噪声。但是，暗区的增强可能会放大噪声和颜色偏差问题，而抑制亮区可能会使过曝区域附近出现颜色。所以，最终的曲线将在这里受到限制。WDR模块允许通过图像块的增益值适当降低饱和度以抑制颜色偏差问题。

![](_static/_images/isp_tuning/image46.png)

Figure 3.8‑5 WDR暗区降饱和度示例

另外，WDR可以针对图像中的高对比度边缘进行适当抑制。当边缘对比度高于设定的阈值diffHigh时将会做淡化处理，减弱边缘对比度，对比度小于diffLow的边缘不会做处理，对比度在diffHigh和diffLow之间的会做插值进行优化。

![](_static/_images/isp_tuning/image47.png)

Figure 3.8‑6 WDR高对比度边缘抑制

WDR曲线调整相关参数见下表

| **Parameter**  | **Type** | **Range** | **Description**                                              | **Default Value** |
| -------------- | -------- | --------- | ------------------------------------------------------------ | ----------------- |
| degamma        | double   | (0,3.0]   | The factor of degamma  curve The higher the value, the darker the image. | false             |
| maxGain        | int      | [0,128]   | Maximum of WDR gain                                          | 128               |
| minGain        | int      | [0,4096]  | Minimum of WDR gain                                          | 1                 |
| diffHigh       | float    | [0,100]   | The threshold for  detecting high contrast edges where the detected high contrast edges will  become lighter in color.   The higher the value,  the fewer high-contrast edges are detected. | 100               |
| diffLow        | float    | [0,100]   | The threshold for  detecting low contrast edges where the detected low contrast edges will  become lighter in color.   The higher the value,  the fewer low-contrast edges are detected. | 100               |
| satRange       | float    | [0,1]     | Strength of  saturation reduction                            | 0                 |
| satThrGainDown | int      | [0,256]   | The threshold used to  determine pixels that need to be desaturated.   The higher the value,  the fewer dark pixels are desaturated. | 1                 |
| satThrGainUp   | int      | [0,256]   | Refer to previous  row. (This function can be used to reduce dark color noise and dark abnormal  colors.) | 16                |
| wdrRgbCoef     | Int[3]   | [0,128]   | [weight_r, weight_g,  weight_b] weight_r + weight_g + weight_b = 128 | [38,75,15]        |

Table 3.9‑4 WDR Strength 阈值调试参数

#### Damping Function

Damping功能用于解决WDR在场景变化时产生的闪烁问题。闪烁的根本原因是场景变化时采集帧和应用帧之间的差异，采集帧生成的曲线不会应用到应用帧中，曲线会逐帧变化。WDR damping对前后帧数据在时间域内的曲线进行平滑处理，以应对场景变化时画面的闪烁现象。

将dampMode置0，即采用manual mode时，dampCurveCoef和dampAvgCoef需要设置为大于0的值，才能保证WDR模块正常收敛和自动调节。将dampMode置1，即采用auto mode时，WDR会根据配置的WDR参数和画面的明暗分布情况自适应得计算dampCurveCoef和dampAvgCoef数据。

WDR damping相关的参数见Table 3.9-5.

| **Parameter**    | **Type** | **Range**  | **Description**                                              | **Default Value** |
| ---------------- | -------- | ---------- | ------------------------------------------------------------ | ----------------- |
| dampMode         | int      | {0,1}      | 0: Manual mode (damping coefficient can be  configured directly)   1: Auto mode (damping coefficient is  calculated adaptively according to the detection result of scene change) | 0                 |
| dampCurveCoef    | int      | [0,127]    | The damping parameter of the local curve.  (manual mode valid)   The larger the value, the faster the image brightness  converges. | 127               |
| dampCurveMax     | int      | [0,127]    | Limit of curve damping coefficient (auto mode)               | 127               |
| dampCurveMin     | int      | [0,127]    | Limit of curve damping coefficient (auto mode)               | 0                 |
| dampAvgCoef      | int      | [0,127]    | Block mean luma damping coefficient (manual  mode)           | 127               |
| dampAvgMax       | int      | [0,127]    | Limit of block mean luma damping coefficient  (auto mode)    | 127               |
| dampAvgMin       | int      | [0,127]    | Limit of block mean luma damping coefficient  (auto mode)    | 0                 |
| dampCoefDecLimit | int      | [0,127]    | Single step change limit of damping  coefficient (auto mode) | 127               |
| dampCoefIncLimit | int      | [0,127]    | Single step change limit of damping  coefficient (auto mode) | 127               |
| dampFilterSize   | int      | [0,16]     | Reference frame number for scene change  detection (auto mode) | 8                 |
| dampLothrLog     | float    | [0.0,20.0] | Threshold for scene change detection (auto  mode)   The higher the value, the faster the video  brightness converges. | 0                 |
| dampHithrLog     | float    | [0.0,20.0] | Refer to the previous row                                    | 12                |

Table 3.9‑5 WDR Convergence 调试参数

#### Halo Color Fading

此功能应用于HSV颜色空间，主要通过调整饱和度阈值和6种纯色（红色、绿色、蓝色、黄色、青色、品红色）的参数来调整单个像素的饱和度。这6种纯色将整个颜色空间分为6个间隔。如果一个像素落在某个间隔内，它将仅根据其相邻的两个色相参数调整。如在Figure 3.9‑7中，点a处只有R和Y参数是有效的。

![image-20240905210927110](./_static/_images/isp_tuning/image-20240905210927110.png)

Figure 3.9‑7 WDR预处理图

| **Parameter**         | **Type** | **Range**  | **Description**                                              | **Default Value** |
| --------------------- | -------- | ---------- | ------------------------------------------------------------ | ----------------- |
| lightEnable           | int      | {0,1}      | 0: Halo color fading  function disable   1: Halo color fading  function enable | 0                 |
| lightSatLothr         | int      | [0,255]    | The low threshold of  the saturation.   pixel_sat ≤ lothr:  the pixel is at low saturation, no need to desaturate.   lothr < pixel_sat  ≤ hithr: transition interval   pixel_sat > hithr:  the pixel is at high saturation, need to desaturate. | 64                |
| lightSatHithr         | int      | [0,255]    | The high threshold of  the saturation.                       | 128               |
| lightRedThrLog[4]     | float[4] | [0.0,20.0] | Red threshold,  monotonically increasing Logarithmic domain (same below) | [0,0,0,0]         |
| lightGreenThrLog[4]   | float[4] | [0.0,20.0] | Green threshold,  monotonically increasing                   | [0,0,0,0]         |
| lightBlueThrLog[4]    | float[4] | [0.0,20.0] | Blue threshold,  monotonically increasing                    | [0,0,0,0]         |
| lightYellowThrLog[4]  | float[4] | [0.0,20.0] | Yellow threshold,  monotonically increasing                  | [0,0,0,0]         |
| lightCyanThrLog[4]    | float[4] | [0.0,20.0] | Cyan threshold,  monotonically increasing                    | [0,0,0,0]         |
| lightMagentaThrLog[4] | float[4] | [0.0,20.0] | Magenta threshold,  monotonically increasing                 | [0,0,0,0]         |

Table 3.9‑6 WDR Halo Color Fading调试参数

当像素的饱和度达到调整阈值时，也会考虑其相邻的纯色参数。单个色相分为5个段：

- pixel_value\<=thr\[0\]：去饱和比例为零，用于保护低饱和度的像素。

- thr\[0\]\<pixel_value\<=thr\[1\]：像素值越大，去饱和比例越大，可用于过渡以消除紫边效应。

- thr\[1\]\<pixel_value\<=thr\[2\]：去饱和比例为1，可用于降低饱和度。

- thr\[2\]\<pixel_value\<=thr\[3\]：像素值越大，去饱和比例越小；可用于增加光晕颜色的衰减，形成颜色吸收效应。

- pixel_value\>thr\[3\]：去饱和比例为零，用于保护光源中心颜色。

为了保持颜色的单调性，通常将color_thr\[0\]和color_thr\[1\]设置为0。然而，如果需要使用此函数来实现减少紫边的效果，则需要将color_thr\[2\]和color_thr\[3\]设置为最大值（20）。

![图片1.png](_static/_images/isp_tuning/image50.png)

Figure 3.9‑8 WDR高亮颜色抑制原理图

#### Highlight Supression

为了应对夜间有光源场景，增加了高光抑制功能。使用局部直方图的有效范围来识别光源。ISP_WDR5_HLC_CTRL配置来调整局部直方图曲线。

该功能基于局部对比度计算当前块为高光区域的可能性。可能性越高，光线衰减的幅度越大。

| **Parameter** | **Type** | **Range**  | **Description**                                              | **Default Value** |
| ------------- | -------- | ---------- | ------------------------------------------------------------ | ----------------- |
| hlcBaseLog    | float    | [0.0,19.0] | Highlight compensation threshold (logarithmic  domain)  The higher the value, the fewer highlight blocks  are detected. | 0.0               |
| hlcSlope      | int      | [0,256]    | Highlight compensation strength  The higher the value, the stronger the highlight compensation. | 0                 |

Table 3.9‑7 WDR High Light Supression调试参数

## Green Equalization（GE）

### Overview

GE模块是为了平衡原始 Bayer 格式中相邻像素gr和gb之间的差异，纠正两个像素之间的不平衡。校正imbalances可以减少在demosaic插值算法产生的方格或其它类似pattern，还可以改善demosaic算法中的false color调试效果。Figure 3.10‑1 绘制了如何识别imbalance：

![](_static/_images/isp_tuning/image51.png)

Figure 3.10‑1 GrGb Imbalance 示意图

现在的Sensors很少出现Green imbalance了，意味着默认的Green equalization值是可以接受的。比较老一点的Sensors和差一点的Sensors可能需要做Tuning。

无论如何，GE模块都需要验证，其过程如下:

- 第一阶段：不需要tuning GE。

- 第二阶段：GE在tuning demosaic之前要进行验证。

- 第三阶段：不需要tuning GE。

### Tuning Theory

**GE模块关键参数**

GE模块参数包含在VTunerClient中Green Equilibration中，参数具体描述见下表。

| **Parameter** | **Type** | **Range** | **Description** | **Default Value** |
|----|----|----|----|----|
| enable        | bool     | {true, false} | Eenable/disable GE module                             | true              |
| threshold     | float    | \[0,511\]     | The larger the threshold, the stronger the processing | 2.5               |

Table 3.10‑1 GE Tuning Prameters.

### Tuning GE during phase two

因为GE在第一阶段是不校正的，Tuning在第二阶段的Demosic之前。Tuning所需的先决条件如下

| **Prerequisite** | **Status / value** |
| :--------------: | :----------------: |
|   Black level    |       Tuned        |
|  Noise proflie   |      Derived       |

Table 3.10‑2 GE prerequisite

如果Green imbalance有问题，增加GE_threshold参数。可在.json文件中设置值。在第三阶段除非存在GE引入的问题，一般不需要重调试GE。

##  Defect Pixel Cluster Correction（DPCC）

### Overview

对各类高低端传感器，受生产工艺、外围电路、工作环境等因素影响，实际使用过程中不可避免会出现缺陷像素。缺陷像素可以通过以下方式来区分：

- 亮像素点Hot pixel：像素会持续保持高亮状态

- 黑像素点Dead pixel：像素会持续保持无光状态

- 伤像素点Weak pixel：像素不会按照线性方式来对外界光线做出反应

不同的缺陷像素对画面的影响也不一样，黑像素对画面质量影响较少，伤像素比较难以预测。DPC功能则主要用来处理比较容易觉察到的亮像素。针对亮像素的处理，其复杂度跟亮像素间的邻近程度有所不同，因此将这些情况做了分类：

- 单亮像素（Single hot pixel）：单独的亮像素其周边都是正常像素

- 邻近亮像素（Double hot pixel）：同一个色彩平面上的两个邻近的亮像素点

- 三个亮像素（Triple hot pixel）：同一个色彩平面上三个邻近的亮像素点

- 亮像素团（Cluster of hot pixels）：同一个色彩平面上四个或大于四个亮像素点相邻

DPCC的调试过程如下：

- 第一阶段：不需要调试

- 第二阶段：确认下静态（Static）DPC 状态，在实验室环境下进行多场景调试DPC

- 第三阶段：无调试要求，除非DPC调试效果或其他依赖DPC模块的调试降低了图像质量

### Tuning Theory

缺陷像素群集校正（DPCC）检测并校正原始拜耳图像数据上的单个像素和小群集缺陷（最多3x3像素），即脉冲噪声。集成的缺陷像素表允许独立于即时检测，独立地校正多达2048个固定位置。实际分析显示在同一平坦区域，残留影响会随着缺陷像素的增加而增加。这种残留影响是因为周边像素平均化处理引起，缺陷像素越多影响就越大。因此如果图像中包含有很多亮像素团，需要跟CMOS sensor厂家确认并改善，这会极大的影响图像效果。

DPCC模块执行静态缺陷像素表控制、动态缺陷像素检测、缺陷像素矫正三项任务。

**静态缺陷像素**

将bptEnable置为true，bptNum设置需要矫正的静态缺陷像素数目，bptPosX/bptPosY配置静态缺陷像素的坐标值将该像素标记为坏点。若bptNum小于配置的bptPosX/bptPosY坐标组数，则只有bptNum设置数目的坏点会被矫正。

bptOutMode决定了静态缺陷像素采用的矫正方式，详细可见表中此参数的描述说明。

**动态缺陷像素检测**

DPCC模块会根据5×5邻域内像素的像素值、像素值排名、像素值差距、梯度排名、梯度极值5个角度评估中心像素是否属于坏点。采用哪几种评估方式和基于哪个通道进行评估可通过methodsSet和setUse参数配置，详细配置逻辑可见表中两个参数的描述说明。

**缺陷像素校正 ** 

缺陷像素的校正方式通过outMode参数控制，主要调节校正计算时各通道是否采用中心像素进行中值计算，详细配置逻辑可见表中此参数的描述说明。

DPCC模块参数包含在VTunerClient中Defect Pixel Cluster Correction 中，参数具体描述见下表。

| **Parameter**    | **Type**  | **Range**               | **Description**                                              | **Default Value**       |
| ---------------- | --------- | ----------------------- | ------------------------------------------------------------ | ----------------------- |
| enable           | bool      | {true, false}           | Enable/disable DPCC                                          | false                   |
| bptEnable        | bool      | {true, false}           | Enable static bad point correction                           | false                   |
| bptNum           | int       | [0,1024]                | The number of static bad points                              | 0                       |
| bptOutMode       | int       | [0,15]                  | Output mode for static bad-point correction.  bptOutMode is a binary parsed parameter, with the  following digits and corresponding functions: The first bit determines the  G-channel. When using median filtering to calculate the correction value,  whether the median filtering range includes the center point, 1 indicates yes  and 0 indicates no.  The second bit determines the RB channel.When  using median filtering to calculate the correction value, whether the median  filtering range includes the center point, 1 indicates yes and 0 indicates  no.  The third bit determines the G-channel. When using  median filtering to calculate the correction value, whether the median  filtering range uses all the same channel points within the 5x5 range, with 1  indicating yes and 0 indicating no.  The fourth bit determines the RB channel. When  using median filtering to calculate the correction value, whether the median  filtering range uses all the same channel points within the 5x5 range, with 1  indicating yes and 0 indicating no. | 0                       |
| bptPosX[2048]    | int[2048] | [0, input_image_width]  | The x-coordinate of the static bad point                     | [0]                     |
| bptPosY[2048]    | int[2048] | [0, input_image_height] | The y-coordinate of the static bad point                     | [0]                     |
| outMode          | int       | [0,15]                  | Interpolation mode for correction unit outMode is  a binary parsed parameter, with the following digits and corresponding  functions:  The first bit determines the G-channel. When using  median filtering to calculate the correction value, whether the median  filtering range includes the center point, 1 indicates yes and 0 indicates  no.  The second bit determines the RB channel. When  using median filtering to calculate the correction value, whether the median  filtering range includes the center point, 1 indicates yes and 0 indicates  no.  The third bit determines the G-channel. When using  median filtering to calculate the correction value, whether the median filtering  range uses all the same channel points within the 5x5 range, with 1  indicating yes and 0 indicating no.  The fourth bit determines the RB channel. When  using median filtering to calculate the correction value, whether the median  filtering range uses all the same channel points within the 5x5 range, with 1  indicating yes and 0 indicating no. | 0                       |
| setUse           | int       | [0,15]                  | DPCC methods set usage for detection  The first bit determines whether the entire set of  parameters for stg1 is enabled.  The second digit determines whether the entire set  of parameters for stg2 is enabled.   The third digit determines whether the entire set  of parameters for stg3 is enabled.  Its fourth position is determining stg_ Whether  the entire set of parameters for fix is enabled, that is, whether a built-in  judgment mechanism is enabled. | 1                       |
| methodsSet[3]    | int[3]    | [0,8191]                | Methods enable bits for SET_1/2/3, different  methods can be used in parallel, the result is the logical AND of all  selected methods.  methodsSet is a 13-bit numerical value that needs  to be viewed in binary.  For all bits, 1: enabled; 0: disabled.  Its lower 5 bits determine the activation of the  five bad point detection methods for the G channel.  The lowest bit determines whether the PG (peak  gradient) method of the G channel is enabled.  The second digit determines whether the LC method  of channel G is enabled.  The third digit determines whether the RO method  of channel G is enabled.  The fourth digit determines whether the RND method  of channel G is enabled.  The fifth digit determines whether the RG method  of the G channel is enabled.  The 9th to 13th positions determine the five  methods for opening the RB channel.  The 9th digit determines whether the PG (peak  gradient) method of the RB channel is enabled  The 10th digit determines whether the LC method of  the RB channel is enabled.  The 11th bit determines whether the RO method of  the RB channel is enabled.  The 12th digit determines whether the RND method  of the RB channel is enabled.  The 13th digit determines whether the RG method of  the RB channel is enabled. | [1, 7453, 0]            |
| lineThresh[2][3] | int[2][3] | [0, 255]                | Line threshold methods, 3 thresh for RB and G                | [[0, 0, 0],  [0, 0, 0]] |
| lineMadFac[2][3] | int[2][3] | [0,63]                  | Mean Absolute Difference (MAD) factor for Line  check        | [[0, 0, 0],  [0, 0, 0]] |
| pgFac[2][3]      | int[2][3] | [0,63]                  | Peak gradient factor                                         | [[0, 0, 0],  [0, 0, 0]] |
| rndThresh[2][3]  | int[2][3] | [0, 255]                | Rank Neighbor Difference threshold                           | [[0, 0, 0],  [0, 0, 0]] |
| rgFac[2][3]      | int[2][3] | [0,63]                  | Rank gradient factor                                         | [[0, 0, 0],  [0, 0, 0]] |
| roLimits[2][3]   | int[2][3] | [0,3]                   | Rank Order Limits                                            | [[0, 0, 0],  [0, 0, 0]] |
| rndOffs[2][3]    | int[2][3] | [0,3]                   | Differential Rank Offsets for Rank Neighbor  Difference      | [[0, 0, 0],  [0, 0, 0]] |

Table 3.11‑1 DPCC Tuning Paramers

### Tuning DPC during phase two

第一阶段不需要调试DPC模块，相关的调试在第二阶段进行。调试前需要首先进行参数的预设，完成相关模块的调试。参数的预设可以采用两种方式：

方式一：参照Table 3.11‑1中的默认配置。

方式二：在预设6组参数中选择一组，在此基础上进行调试，生成新的配置。

**调试流程**

1.  将摄像头对准实验室搭建的场景中，如下图。在VTunerClient中将曝光设定成Manual模式。

![C:\Users\xiaonan.ma\Documents\WeChat Files\cnjatfm\FileStorage\Temp\8afa906d75638001a96b51c7265e829.jpg](_static/_images/isp_tuning/image52.jpeg)

Figure 3.11‑1 Example of a studio scene

2.  通过将enable设置为1开启DPCC功能，按表格中默认参数进行配置，观察画面中缺陷亮像素分布。

3.  若在当前参数下仍能观察到缺陷像素，可通过减小lineMacFac/lineThresh/rndThresh/rgFac，增大roLimits/pgFac的值，可按数值取值范围的10%左右数值做调试尝试，直至观察不到缺陷像素。

4.  缩小调整步长，逐步精调各参数，直到能够成功移除缺陷像素，此时即为移除缺陷像素的参数阈值，可按实际需求再做微调，直至当前gain下调试的DPCC满足规格，则保存对应的配置参数。

5.  重复步骤3-4，调整所有的Gain下的DPCC的参数

### Fine tuning DPC during phase three

对DPC模块fine 调试， 完成不同增益下DPCC模块参数调试后，将对应的参数表写入到对应的参数表中。在实际应用场景中发现依然有坏点存在，则基于对应的场景微调对应Gain下的参数配置。

##  2DNR

### Overview

2D Noise Reduction (2DNR)模块用于降低RAW图像中的空间噪声。该模块是ISP的关键组成部分，因为它显著提高了图像的质量，特别是在低光条件下拍摄的图像。2DNR模块会在高、中、低三个层中分别进行滤波处理后，输出最终结果。

2DNR可以分解为滤波处理、细节增强、Luma control、motion blending四大部分功能。

调试流程大致如下：

- 第一阶段：无需调整。

- 第二阶段：在实验室实景环境中，对2DNR的参数进行调整。

- 第三阶段：针对实际场景调整的2DNR参数，以达到尽可能适应所有场景的状态。该阶段主要调整在不同Gain值条件下2DNR的配置参数。

### Tuning Theory

#### NLM Processing

本模块采用非局部均值（Non-Local Means，NLM）算法，在较大的搜索窗口内寻找与当前像素点具有相似特征的点集。通过计算这些点的加权平均值，利用类似高斯分布的权重函数对所有相似像素块进行累积，以此达到消除图像中原始像素块的随机噪声，从而有效提升图像的信噪比（Signal-to-Noise Ratio，SNR）。

2DNR处理过程中，为了最大化算法性能，需要使用相机的噪声配置文件（Noise Profile）。在客观标定阶段，必须准确地标定不同增益条件下的噪声配置文件。这对于确保算法能够根据实际噪声水平适当地调整其处理策略，以优化图像质量至关重要。补充NR TOOL使用说明

2DNR处理流程图：

![](_static/_images/isp_tuning/image53.png)

Figure 3.12‑1 2DNR处理流程图

2DNR模块参数包含在VTunerClient中2D Noise Reduction中。

**注：在此表中，layer 0 指细节层，layer 1 指中等细节层，layer 2 指粗略信息层。**

| **Parameter**        | **Type** | **Range**      | **Description**                                              | **Default**  **Value** |
| -------------------- | -------- | -------------- | ------------------------------------------------------------ | ---------------------- |
| enable               | int      | [0,1]          | 0: disables 2DNR .  1: enables 2DNR .                        | 0                      |
| vstFactor            | float    | [1.0, 1000.0]  | A factor to control the sigma of the decompose  filter.   The greater the factor, the larger the  decompose sigma. | 16                     |
| motionCtrlEn         | int      | [0,1]          | 0: bypasses motion adaptive 2DNR.  1: enables motion adaptive 2DNR. | 1                      |
| sigmaFactorMotionMin | int      | [0, 1024]      | The minimum 2DNR threshold.   For pixels with motion less than this  threshold, 0% 2DNR is applied. | 0                      |
| sigmaFactorMotionMax | int      | [1, 1024]      | The maximum 2DNR threshold.   For pixels with motion greater than this  threshold, 100% 2DNR is applied. | 800                    |
| sigmaScale[3]        | float[3] | [0.001, 100.0] | The sigma factors for layer 0, layer 1, and  layer 2 in order.  A greater sigma factor makes the corresponding  layer smoother. | [1.0, 1.0, 1.0]        |

Table 3.12‑1 2DNR NLM调试参数

#### Luma Control

lumaCurve是2DNR处理中的一个关键功能，它根据像素值的亮度进行降噪处理。在此过程中， lumaCurveX 和lumaCurveY参数配合使用，以根据像素的亮度值调整降噪强度。具体来说，lumaCurveY参数的值越高，表示应用的降噪强度越弱。这允许在保持图像细节的同时，有效降低噪声。

lscCompCurve用于根据像素当前位置与图像中心的距离进行降噪处理。该曲线的设计使得图像边缘区域的降噪强度可以根据距离中心的远近进行调整。lscCompCurve对应的值越高，降噪强度越弱，其中值1024相当于乘数1.0。这意味着，当lscCompCurve的值为1024时，降噪处理不会增强也不会减弱。

这两个曲线参数的正确设定对于实现高质量的图像降噪至关重要。用户应根据具体的图像内容和预期的降噪效果来调整这些参数。

| **Parameter**              | **Type** | **Range** | **Description**                                              | **Default**  **Value**                                       |
| -------------------------- | -------- | --------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| lumaCtrlEn                 | int      | [0, 1]    | 0: bypasses luma adaptive 2DNR.  1: enables luma adaptive 2DNR. | 1                                                            |
| lscGainCompEn              | float    | [0, 1]    | 0: disables gain  compensation for lens shading compensation (LSC).  1: enables gain  compensation for LSC. | 0                                                            |
| lumaCurveX[12]             | int[12]  | [0,4095]  | The luma control  curve in SNR.  Based on this curve,  the local SNR sigma is adjusted according to the luma value of each pixel.  The greater the value  of lumaCurveY, the weaker the SNR denoising effect. Value 256 leads to the  same SNR denoising effect as when lumaCtrlEn is set to 0 to disable luma  control.  lumaCurvePx indicates  the base 2 logarithm of the distance between adjacent X anchors specified by  is lumaCurveX. lumaCurvePx is reserved for compatibility and is usually not  used. | [0, 32, 64, 96, 128, 256, 512,  768, 1024, 1536, 2048, 4095] |
| lumaCurveY[12]             | int[12]  | [0,65535] | [256, 256, 256, 256, 256, 256,  256, 256, 256, 256, 256, 256] |                                                              |
| lumaCurvePx[12]考虑删      | int[12]  | [0,12]    | [0, 5, 5, 5, 5, 7, 8, 8, 8, 9,  9, 11]                       |                                                              |
| lscCompCurveX[12]          | int[12]  | [0,4095]  | The LSC gain  compensation curve in SNR.  Based on this curve,  the local SNR sigma is adjusted according to pixel coordinates.  The greater the value  of lscCompCurveY, the weaker the SNR denoising effect. Value 1024 leads to  the same SNR denoising effect as when lscGainCompEn is set to 0 to disable  gain compensation for LSC.  lscCompCurvePx  indicates the base 2 logarithm of the distance between adjacent X anchors  specified by is lscCompCurveX. lscCompCurvePx is reserved for compatibility  and is usually not used. | [0, 32, 64, 96, 128, 256, 512,  768, 1024, 1536, 2048, 4095] |
| lscCompCurveY[12]          | int[12]  | [0,65535] | [1024, 1024, 1024, 1024, 1024,  1024, 1024, 1024, 1024, 1024, 1024, 1024] |                                                              |
| lscCompCurvePx[12]  考虑删 | int[12]  | [0,12]    | [0, 5, 5, 5, 5, 7, 8, 8, 8, 9,  9, 11]                       |                                                              |

Table 3.12‑2 2DNR Luma Control调试参数

#### Moving&Static Booting

2DNR模块可以控制运动区域和静止区域细节的增强。

| **Parameter**                 | **Type**    | **Range**   | **Description**                                              | **Default**  **Value**                                |
| ----------------------------- | ----------- | ----------- | ------------------------------------------------------------ | ----------------------------------------------------- |
| motionFactorCurveX[12]        | int[12]     | [0, 1024]   | The motion control curve in SNR.   Based on this curve, the local SNR sigma is  adjusted according to the motion value of each pixel.   The greater the value of motionFactorCurveY, the  weaker the SNR denoising effect. Value 128 leads to the same SNR denoising  effect as when motionCtrlEn is set to 0 to disable motion control.   motionFactorCurvePx indicates the base 2 logarithm  of the distance between adjacent X anchors specified by is  motionFactorCurveX. motionFactorCurvePx is reserved for compatibility and is  usually not used. | [0, 4, 8, 16, 32, 64,  128, 192, 256, 384, 512, 1024] |
| motionFactorCurveY[12]        | int[12]     | [0, 65535]  | [1408, 1152, 1024,  896, 768, 640, 512, 437, 384, 309, 256, 128] |                                                       |
| motionFactorCurvePx[12]       | int[12]     | [0, 10]     | [0, 2, 2, 3, 4, 5, 6,  6, 6, 7, 7, 9]                        |                                                       |
| motionAnchorX[2]              | int[2]      | [0, 1024]   | The motion  thresholds.   Pixels with motion  less than motionAnchorX[0] are considered static and use static boost  parameters. Pixels with motion greater than motionAnchorX[1] are considered  moving and use moving boost parameters.   For pixels with  motion between motionAnchorX[0] and motionAnchorX[1], their boost threshold  and clip threshold are obtained through linear interpolation | [100, 600]                                            |
| staticDetailThresh[2][3]      | int[2][3]   | [0, 4095]   | The detail  suppression threshold for static pixels per layer per RGB channel.   For instance,  staticDetailThresh[0][1] indicates the threshold for static pixels at layer 0  for color channel 1.   Coefficients of  detail pixels that are less than the threshold are set to 0. | [[0, 0, 0], [0, 0,  0]]                               |
| staticDetailBoostThresh[2][3] | int[2][3]   | [0, 4095]   | The detail boosting  threshold for static pixels per layer per RGB channel.   For instance,  staticDetailBoostThresh[0][1] indicates the threshold for static pixels at  layer 0 for color channel 1. | [[4095, 4095, 4095],  [4095, 4095, 4095]]             |
| staticDetailBoost[2][3]       | float[2][3] | [1.0, 4.0]  | The detail boosting  factor for static pixels per layer per RGB channel.  For instance, if the  detail amount of static pixels at layer 0 for color channel 1 is greater than  staticDetailBoostThresh[0][1], the detail amount is multiplied by  staticDetailBoost[0][1]. | [[1.0, 1.0, 1.0],  [1.0, 1.0, 1.0]]                   |
| staticDetailClipThresh[2][3]  | int[2][3]   | [0, 4095]   | The detail boosting  clipping threshold for static pixels per layer per RGB channel. For instance,  staticDetailClipThresh[0][1] indicates the threshold for static pixels at  layer 0 for color channel 1.   The boosting value is  calculated as follows: boosting value = clip(boost_fac × (detail_input −  boost_thresh), clip_thresh) | [[4095, 4095, 4095],  [4095, 4095, 4095]]             |
| movingDetailThresh[2][3]      | int[2][3]   | [0, 4095]   | The detail  suppression threshold for moving pixels per layer per RGB channel.  For instance,  movingDetailThresh[0][1] indicates the threshold for moving pixels at layer 0  for color channel 1. Coefficients less than the threshold are set to 0. | [[0, 0, 0], [0, 0,  0]]                               |
| movingDetailBoostThresh[2][3] | int[2][3]   | [0, 4095]   | The detail boosting  threshold for moving pixels per layer per RGB channel.   For instance,  movingDetailBoostThresh[0][1] indicates the threshold for moving pixels at  layer 0 for color channel 1. | [[4095, 4095, 4095],  [4095, 4095, 4095]]             |
| movingDetailBoost[2][3]       | float[2][3] | [1.0, 4.0]  | The detail boosting  factor for moving pixels per layer per RGB channel.   For instance, if the  detail amount of moving pixels at layer 0 for color channel 1 is greater than  movingDetailBoostThresh[0][1], the detail amount is multiplied by  movingDetailBoost[0][1]. | [[1.0, 1.0, 1.0],  [1.0, 1.0, 1.0]]                   |
| movingDetailClipThresh[2][3]  | int[2][3]   | [0, 4095]   | The detail boosting  clipping threshold for static pixels per layer per RGB channel.   For instance,  staticDetailClipThresh[0][1] indicates the threshold for static pixels at  layer 0 for color channel 1.   The boosting value is  calculated as follows: boosting value = clip(boost_fac × (in − boost_thresh),  clip_thresh) | [[4095, 4095, 4095],  [4095, 4095, 4095]]             |
| staticFactor[3]               | float[3]    | [0.01, 1.0] | The sigma ratio of  fully static regions for each layer.   If this parameter is  set to 0.1, it means 0.1 × moving_sigma is applied to fully static pixels. It  helps keep fine details in the background. | [0.1, 0.1, 0.1]                                       |
| sigmaFactorMul[3]             | float[3]    | [0.1, 10.0] | The factor that  adjusts the decreasing speed of SNR sigma from moving to static for each  layer.   A greater value of  this parameter leads to stronger denoising effects in previously moving  regions. | [1.0, 1.0, 1.0]                                       |

Table 3.12‑3 2DNR Motion&Static Boot调试参数

**motionAnchorX参数说明：**

motionAnchorX参数用于区分像素在图像增强（boosting）过程中是属于静止状态还是运动状态。该参数包含两个关键阈值：motionAnchorX\[0\] 和 motionAnchorX\[1\]。

![](_static/_images/isp_tuning/image54.png)

Figure 3.12‑2 2DNR MotionAnchor 作用示意图

当像素的运动值（motion）小于motionAnchorX\[0\] 时，该像素被视为静止。在boosting过程中，将使用以下静止状态的boosting参数：

- 静态细节阈值（static detail thresh）

- 静态细节增强阈值（static detail boost thresh）

- 静态细节增强（static detail boost）

- 静态细节剪切阈值（static detail clip thresh）

当像素的运动值（motion）大于motionAnchorX\[1\] 时，该像素被视为运动。在boosting过程中，将使用以下运动状态的boosting参数：

- 运动细节阈值（moving detail thresh）

- 运动细节增强阈值（moving detail boost thresh）

- 运动细节增强（moving detail boost）

- 运动细节剪切阈值（moving detail clip thresh）

对于运动值位于motionAnchorX\[0\] 和 motionAnchorX\[1\]之间的像素，其threshold，boost threshold，boost和clip threshold参数将通过插值方法，基于静止和运动两套参数计算得到。

频率合成（Frequency Synthesis）根据像素的boosting参数进行，分为以下情况：

- 如果 abs(detail)小于 threshold，输出结果（out）为粗糙层（coarse）。

- 如果 abs(detail)大于threshold 且 abs(detail) 小于boosting threshold，输出结果（out）为粗糙层（coarse）加上细节层（detail）。

- 如果 abs(detail) 大于 boosting threshold，输出结果（out）为粗糙层（coarse）加上细节层（detail）乘以增强因子（boost factor），但不超过最大增强值（max boosting value）。

请根据您的具体算法和应用场景的要求，调整上述描述中的参数值。

![](_static/_images/isp_tuning/image55.png)

Figure 3.12‑3 2DNR Staitc&Moiton Detail Boost作用示意图

#### 2DNR and 3DNR Blending

2DNR算法在有效去除噪声的同时，也可能导致图像细节的损失。为了平衡降噪与保留细节之间的关系，算法通过区分静态和运动区域，对2DNR的应用进行不同的权重调整。每个像素的权重由其局部运动因子（motion factor）决定，并通过运动控制曲线（motion control curve）进行调整。

![](_static/_images/isp_tuning/image56.png)

Figure 3.12‑4 2DNR同MotionFactor关系图

局部SNR标准差调整：根据像素的运动值，通过运动控制曲线调整局部信噪比（SNR）的标准差。motionFactorCurveY 值较高时，表示应用了较弱的SNR降噪效果。当该值设为128时，相当于乘数1.0，即不增强也不减弱降噪效果。

静止区域的像素处理：

![image-20240905211226800](./_static/_images/isp_tuning/image-20240905211226800.png)

完全运动区域的像素处理：

![image-20240905211237042](./_static/_images/isp_tuning/image-20240905211237042.png)

介于静止和运动区域的像素处理：

![image-20240905211408713](./_static/_images/isp_tuning/image-20240905211408713.png)

![](_static/_images/isp_tuning/image57.png)

Figure 3.12‑5 Static&Motion 2DNR Blending示意图

![image-20240905211448961](./_static/_images/isp_tuning/image-20240905211448961.png)

Table 3.12‑4 2DNR&3DNR Blending调试参数

### Tuning 2DNR during phase two

由于2DNR的调试不依赖Sensor的特性，因此，调试从第二阶段开始的。在完成下表中先决条件后，可进入调试流程。

|      **模块**      | **状态 / 值** |
| :----------------: | :-----------: |
|    Black level     |     Tuned     |
|        DPC         |     Tuned     |
| Green equalization |     Tuned     |
|      Demosaic      |     Tuned     |
|        3DNR        |     Tuned     |
|    noise proﬁle    |      set      |

Table 3.12‑5 2DNR先决条件

调试2DNR的实景中，需要包含ColorChart、各种纹理摆件、各种颜色的纹理、平坦区及ISP12233 卡，利于有效观察2DNR模块对各类目标物和区域的影响。

**调试流程**

调试2DNR的大致流程图如Figure 3.12‑6所示。 将2DNR模块调试出符合要求的参数，需要通过处理和分析大量包含不同内容、不同细节和亮度的图片并对其做出主客观的判断。一般来讲，在低增益条件下，使用较小的2DNR threshold值，来保留图片中的纹理和细节；在高增益条件下，需要增加2DNR threshold值，以达到降噪的目的。

![](_static/_images/isp_tuning/image58.png)

Figure 3.12‑6 2DNR调试流程图

**2DNR Filtering处理过程**

1.  相似Block搜索

利用和绝对差（Sum of Absolute Differences, SAD）比较搜索Block和中心Block的相似度。

2.  Block权重计算转化

> 利用类高斯的递减曲线将SAD转化为Block权重。

Sigma计算：

![image-20240905211527593](./_static/_images/isp_tuning/image-20240905211527593.png)

> 其中sigma值越大，曲线越平缓，滤波效果越强，且趋近于均值滤波。vstFactor 决定sigma，sigmaScale决定各层（layer）的sigma放大系数。

3.  Sigma Factor计算

![image-20240905211539447](./_static/_images/isp_tuning/image-20240905211539447.png)

> 该因子综合考虑亮度、运动及LSC补偿三个方面因素来修正SAD。

亮度：

![image-20240905211605775](./_static/_images/isp_tuning/image-20240905211605775.png)

运动：

- 如果motion小于 sigmaFactorMotionMain，则motion_factor等于staticFactor。

- 如果motion大于sigmaFactorMotionMax，则motion_factor等于64。

- 否则，motion_factor = LUT lookup(snr_motion_curve, motion_frame\[i,j\]) \* sigma_factor_mul

4.  Isc增益

![image-20240905211620728](./_static/_images/isp_tuning/image-20240905211620728.png)

5.  Block权重的确认

Block在weight curve中的位置

![image-20240905211629239](./_static/_images/isp_tuning/image-20240905211629239.png)

> sigma_offset设置了一个相对于SAD的阈值，SAD小于它的Block会获得最大的权重。上述因子越大，最终得到的SAD越大，滤波强度越小。

6.  计算最终Block的权重

根据权重对各Block进行加权平均，以确定最终的Block权重。

**注：SNR值是一个评估噪声的指标，但是不能反映人眼感知到的噪声和细节，因此不能用于主观分析。**

由于2DNR调试存在很大的主观性，可将其分解成不同的子模块，各子模块可单独调试。调试的基础流程为：

1.  按照Table 3.12‑6设置2DNR的默认参数

| **Parameter** | **Default** |
|:--:|:--:|
|    Driver_load    |                            False                             |
|       Sigma       |                              5                               |
| Pregamma_strength |                              1                               |
|   Luma_curve_x    | \[0, 32, 64, 96, 128, 196, 256, 512, 768, 1024, 2048, 4096 \] |
|   Luma_curve_y    | \[256, 256, 256, 256, 256, 240, 210, 180, 150, 200, 256, 256 \] |

Table 3.12‑6 2DNR默认参数

2.  将Enable设置成0，禁用2DNR模块且在Total Gain为1x时，拍摄一组包含ColorChecker的实景图片。

3.  使用Imatest分析Patch22的SNR值，对应下图第四个点的值。此值将作为使能2DNR后，测量SNR参考值。基于SNR值对2DNR参数调整流程如下：

![](_static/_images/isp_tuning/image59.png)

Figure 3.12‑7 Imatest ColorChecker SNR输出

1)  将Enable设置成 1，观察并核对图像效果。认真观察输出图片上纹理细节的变化及核对SNR值前后的变化。

2)  不满足设定SNR要求则重新调整vstFactor值，直到满足预期的SNR的需求

3)  SNR基本达到要求后，进一步判断图片中噪声和细节表现能否符合要求。若不满足则调整高中低频域对应的sigmaScale的值

4)  观察画面中不同亮度区域、中心到边角区域及运动区域噪声状态是否符合要求。若不符合，则调整lumaCurve、motionFacCurve及lscCurveY的值，直到满足要求。

5)  调整环境亮度到不同倍率的Gain，重复步骤2)-4)，进行2DNR参数的调整。

**Motion Blending**

依据Motion的强弱，动态调整2DNR的强度。运动越剧烈，2DNR强度增强，3DNR强度减弱，达到提升信噪比的同时降低运动区域的运动伪影。

**Verification**

调整完了上面说明的所有参数后，在实景实验室拍摄不同Gain下的照片，并通过Imatest的ColorChecker模块对照片进行分析。如果SNR值和细节纹理的表现均符合要求，2DNR可进入到第三阶段的调试。如果没有，则重复上面的步骤，直到满足要求为止。

**其它调试信息**

可以Table 3.12-7中数据作为SNR值的参考值。Figure 3.12‑8展示的是SNR值 \> 40时的实际效果图，从图片中可以看出，噪声和纹理都得到了很好的保留。

![](_static/_images/isp_tuning/image60.png)

Figure 3.12‑8 2DNR 调试实景示意图

| **D65 1x gain条件参考** | **卤素灯 系统最大Gain** |
| :---------------------: | :---------------------: |
|      Good: 40 - 50      |       Good: 25-35       |
|      Fair: 35 - 40      |      Fair: 15 - 25      |
|       Poor: \< 35       |       Poor: \< 15       |

Table 3.12‑7 SNR的目标值

在调试过程中，噪声和纹理细节的表现，结合具体需求找出合适的平衡点。但在多数条件下，要避免图片中出现过多噪声的极端参数。

### Fine tuning 2DNR phase three

在第二阶段，完成不同Total Gain下参数的调整后，继续进入到第三阶段的调试。ISP Pipeline中其它模块也会对2DNR的调整产生影响。因此，为能使在每个gain条件下都能得到较为均衡的图像效果，需要按照配置的gain lut一起调整DPC、2DNR、3DNR、Demosaic及EE模块。

最新的Sensor在良好的光照条件/1x Gain条件下，几乎看不到噪声。在这种情况下，需要将照度降低到一定程度，使Gain增加，直到画面中出现可见噪声为止。对于无可见噪声的增益条件下，保持较小的强度设定组合。

##  3DNR

### Overview

3DNR 基于边缘/运动检测方法的空域去噪（非局部均值滤波器）和时域去噪。非局部滤波器主要用于消除静态区域的噪声，时域滤波用于消除移动物体上的噪声。3DNR中的运动检测模块，可以区分处运动区和非运动区。时域滤波和空间去噪分别作用于运动区和静态区。中间过渡区域可使用空间滤波和时域滤波融合更加平滑的输出结果，最终生成去噪帧。

静态区域，使用更多的参考值作为tnr_out，否则我们使用当前值。在处理计算运动区域时，不仅考虑motion_frame，还考虑motion_history（从内存中读取的运动参考）。

3DNR部分包含下面的子功能：Motion detection(运动检测)，Motion dilation(运动膨胀)，Motion Mask Blending，参考帧Blending，NoiseProfile标定。

下面是对调试过程的简要描述：

第一阶段：标定模组的NoiseProfile。

第二阶段：实验室实景环境，调整适配3DNR强度和Motion参数。

第三阶段：针对实际场景调整的3DNR参数，以达到尽可能适应所有场景的状态。该阶段主要不同Gain值条件下调整3DNR的参数。

### Tuning Theory

整个3DNR模块的处理流程图下图：

![](_static/_images/isp_tuning/image61.png)

Figure 3.13‑1 3DNR处理流程图

3DNR模块参数包含在VTunerClient中2D Noise Reduction中，调试参数具体描述参照下表。

| **Parameter**  | **Type** | **Range**    | **Description**                                              | **Default**  **Value** |
| -------------- | -------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| enable         | int      | [0,1]        | 0: bypasses 3DNR v4.   1: enables 3DNR v4.                   | 0                      |
| tnrEn          | int      | [0,1]        | 0: bypasses temporal noise reduction (TNR).   1: enables TNR. | 1                      |
| nlmEn          | int      | [0,1]        | 0: bypasses spatial noise reduction (SNR).   1: enables SNR  | 1                      |
| motionDilateEn | int      | [0,1]        | 0: disables motion dilation.   1: motion dilation.           | 0                      |
| gaussBlurEn    | int      | [0,1]        | 0: disables Gaussian blur before motion  detection.   1: enables Gaussian blur before motion  detection. | 0                      |
| noiseModelEn   | int      | [0,1]        | 0: disables the noise model curve.   1: enables the noise model curve. | 1                      |
| inputBits      | int      | {20,24}      | The bit depth of the noise model curve.                      | 20                     |
| noisemodelA    | double   | [0.1, 100]   | The slope of the noise model curve.   This parameter is calibration data used to  calculate the noise curve by the driver. | 0.3                    |
| noisemodelB    | double   | [0.1, 10000] | The offset of the noise model curve.   This parameter is calibration data used to  calculate the noise curve by the driver. | 1.5                    |

Table 3.13‑1 3DNR基础配置参数

**Temporal Filtering的计算过程**

1.  历史参考帧长度计算

计算reference迭代更新时的factor update：

![image-20240905211732934](./_static/_images/isp_tuning/image-20240905211732934.png)

filterLen越大，thr_update越大。决定历史窗口长短，历史时间窗口越长，时域噪声去除效果越好。

2. TNR结果计算

   ![image-20240905211744542](./_static/_images/isp_tuning/image-20240905211744542.png)

NR4中detail和coarse层会分别单独做时间滤波，并通过tnr strength和tnr_strength2配置与tnr_in的回加。

3.  更新历史motion信息

![image-20240905211757332](./_static/_images/isp_tuning/image-20240905211757332.png)

filterLen2越大，motion_thr_update越大。影响运动过渡区域的效果，主要因为不同motion运动强度作用2DNR强度不一样。

#### Motion Detection

运动检测模块的设计是依据参考帧和当前帧原始的中低频数据，通过SAD和块均值两种类型差异值来推算运动检测结果。块差异计算是在RGB域完成的。

![](_static/_images/isp_tuning/image62.png)

Figure 3.13‑2 3DNR Motion Detection处理流程图

**Motion Detection处理步骤**：

1.  Pre-processing

参数gaussBlurEn用于决定是否对图像进行高斯模糊的预处理。当该参数启用时（即 gaussBlurEn 设为 true），图像将先经过高斯模糊处理，以减少噪声干扰并改善后续处理步骤的效果。

高斯模糊的强度由参数 motionSmoothFactor控制，该参数决定了高斯核的标准差（sigma）。motionSmoothFactor 的值越大，应用于图像的高斯模糊效果越明显，从而在平滑图像的同时，也更强烈地抑制了高频噪声。通常，motionSmoothFactor 的值需要根据具体的应用场景和图像实际效果进行调整。

2.  Calculate block difference。

计算当前帧与参考帧之间的块差异（Block Difference），本算法支持两种可配置的差异计算方法。用户可通过参数diffType指定采用以下两种方法中的哪一种。

diffType = 0:

![image-20240905211817148](./_static/_images/isp_tuning/image-20240905211817148.png)

diffType = 1:

​	diff1:对diff0平方的估计值，即平方后右移sqrDiffFactor决定的位数

diffType参数的设定将直接影响差异计算的结果，因此应根据实际应用场景选择。

3.  Motion Classifier

通过两个关键参数 “t1” 和 “t2”来分类图像区域的运动状态。参数 “t1” 定义了完全静止状态的阈值，而 “t2” 和 “t1” 的差值（t2 - t1）定义了运动与静止之间的过渡区域。

参数 “t1” 的值通过 tnrLumaCurveY的插值计算得到。当 “t1” 的值增大时，系统将更多的区域分类为完全静止，相应地，被分类为完全运动的区域减少。

（t2 - t1）的值通过 tnrMotionSlopeY的插值计算得到。当 ( t2 - t1 ) 的值减小时，表示过渡区域的范围缩小，从而使得图像中的运动区域与静止区域之间的界限更加明确。

这两个参数的设定对于运动检测的准确性和图像处理的最终效果至关重要。用户应根据实际的图像内容和预期的处理效果来调整t1和 ( t2 - t1 ) 的值。

![image-20240905211817148](./_static/_images/isp_tuning/image63.png)

Figure 3.13‑3 3DNR Motion Detection处理流程图

4.  Motion Mask后处理

后处理步骤提供两种模式，由参数 “motionSmoothLvl” 控制：

当motion_smooth_Lvl = 1时，将对 motion mask应用中值滤波（Median Filter）。这种处理方式能有效去除噪点，保留边缘信息，但对图像的平滑程度有限。

当motion_smooth_LVL = 0时，后处理流程更为复杂。首先，对 motion mask进行下采样（Downsampling），以减少数据量并消除细微噪声。接着，应用中值滤波处理，最后通过上采样（Upsampling）恢复原始尺寸。使得 motion mask 的平滑效果更加显著，适用于需要强烈平滑处理的场景。

用户应根据具体的图像特性和处理需求选择合适的后处理模式。运动检测相关的调试参数如下。

| **Parameter**       | **Type** | **Range**     | **Description**                                              | **Default**  **Value**                                       |
| ------------------- | -------- | ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| fixCurveStart       | int      | [0, 4096]     | The curve linearity protection in dark areas,  which defines the first non-zero X value of the variance stabilization  transformation (VST) curve. | 256                                                          |
| blsExp[4]           | Int[4]   | [0, 1048575]  | The black level subtraction (BLS) values for  images expanded by the noise model. | [0,0,0,0]                                                    |
| vstFactor           | double   | [1.0, 1000.0] | A factor to control the sigma of the decompose  filter.  The greater the factor, the larger the  decompose sigma. | 16                                                           |
| tnrStrength         | int      | [0, 128]      | The output strength of denoised detail.   If this parameter is set to 0, TNR is disabled  and the input image is output.   If this parameter is set to 128, TNR is  maximized and the TNR result is output. | 128                                                          |
| tnrStrength2        | int      | [0, 128]      | The output strength of denoised coarse.  If this parameter is set to 0, TNR is disabled  and the input image is output.   If this parameter is set to 128, TNR is  maximized and the TNR result is output. | 128                                                          |
| filterLen           | int      | [1, 99]       | The TNR IIR window size.                                     | 1                                                            |
| filterLen2          | int      | [1, 99]       | The motion IIR window size, used for motion  history generation. | 4                                                            |
| motionSmoothFactor  | double   | [0.1, 5.0]    | The Gaussian smooth sigma to smooth input  images for motion detection.  Set this parameter to a small value for low  ISO and a high value for high ISO. | 0.5                                                          |
| rangeH              | int      | {3, 6}        | The width of the motion detection window.                    | 3                                                            |
| sadweight           | int      | [0, 16]       | The weight of the sum of the absolute  difference (SAD), which is used to calculate the merged difference as  follows:   diff = [sad_weight × sad + (16 − sad_weight) ×  mean_diff]/16   where:   · sad_weight is specified by this parameter. · sad is the SAD between the current and reference coarse layers.  · mean_diff is the difference between the means of the current and  reference coarse layers. | 12                                                           |
| diffType            | int      | {0, 1}        | The difference type to be used for motion  detection.   0: the difference merged from the SAD and mean  difference by applying the sadWeight value.   1: an approximation of squared difference  based on the merged difference. | 1                                                            |
| sqrDiffFactor       | int      | [0, 10]       | The number of bits shifted to adjust motion  difference.     | 10                                                           |
| noiseLevel          | int      | [0, 65535]    | A motion classifier parameter.   If the motion difference of a pixel is less  than the value of this parameter, the pixel is classified as static. | 32                                                           |
| thrMotionSlope      | int      | [0, 4095]     | A motion classifier parameter.   If the motion difference of a pixel is greater  than the sum of this parameter and noiseLevel, the pixel is classified as  100% moving. | 100                                                          |
| tnrLumaCurveX[12]   | int[12]  | [0, 4095]     | The pixel luma curve to define the TNR motion  classifier.   | [0, 32, 64, 96, 128, 256, 512, 768,1024,1536, 2048, 4095]    |
| tnrLumaCurveY[12]   | int[12]  | [0, 65535]    | The noise level curve to define the TNR motion  classifier.  | [32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32]             |
| tnrMotionSlopeY[12] | int[12]  | [0, 4095]     | The motion slope curve to define the TNR  motion classifier. | [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100] |

Table 3.13‑2 3DNR Motion Detection调试参数

#### Motion Mask

运动掩膜（motion mask）是用于标记图像或视频中发生运动的区域的二进制图像。利用运动估计技术从视频序列中提取出运动信息，以便在时域上进行降噪处理。

历史帧运动掩膜是利用过去的视频来检测当帧中的运动目标的掩膜。它是通过对相邻帧之间的差异进行分析，找出像素在时间上的位移，从而找到当前帧中运动的区域。

| **Parameter**   | **Type** | **Range** | **Description**                                              | **Default**  **Value** |
| --------------- | -------- | --------- | ------------------------------------------------------------ | ---------------------- |
| motionSmoothLvl | int      | {0,1}     | The smoothing level of the motion mask.  Level 0 provides a stronger smoothing effect  on   the motion mask than level 1. | 1                      |

Table 3.13‑3 Motion Mask调试参数

#### Motion Dilation

运动膨胀模块的设计是使motion mask更加稳定。通过将原始图像与一个运动核（也称为运动模板）进行卷积来实现。运动核的形状会决定运动模糊的方向和程度。

完成motion mask平滑处理后，将针对水平方向进行膨胀处理以进一步优化图像特征。该膨胀处理的参数是固定的，由固件（firmware）预设决定，通常不需要用户干预。旨在增强图像中的特定结构，如边缘和轮廓，从而为后续的图像分析提供更清晰的特征。

由于膨胀处理的参数是固件设定的。用户无需对其进行调整。如果有特殊的应用需求，可能需要重新考虑这些参数的设定。

| **Parameter** | **Type** | **Range** | **Description**                                   | **Default Value** |
|----|----|----|----|----|
| dialteH       | int      | {3,6}     | The motion dilation size in horizontal direction. | 3                 |

Table 3.13‑4 Motion Dilation调试参数

#### NoiseProfile

NoiseProfile反映的是模组在不同gain下，不同亮度noise level的水平，由静态标定工具标定根据输入的RAW序列估计得出。

标定输入RAW需是平坦区且同时存在一定动态范围像素的分布，更能反映出模组本身在不同亮度条件下的noise level值。灰板的亮度范围建议在140~160 之间。具体标定要求见《X5-Calibration tool工具指南》。

![C:\Users\hobot\AppData\Roaming\LarkShell\sdk_storage\82c1d3d13abe7e2b8aaa4f8bdfd360b7\resources\images\img_v2_b478d8c6-6595-4bd7-ba7b-069d1e52cf5g.jpg](_static/_images/isp_tuning/image64.jpeg)

Figure 3.13‑4 NoiseProfile标定示意图

### Tuning 3DNR Process

由于3DNR的调试不依赖Sensor的特性值，因此，调试是从第二阶段开始的。

先决条件满足后，可进入调试流程。

|   **变量**   |     **状态/值**     |
| :----------: | :-----------------: |
| NoiseProfile | CalibrationTool生成 |

Table 3.13‑5 NoiseProfile标定先决条件

调试3DNR可设置与2DNR调试相同的实景，实景的布置需要包含运动物体、ColorChecker、纹理物体、颜色纹理、分辨率卡和平坦区。运动物体是用来确认Ghost的程度，如Figure 3.13‑5 中的玩具小火车。节拍器也是个用来确认Ghost的不错选择。

![](_static/_images/isp_tuning/image65.png)

Figure 3.13‑5 3DNR 调试实景示意图

**调试流程**

![](_static/_images/isp_tuning/image66.png)

Figure 3.13‑6 3DNR 调试流程图

**3DNR具体调试步骤**

1.  通过Noise标定获得noise_model_a/b

noise_model_a/b反应了该曝光条件下，Raw像素在不同亮度上的噪声水平和趋势。noise_model_a/b用于TNR 的noise_level曲线拟合，也用于2DNR频率分解的计算。

2.  区分运动区域和静止区域。

确定好noise_model_a/b之后，先调试TNR。如果是噪声很大的场景，可以适当调整sad_weight,更多使用块均值匹配，找出合适的noise_level将运动区域和静止区域区分开。

打开配置中的debug dump，然后借助noise 分析工具，基于3dnr debug dump来大致得到区分静止和运动的两条luma-noise level curve，一条为luma-noise level(tnr luma curve)，一条为luma-motion slope(motion slop curve)。在此基础上可以精调tnr luma curve和motion slop curve来对不同亮度区域的运动和静止区域做更好的区分。另外，tnr factor(filt len)用来改变历史帧权重。

Tnr_factor写1时，tnr迭代慢，约30帧收敛，静止区域噪声降到1/30的水平，相对更smooth；当tnr_factor写非1的值，例如10，则约10顿收敛，静止区域噪声降到1/10的水平，相对残留较多。

3.  调节2DNR强度。

运动和静止基本区分好之后，关闭TNR，来调节2DNR；主要关注运动物体上的2DNR是否合适。一般建议detail thr 以及moving detail thr都置0。Sigam 0，sigam 1，sigma base分别代表高、中、低频，一般建议sigma0\>sigma1\>sigma base。确定好参数之后，将TNR和2DNR打开联调。

4.  TNR和2DNR联调

​	1) 通过调节motion factor curve来对静止~运动区域做不同程度的2dnr。在这过程中，motion factor(filt_len2)会对motion joint造成影响，加大motion factor，运动历史顺的权重增大，运动过去的区间更多的使用历史帧信息，2dnr强度变大

​	2) NLM之后直接输出的是低频分量，同时可以有选择的进行中高频分量的叠加。此时通过中高频分别在静止~运动区域的回加来做一些纹理的增强或者抑制处理（但仅限于NLM之后的细节纹理）。

- 小于detail threshold则不回加
- 大于detail threshold且小于boost detail threshold则直接不增强回加
- 大于boost detail threshold则增强回加

> 增强的系数由boot factor决定。

静止和运动区域区分由\[anchor0,anchor1\]决定，anchor是在motion joint轴上选择两个值，anchor0以下认为是静止，anchor1以上认为是运动，中间区域则由静止和运动参数线性插值。boost clip参数用于对增强做限制，凡是超过clip值的都会被clip到该值。

有选择的对NLM之前和之后的结果进行叠加。NLM之后即经过上述b的处理之后，NLM之前即经过TNR处理之后，对两者进行叠加，可以通过nlm strength offset,nlm strength max 以及nlm strength slope来调试，如果nlm strength offset为900，nlm strength max为1024，即在motion joint轴上，从0开始，NML之后的结果占比900/1024，NLM之前的结果占比（1024-900）/1024。

从0以上，nlm strength以slope决定的斜率上升，直到上升到1024截止。叠加一定比例的NLM之前的结果，会使原本非常平滑的区域，有一些小颗粒，当2dnr之后出现不自然的油感时，可尝试此方法。

**Tips**：

- 2dnr vstfactor取值范围\[0,1000\]，3 dnr vstfactor的值的取值范围是\[1,1000\]；

- 2dnr中manual/auto参数中都有vstfactor，3dnr中只有manual参数中有vstfactor；

- 3dnr和2dnr vstfactor的处理方式

  - 3dnr auto & 2dnr auto

    3dnr auto中计算出来的vstfactor给到2dnr，当2dnr auto计算出来的vstfactor的值小于1时，使用3dnr计算出来的vstfactor；当2dnr auto计算出来的vstfactor的值大于等于1时，使用2dnr计算出来的vstfactor。

  - 3dnr auto & 2dnr manual

    3dnr auto计算出来的vstfactors给到2dnr，2dnr直接使用3dn计算的vstfactor的值，跟2dnr manual下发的vst factor没关系。

  - 3dnr manual & 2dnr auto

    2dnr auto使用自己计算出来的vstfactor，跟3dnr的参数没有关系。

  - 3dnr manual & 2dnr manual

    2dnr使用自己的vstfactor，跟3dnr没有关系。

## Demosaic

### Overview

在数字图像处理中，Demosaic用于将Bayer数据插值成完整的RGB颜色。

在插值处理过程中上，针对不同的颜色通道做方向插值，以减少引入的伪像；同时在空间域对图像进行锐化处理，提升图片的清晰度。

### Tuning Theory

依据Bayer 矩阵来还原每个像素在RGB色彩空间的像素值。使用各向同性和各向异性的非线性颜色差值算法来进行梯度检测，然后结合边缘自适应锐化，最大程度降低高频噪声和伪色抑制。

Demosaic主要目标是最大化各向同性与各向异性的梯度检测。为了做到这一点，可调整各梯度检测判定参数。模块的基本处理流程如下：

![](_static/_images/isp_tuning/image67.png)

Figure 3.14‑1 Demosaic Processing Flow

Demosaic模块的调试可分为三个阶段完成：

- 第一阶段：无需调整。

- 第二阶段：实验室场景中完成Interpolation、Sharpen、De-Purple等关键模块参数的调试。

- 第三阶段：根据实际场景，微调Demosaic模块参数，使其更好的适应所有的场景。主要包含依据Gain值不同而变化的锐化参数。

#### CAC

色差是指光学镜头不能将各种波长的光聚焦在同一点上，其主要原因是不同波长的光通过镜头时的折射率不同，这是镜头的一种缺陷，通常情况下，离图像中心越远，色差越明显，一般表现为物体的两个边缘呈现出不同的颜色。CAC 是以 G 平面为基准对 RB 平面进行缩放，使得三个通道的图像高度相同，RB 平面的缩放方向和强度通过标定得到。

CAC参数与模组特性强相关，CAC 校正系数是通过CalibrationTool标定生成的，通过Vtuner导入客观标定生成的json或XML时，工具会自动将客观CA标定部分的参数写入到DMSC的CAC部分。下表展示的是ISP pipeline中CAC每个参数的描述，不建议修改，以工具标定生成的参数值为准。

| **Parameter** | **Type** | **Range**          | **Description**                                              | **Default**  **Value** |
| ------------- | -------- | ------------------ | ------------------------------------------------------------ | ---------------------- |
| cacEnable     | bool     | {true, false}      | Enable the CAC module in demosaic                            | false                  |
| aBlue         | float    | [-16,15.9375]      | Linear Parameters for radial shift calculation  in blue channel | 0                      |
| aRed          | float    | [-16,15.9375]      | Linear Parameters for radial shift calculation  in red channel | 0                      |
| bBlue         | float    | [-16,15.9375]      | Square Parameters for radial shift calculation  in blue channel | 0                      |
| bRed          | float    | [-16,15.9375]      | Square Parameters for radial shift calculation  in red channel | 0                      |
| cBlue         | float    | [-16,15.9375]      | Cubical Parameters for radial shift  calculation in blue channel | 0                      |
| cRed          | float    | [-16,15.9375]      | Cubical Parameters for radial shift  calculation in red channel | 0                      |
| centerHoffs   | int      | [0,image_width/2]  | Horizontal distance between the image and optical  center in pixels | 0                      |
| centerVoffs   | int      | [0,image_height/2] | Vertical distance between the image and  optical center in pixels | 0                      |

Table 3.14‑1 CAC标定校正参数

镜头系统中观察到的色差通常在图像的角落比中间部分更为明显。一般来说，色差的强度取决于与光学图像中心的距离。算法内校正通过多项式运算动态调整色彩分布因此，以光学图像中心半径为函数。它是一个9位的二进制补码整数，有4位小数，有效范围为\[-16, 15.9375\]。例如对B通道的计算过程为：

![image-20240905212714150](./_static/_images/isp_tuning/image-20240905212714150.png)

这个多项式允许设置线性、平方和立方项，以使校正函数适应观察到的色差函数。校正应通过使用适当的计算工具，结合待校正的传感器模型生成的测试图像来完成。

如果镜头系统与传感器阵列不完全匹配，图像中心可能与色差中心有偏移。这种偏差可以通过设置以下寄存器来校正：

- *h*\_𝑐𝑜𝑢𝑛𝑡_𝑠𝑡𝑎𝑟𝑡\[bits 12:0\]

- 𝑣_𝑐𝑜𝑢𝑛𝑡_𝑠𝑡𝑎𝑟𝑡\[bits 28:16\]

计算方式为

![image-20240905212729035](./_static/_images/isp_tuning/image-20240905212729035.png)

式中

- $h_{size}$为图像的水平方向的像素数

- $v_{size}$为图像的竖直方向的像素数

- $h_{offset}$为距离图像中心和光学中心的水平像素距离

- $v_{offset}$为距离图像中心和光学中心的竖直像素距离

距离图像中心的最大距离为

$$dist\_ max = \sqrt{{h\_ count\_ max}^{2} + {v\_ count\_ max}^{2}}$$

$h\_ count\_ max$和$v\_ count\_ max$分别是水平和竖直方向的像素统计最大值。

上述参数之间的关系如Figure 3.14‑2所示。

![](_static/_images/isp_tuning/image68.png)

Figure 3.14‑2 Relationship Between Image Center and Optical Center

#### Interpolation

Demosaic模块中插值过程中，会对输入的图片进行梯度计算、边缘和平坦区分离、方向判断、角点判断等处理过程，综合上面所有处理的结果，将输入的Bayer图片插值成RGB结果。通常情况下插值模块的参数无需调整，保持默认值即可。

| **Parameter**         | **Type** | **Range**      | **Description**                                              | **Default**  **Value** |
| --------------------- | -------- | -------------- | ------------------------------------------------------------ | ---------------------- |
| dmsc3Enable           | bool     | {false , true} | DMSC enable/disable                                          | true                   |
| granThMin             | int      | [0,4095]       | During interpolation, flat area (mean value  interpolation) upper_bound/lower_bound threshold determination:  1. lower_bound refers to darkest area.  2. upper_bound refers to brightest area.  ==> each pixel calculate brightness within 5x5  window and calculate threshold adaptively | 4                      |
| granThMax             | int      | [0,4095]       | 20                                                           |                        |
| diffColorCoef         | int      | [0,128]        | 1. weighted fusion ratio for "cross channel  difference" wt  2. weighted fusion ratio for "inner  channel difference" 128-wt | 128                    |
| adptCoefMode          | int      | [0,3]          | self-adaptive model for different channel  switch:  0: self-adaptvie mode disable, use  dmsc3_diffColor_coef  1: self-adaptive mode for pixels in R&B  channel  2: self-adaptive mode for pixels in Gr&Gb  channel  3: self-adaptive mode applied to all selected  pixels | 3                      |
| adptCoefThLow         | int      | [0,255]        | with coef enable:local average color  difference and stability  ==> cross channel difference use  "dmsc3_adpt_coef_min" to determine direction when  average&stability is under this threshold  ==> cross channel difference use  "dmsc3_adpt_coef_max" to determine direction when  average&stability is beyond (th_low + (1 << th_shift))  ==> (1<<shift) indicates the  transition area from "dmsc3_adpt_coef_min" to  "dmsc3_adpt_coef_max" | 24                     |
| adptCoefThShift       | int      | [0,8]          | 6                                                            |                        |
| adptCoefMin           | int      | [0, 128]       | minimum/maximum coefficiency involved in   direction determination for cross channel  difference with AdptCoefMode enable | 0                      |
| adptCoefMax           | int      | [0, 128]       | 128                                                          |                        |
| interpCornerEn        | bool     | {false , true} | corner rough selecting enable/disable                        | true                   |
| interpDirStrength[4]  | int[4]   | [0,256]        | horizontal/ vertical rough selecting;  h/v directional end selecting;  h/v 2nd round selecting;  h/v 3rd round selecting | [32,64,32,16]          |
| interpLargeStr[2]     | int[2]   | [0,16]         | directional weighted fusion for large area and  small area corresponding to 2rd/3rd h/v directional selecting. | [12,4]                 |
| dir0InterpType        | int      | [0,3]          | For non-ISO and direction unclear pixel,  choose interpolation method:  0: mean interpolation method in flatter area  likeISO point;  1~3: use different method based on surrounding  pixels; | 0                      |
| cornerLowTh           | int      | [0,4095]       | cornerLowTh:  threshold for directional interpolation, lower    bound threshold refers to directional average:  (cornerLowTh + (1 << cornerShift)):  threshold for directional interpolation, upper    bound threshold refers to weighted directional  similarity:  transition area;  larger value tend to use mean interpolation  smaller value tend to use non-mean interpolation | 1024                   |
| cornerShift           | int      | [0,12]         | 6                                                            |                        |
| declineEn             | bool     | {false , true} | high brightness compression during RB  interpolation: determine if filter out row/column with high brightness | true                   |
| highlightControlTh    | int      | [0,4095]       | Threshold for high brightness determine                      | 1024                   |
| highlightControlShift | int      | [0,9]          | Width for transition area:(1 <<  highlightControlShift)      | 6                      |
| deburstMode           | int      | [0,3]          | No channel selected for deburst  1: Deburst for g channel during interpolation  2: Deburst for rb channel during interpolation  3: Deburst for rb and g channel during  interpolation | 3                      |
| pureGWeight           | int      | [0,16]         | During G interpolation in uneven area use  "non color diff interpolation result" (weight) and "color diff  interpolation result" in flat area (16-weight) | 0                      |
| pureRBWeight          | int      | [0,16]         | During R/B interpolation in uneven area use  "non color diff interpolation result" (weight) and "color diff  interpolation result" in flat area (16-weight) | 0                      |
| pureGWeightISO        | int      | [0,16]         | During G interpolation in flat area use  "non color diff interpolation result" (weight) and "color diff  interpolation result" in flat area (16-weight); | 0                      |
| pureRBWeightISO       | int      | [0,16]         | During R/B interpolation in flat area use  "non color diff interpolation result" (weight) and "color diff  interpolation result" in flat area (16-weight) | 0                      |
| demoireRefineGEn  API | bool     | {false , true} | correct G value based on interpolation  direction of surrounding pixels. | true                   |
| refineGTh             | int      | [0,4095]       | refine G focus on interpolated G value. If  difference of R and B is larger than setting, start the correction. | 100                    |
| DeFalseColorEn  API   | bool     | {false , true} | defalse color enable/disable (open by default  and recommended) | true                   |

Table 3.14‑2 DMSC Interpolation调试参数

#### Sharpen

Demosaic中的Sharpen子功能是用于边缘增强，提升清晰度。支持频域划分，实现对不同频域的sharpen增强。Sharpen模块将输入图片分解成对高/中/低频3个频段，每个频域段进行3段式的处理。

Sharpen的整个处理流程图如下：

![](_static/_images/isp_tuning/image69.png)

Figure 3.14‑2 Demosaic Sharpen 处理流程图

Demosaic Sharpen模块具体参数的说明如下。

| **Parameter**            | **Type** | **Range**      | **Description**                                              | **Default**  **Value** |
| ------------------------ | -------- | -------------- | ------------------------------------------------------------ | ---------------------- |
| dmscSharpenEnable        | bool     | {false , true} | true: enables the sharpen function in demosaic.  false: disables the sharpen function in demosaic. | true                   |
| dmscSharpenCurve0T1      | int      | [0,2047]       | The texture value threshold T1.  For the curve illustration, see Figure 3.14-3. | 32                     |
| dmscSharpenCurve0T2Shift | int      | [0,11]         | The shift to T1 which determines the texture value    threshold T2 as follows:  T2 = T1 + 2t2_shift | 6                      |
| dmscSharpenCurve0T3      | int      | [0,2047]       | The texture value threshold T3                               | 122                    |
| dmscSharpenCurve0T4Shift | int      | [0,11]         | The shift to T3 which determines the texture value    threshold T4 as follows:  T4 = T3 + 2t4_shift | 6                      |
| dmscSharpenCurve0R1      | int      | [0,256]        | The sharpen levels R1, R2, and R3.  The larger the longitudinal axis, the stronger the  texture sharpening. | 0                      |
| dmscSharpenCurve0R2      | int      | [0,256]        | 100                                                          |                        |
| dmscSharpenCurve0R3      | int      | [0,256]        | 126                                                          |                        |
| dmscSharpenCurve1T1      | int      | [0,2047]       | The texture value threshold T1.  For the curve illustration, see Figure 3.14-3. | 8                      |
| dmscSharpenCurve1T2Shift | int      | [0,11]         | The shift to T1 which determines the texture value    threshold T2 as follows:  T2 = T1 + 2t2_shift | 5                      |
| dmscSharpenCurve1T3      | int      | [0,2047]       | The texture value threshold T3                               | 64                     |
| dmscSharpenCurve1T4Shift | int      | [0,11]         | The shift to T3 which determines the texture value    threshold T4 as follows:  T4 = T3 + 2t4_shift | 5                      |
| dmscSharpenCurve1R1      | int      | [0,256]        | The sharpen levels R1, R2, and R3.  The larger the longitudinal axis, the stronger the  texture sharpening. | 0                      |
| dmscSharpenCurve1R2      | int      | [0,256]        | 126                                                          |                        |
| dmscSharpenCurve1R3      | int      | [0,256]        | 168                                                          |                        |
| dmscSharpenCurve2T1      | int      | [0,2047]       | The texture value threshold T1.  For the curve illustration, see Figure 3.14-3. | 0                      |
| dmscSharpenCurve2T2Shift | int      | [0,11]         | The shift to T1 which determines the texture value    threshold T2 as follows:  T2 = T1 + 2t2_shift | 6                      |
| dmscSharpenCurve2T3      | int      | [0,2047]       | The texture value threshold T3.                              | 72                     |
| dmscSharpenCurve2T4Shift | int      | [0,11]         | The shift to T3 which determines the texture value  threshold T4 as follows:  T4 = T3 + 2t4_shift | 67                     |
| dmscSharpenCurve2R1      | int      | [0,256]        | The sharpen levels R1, R2, and R3.  The larger the longitudinal axis, the stronger the  texture sharpening. | 0                      |
| dmscSharpenCurve2R2      | int      | [0,256]        | The sharpen levels R1, R2, and R3.  The larger the longitudinal axis, the stronger the  texture sharpening. | 152                    |
| dmscSharpenCurve2R3      | int      | [0,256]        | The sharpen levels R1, R2, and R3.  The larger the longitudinal axis, the stronger the  texture sharpening. | 200                    |

Table 3.14‑3 DMSC sharpen调试参数

![](_static/_images/isp_tuning/image70.png)

Figure 3.14‑3 Demosaic Sharpen level作用示意图

根据上图所示是锐化级别曲线，纵轴值越大，纹理锐化就越强。

t系列参数值越大（或r系列参数值越小），曲线向右移动（向下），即整体锐化程度越低。

- 梯度值小于t 区域， sharpen值设定为 r1；

- 梯度值在 t2 和t3 区域，sharpen值设定为r2;

- 梯度值大于t4区域，sharpen值设定为r3, 其它区域sharpen值，使用线性插值得到对应的sharpen值。

#### Black&White Edge Control

黑白边锐化通常通过对图像中的边缘区域进行检测，并应用锐化滤波器来增强边缘的对比度。这样可以使图像中的物体边界更加清晰，提高图像的清晰度和分辨率。

需要注意的是，过度的锐化可能会导致图像出现噪点或伪影，因此在应用黑白边锐化功能时需要根据具体情况进行调整，以达到最佳的效果。

可分别设定factors中black和white的值控制增强的强度。

可分别设定clips中black和white值来限定锐化的强度最大值。

| **Parameter**     | **Type** | **Range** | **Description**                                              | **Default**  **Value**    |
| ----------------- | -------- | --------- | ------------------------------------------------------------ | ------------------------- |
| dmscSharpenFactor | int[6]   | [0,511]   | The high, middle, and low frequency enhancement  ratios on brighter and darker sides. | [100,100,200,200,300,300] |
| dmscSharpenClip   | int[6]   | [0,2047]  | The high, middle, and low frequency enhancement  clip values on brighter and darker sides. | [20,30,30,30,30,40]       |

Table 3.14‑4 DMSC Sharpen 调试参数

#### Sharpen Line

Line Sharpen 功能主要时对图像中的边缘和纹理与平坦区进行区分，对边缘和纹理区域应用锐化滤波器来增强边缘的对比度和细节表现。这样可以使图像中的物体边界更加清晰，纹理细节表现更丰富，以提高图像的清晰度和分辨率表现。

| **Parameter**            | **Type** | **Range**    | **Description**                                              | **Default**  **Value** |
| ------------------------ | -------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| dmscSharpenLineEnable    | bool     | {true,false} | true: enables the line sharpen function in  demosaic.  false: disables the line sharpen function in  demosaic.  Setting this parameter to false is recommended. | false                  |
| dmscSharpenLineStrength  | int      | [0,4095]     | The weight of the sharpen_line image for merging  into the output image. | 8                      |
| dmscSharpenLineThr       | int      | [0,2047]1    | The line detection threshold T1.  For the curve illustration, see Figure 3.14-4. | 24                     |
| dmscSharpenLineThrShift1 | int      | [0,11]       | The shift to T1 which determines the line  detection   threshold T2 as follows:  T2 = T1 + 2t2_shift | 3                      |
| dmscSharpenLineR1        | int      | [0,256]      | The sharpen levels R1 and R2.  The larger the longitudinal axis, the stronger the  texture sharpening. | 0                      |
| dmscSharpenLineR2        | int      | [0,256]      | The sharpen levels R1 and R2.  The larger the longitudinal axis, the stronger the  texture sharpening. | 256                    |

Table 3.14‑5 DMSC Sharpen Line调试参数

![](_static/_images/isp_tuning/image71.png)

Figure 3.14‑4 Sharpen for t1 and t2

如Figure 3.14‑4所示，纵向轴越大，锐化结果越接近于方向性（水平或垂直）增强。同时，更多的点会断开，这可能导致高频细节出现错误。基本效果是在垂直或水平方向平滑线条或纹理。默认设置是禁用锐化。

#### De-Purple

De-Purple功能旨在识别图像中高对比度区域的紫色，用颜色校正算法，根据图像中的颜色分布动态调整去紫边强度并通过调整饱和度来纠正这些边缘紫色。该功能通过定义Cb（蓝色差分）和Cr（红色差分）的亮度阈值，检测设定区域内的高对比度边缘梯度。对于识别出紫边区域，系统便会对这些区域执行去饱和处理，以消除不希望的紫色边缘，从而提高图像质量。这种方法对于减少成像传感器产生的色差非常有效，尤其是在边缘对比度极高的情况下。

下面是De-Purple模块的处理流程图:

![](_static/_images/isp_tuning/image72.png)

Figure 3.14‑5 Demosaic DePurple处理流程图

去紫边模块的关键参数如下

| **Parameter**         | **Type** | **Range**     | **Description**                                              | **Default**  **Value** |
| --------------------- | -------- | ------------- | ------------------------------------------------------------ | ---------------------- |
| dmscDepurpleEnable    | bool     | {true, false} | true: enables the depurple function in demosaic.  false: disables the depurple function in demosaic. | false                  |
| gradControl           | int      | [0,1]         | 0: disables gradient protection that is integrated  in demosaic v3.  1: enables gradient protection that is integrated  in demosaic v3. | 1                      |
| protectThLow          | int      | [0,255]       | The upper and lower thresholds of gradient  protection.  Lower threshold: protectThLow  Upper threshold:  protectThLow +  (1 << protectShift) | 16                     |
| protectShift          | int      | [0,8]         | The upper and lower thresholds of gradient  protection.  Lower threshold: protectThLow  Upper threshold:  protectThLow +  (1 << protectShift) | 5                      |
| dmscDepurpleSatShrink | int      | [0,8]         | The desaturation strength.  A greater value leads to a stronger desaturation  strength. | 8                      |
| dmscDepurpleCbcrMode  | int      | {0, 1, 2, 3}  | The desaturation mode on Cb/Cr channels.  0: depurple disabled.  1: Cr channel depurple.  2: Cb channel depurple.  3: Cr/Cb channel depurple. | 3                      |
| dmscDepurpleThr       | int      | [0, 255]      | The threshold to judge purple areas.                         | 40                     |
| cbLowth[0]            | int      | [0, 255]      | The upper and lower bounds for Cr/Cr color region  1.        | 132                    |
| cbHighth[0]           | int      | [0, 255]      | The upper and lower bounds for Cr/Cr color region  1.        | 220                    |
| crLowth[0]            | int      | [0, 255]      | The upper and lower bounds for Cr/Cr color region  1.        | 112                    |
| crHighth[0]           | int      | [0, 255]      | The upper and lower bounds for Cr/Cr color region  1.        | 200                    |
| cbLowth[1]            | int      | [0, 255]      | The upper and lower bounds for Cr/Cr color region  2         | 96                     |
| cbHighth[1]           | int      | [0, 255]      | The upper and lower bounds for Cr/Cr color region  2         | 122                    |
| crLowth[1]            | int      | [0, 255]      | The upper and lower bounds for Cr/Cr color region  2         | 82                     |
| crHighth[1]           | int      | [0, 255]      | The upper and lower bounds for Cr/Cr color region  2         | 118                    |

Table 3.14‑6 DMSC Depurple调试参数

dmscDepurpleThr是用于检测图像中紫色值的阈值。如果紫色值大于阈值，DMSC 将执行去色饱和度和颜色补偿处理。如果紫色值小于阈值，DMSC 将不执行任何操作。阈值设置得越小，检测到的紫色边缘就越多。最好将该值设置为大于或等于40。

dmscDepurpleSatShrink直接去饱和紫色区域的点。最大值为8，它将在检测到紫色时强制去饱和并处理为灰色。理想值为0或略大于0。

Figure 3.14‑6 Demosaic Depurple作用示意图

![](_static/_images/isp_tuning/image73.png)

threshold值越小，将有更多的像素被视为紫边。由于当前的检测只检测边缘而不检测颜色，因此需要谨慎使用“去饱和”功能。

#### DeFalse Color

在demosaic处理中，de-false color用于消除由于CFA模式和插值算法引起的颜色失真。这种失真通常表现为高对比度边缘附近的彩色条纹或斑点，尤其是在细节丰富的区域。

去伪彩算法的工作原理是检测图像中可能出现伪彩的区域，并对这些区域进行局部的颜色校正。这通常涉及到分析相邻像素的颜色差异，并对疑似伪彩的像素进行平滑处理，以减少颜色失真。

| **Parameter**      | **Type** | **Range**     | **Description**                                              | **Default**  **Value** |
| ------------------ | -------- | ------------- | ------------------------------------------------------------ | ---------------------- |
| DeFalseColorEn API | bool     | {true, false} | defalse color enable/disable (open by default and  recommended) | true                   |
| ColorStr           | int      | [0,128]       | defalse color strength (default and fixed 128)               | 128                    |
| cbCrClassTh        | int      | [0,7]         | threshold for median based classification (5 or 6  recommended) | 5                      |
| grayProtectStr     | int      | [0,128]       | If new_cbcr has higher saturation than old_cbcr,  activate this function higher value refers to heavier   weighted old_cbcr | 0                      |

Table 3.14‑7 DMSC DeFalse Color调试参数

#### Demoire

去摩尔纹模块相关的参数如下。

| **Parameter**        | **Type** | **Range**     | **Description**                                              | **Default**  **Value** |
| -------------------- | -------- | ------------- | ------------------------------------------------------------ | ---------------------- |
| demoireRefineGEn API | bool     | {true, false} | correct G value based on interpolation direction  of   surrounding pixels. | true                   |
| refineGTh            | int      | [0,4095]      | refine G focus on interpolated G value. If  difference   of R and B is larger than setting, start the  correction. | 100                    |

Table 3.14‑8 DMSC Demoire调试参数

### Tuning during Demosaic phase two

由于初始调试使用.RAW图像，Demosaic模块直到第二阶段才开始调整。在完成下表中列出的先决条件后才能开始调整：

|      **Prerequisite**      | **Status / value** |
| :------------------------: | :----------------: |
|        Black level         |       Tuned        |
|        Noise proﬁle        |      Derived       |
|     Green equalization     |       Tuned        |
| Defective pixel correction |       Tuned        |
|            2DNR            | Tuned and enabled  |
|            3DNR            | Tuned and enabled  |

Table 3.14‑9 Demosaic的先决条件

**调试流程 —— Sharpening**

Demosaic中的锐化模块与图像中的边缘和纹理有关，仅对检测出的边缘和纹理进行锐化处理，不对平坦区做任何处理。这样做的目的是正确权衡图像清晰度和伪像。

边缘和纹理的判定，可以通过layerT1/layerT2Shift/layer0T3/layerT4Shift来设定边缘和纹理梯度变化值来实现。T1、T2、T3、T4 纹理细节丰富程度由低到高排列。边缘和纹理增强，可以通过layerR1/layerR2/layerR3 来分别设定不同纹理丰富区域的锐化增强强度。

**注：1. Sharpen尽管可以提升客观数据的表现，但可能会导致主观图像质量下降。通常由过度锐化引起的伪影例如”haloing”和噪声。**

**2.如需为纹理和边缘设置不同的锐化强度，请通过设定 sharpenCurveIndex的值，来分别修改高频、中频、低频的不同频率段中不同纹理情况下的锐化强度。**

在图像效果测试期间，这个过程需要很多主客观的评估。调试的过程，需使用到不同的照明条件和场景下拍摄的大量图片，在调试其它系统Gain的参数前，先从最小的Gain值开始调试。

Shapen的调试流程图：

![](_static/_images/isp_tuning/image74.png)

Figure 3.14‑7 Demosaic Sharpen调试流程图

**sharpness调整步骤**

1.  将Total gain的值设定为1x。

2.  设定Sharpen初始参数。建议设定成默认值或过往项目中使用的值。

3.  正确摆放好分辨率卡，调整环境采集图片。

4.  指标分析。

&nbsp;

1)  打开Imatest，通过SFR模块分析采集到的图片。具体指标要求取决于客户的具体需求，但是MTF50低于或接近0.5（cycles/pixel）和overshoot 低于或接近10％的值可作为基础调试参考。这两部分值都能从Imatest的SFR模块输出。

2)  分析结果中MTF50和overshoot的值，分别对应Edge profile和SFR（MTF）结果项。

&nbsp;

5.  如不满足要求，请以+/-5的范围调整layerR1，layerR2和layerR3的值 ，分析结果并重复直到达到要求为止。

其它调试信息：

如果结果未达到最终分辨率目标或在图像中存在清晰可见伪像，则需要优化调试参数。下面列出了有关如何实现的方法：

- 通过VTunerClinet禁用动态像素校正（DPCC）模块，检查该模块是否引入伪像。如果伪像消失，则重新对DPCC参数进行调整，每次调整完成，评估对其他模块的影响。

- 通过VTunerClinet禁用GE模块，检查绿色均衡（GE）是否引入伪影。如果伪影消失，则重新调整 threshold的值。

- 检查图像是否由于过大的降噪强度而出现模糊，尤其注意在良好照明条件下图像的清晰度。

- 了解摄像头系统的局限性，因为所使用的传感器和光学元件会影响对整个系统的分辨率。

### Fine tuning demosaic phase three

针对系统Total Gain范围内调制表的调试。调试的先决条件如下。

| **Prerequisite** | **Status / value** |
| :--------------: | :----------------: |
|  Phase 2 Tuning  |     Completed      |
|       2DNR       |       Tuned        |
|       3DNR       |       Tuned        |
|        EE        |      Disabled      |

Table 3.14-10 锐化先决条件

对所有在Total Gain范围内所有Gain，重复第二阶段中调试Sharpening步骤1~步骤4的操作，并将校正得到的值填写到对应Gain下LUT表中。

## Color Correction Matrix（CCM）

### Overview

CCM模块根据客户的喜好对颜色进行校正和调整。它更改图像的色度值以匹配标准色彩空间的色度值。这个通过捕获Colorchecker并使用所有色块及其参考色度值。大多数情况下，标准颜色无法提供最佳图像质量。根据应用程序或客户的喜好，将这些值校准为更符合产品需求的值。

调整过程可以控制整体的色相和饱和度，下面将对此进行介绍：

- 第一阶段——使用.RAW图像在Calibration tool中调整CCM。

- 第二阶段——在实验室条件下使用.RGB图像通过Calibration Tool调整CCM。

- 第三阶段——根据增益微调CCM参数以适合所有场景。

### Tuning Theory

ISP 中的CCM模块用于校正相机传感器内部的串扰效应和色彩空间偏移。

CCM模块执行常规的 RGB 到 R’G’B’颜色空间转换，以补偿图像传感器的色彩分量之间的串扰。此外，可以通过适当的矩阵系数对色彩空间和饱和度进行校正。

因此，该模块能够通过矩阵运算对每个像素值进行校正，如下所示：

![image-20240905213504935](./_static/_images/isp_tuning/image-20240905213504935.png)

CCM调试相关的参数如下。

| **Parameter** | **Type**    | **Range**                                           | **Description**         | **Default**  **Value**                     |
| ------------- | ----------- | --------------------------------------------------- | ----------------------- | ------------------------------------------ |
| enable        | bool        | {true,false}                                        | Whether to enable CCM   | true                                       |
| ccMatrix[9]   | float[3][3] | 13-bit: [-2048/128, 2047/128]   12-bit: [-8, 7.992] | Gain for each channel   | [[1.0, 0, 0],   [0, 1.0, 0],  [0, 0, 1.0]] |
| ccOffset[3]   | float[3]    | [-2047, 2047]                                       | Offset for each channel | [0.0, 0.0, 0.0]                            |

Table 3.15‑1 CCM静态校准参数

### Tuning during phase one

**先决条件**

| **Prerequisite** | **Status / value** |
|:--:|:--:|
|   Black level    |                            Tuned                             |
|   Lens shading   |                            Tuned                             |
|  Initial gamma   |                            Tuned                             |
|       CNR        |                           Disabled                           |
| Manual exposure  | −0.25 \< exposure error \< 0.25 (f-stops). This can be veriﬁed through Imatest. Avoid clipping of patch 19 from the ColorChecker chart |

Table 3.15‑2 CCM 调试先决条件

**调试流程**

在此初始调整阶段，不期望CCM达到完美的值，按照《X5-Calibration tool工具指南》中CCM标定步骤，标定得到不同色温下的CCM值。最重要的是第二阶段和第三阶段对CCM的调整。

### Tuning during phase two

**先决条件**

| **Prerequisite** | **Status / value** |
|:--:|:--:|
| Phase one prerequisites |                           Complete                           |
|           AWB           |                            Tuned                             |
|          gamma          |                           Disabled                           |
|           AE            | −0.25 \< exposure error \< 0.25 (f-stops). This can be veriﬁed through Imatest. |

Table 3.15‑3 CCM Phase two 先决条件

**调试流程**

在进行CCM第二阶段的调试之前，使用Imatest的Colorcheck模块，验证曝光误差。如果曝光误差不在Table 3.15‑23.1-19给出的范围内，请重新调整AE_target参数来调整曝光。重复此过程，直到正确曝光为止。

第二阶段的调整和第一阶段的调整非常相似。根据具体对图像的需求调整标定得到不同色温下对应风格的CCM。

### Fine tuning phase three

第三阶段包括两个主要部分，更新校准参数和饱和度调制。其中第一个重点是说明先前模块参数的变更。另一个定义与增益关联的CCM，其思想是在更高增益或更低照度下提供更多控制噪声的方法。

**注：颜色准确性和噪点可见性之间的权衡是在每个增益条件下都需要谨慎考虑。通常，目标是提供最高饱和而不会出现不必要的噪声。尽量考虑客户需求或预期的应用。**

在第三阶段进行大量微调时，通常是由于CCM所依赖的模块（例如gamma）参数发生变更导致。这有可能需基于第二阶段的处理结果重新调试并更新CCM。

**Saturation modulation**

随着照度的逐渐降低，若需要对不同照度下的饱和度做一定的调整，来减低引入的彩色噪声。可以在CCM标定阶段，在不同色温下，分别对 saturation 的百分比进行调节，生成多组不同目标饱和度的CCM矩阵。在生成标定参数阶段可以一并生成。在实际调试应用中，可以在json配置文件中通过更改对应的Gain值，以实现Gain与CCT二维的降饱和处理。

## Gamma Correction

### Overview

Gamma 模块对图像进行亮度的非线性转换以适配输出设备，主要用于调整对比度。

RGB Gamma 模块，用于创建视频处理中常见的 gamma 预校正图像。伽马值为 1.0 表示线性关系，其中输出值与输入值直接成比例。大多数显示器和图像格式使用约为 2.2 的伽马值，并且在伽马曲线的开始部分有一个线性段，这提供了更符合感知均匀分布的亮度级别。

Gamma 表各节点之间的值使用线性插值生成。调试过程如下：

- 第一阶段：使用Calibration tool在实验室内tuning，tuning效果需要覆盖到大部分场景。

- 第二阶段：Gamma依照AE_target调整以改善对比度。

- 第三阶段：Gamma微调，使对比度适合所有场景。

### Tuning theory

18. G、B三通道分别使用不同的Gamma LUT，LUTs由64个均匀间隔的节点组成, 在这些节点之间进行线性插值。每个数据为10bit无符号类型，所以gamma\[0\]=0, gamma\[64\]=1023，这些节点值定义gamma校正曲线。

    将standard置为true时，通过设置standardVal的值可直接得到对应的gamma曲线。将standard置为false时，tandardVal参数将置灰，无法获得标准gamma曲线，但此时支持用户通过手动拖拽曲线锚点和修改LUT数值的方式，调整gamma曲线的Y轴值以获得自定义的Gamma曲线。

    默认状态下Gamma曲线的X轴为均匀间隔的节点，若需自定义X轴节点分布，可将userCurveX置为true，调整curvePx的值以实现X轴节点的修改。修改后X轴节点的位置为

    ![image-20240905213615063](./_static/_images/isp_tuning/image-20240905213615063.png)

    其中

    ![image-20240905213624718](./_static/_images/isp_tuning/image-20240905213624718.png)

Table3.16-1列举了Gamma模块的调试参数

| **Parameter** | **Type** | **Range**    | **Description**                                              | **Default**  **Value**                                       |
| ------------- | -------- | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| enable        | bool     | {true,false} | Enable/disable the Gamma module                              | true                                                         |
| standard      | bool     | {true,false} | If false, use the customized curve                           | true                                                         |
| standardVal   | float    | [1,4]        | Generate uniform curve with gamma formula                    | 2.2                                                          |
| curve[64]     | Int[64]  | [0,1023]     | Gamma curve.                                                 | [155, 212, 255, 290, 321, 349, 374, 398, 419,  440, 460, 478, 496, 513, 529, 545, 560, 575, 589, 603, 617, 630, 643, 655,  667, 679, 691, 703, 714, 725, 736, 747, 757, 767, 778, 788, 798, 807, 817,  826, 836, 845, 854, 863, 872, 881, 889, 898, 906, 915, 923, 931, 939, 947,  955, 963, 971, 978, 986, 994, 1001, 1008, 1016, 1023] |
| userCurveX    | boo      | {true,false} | Use the manual/inline value   true: Use the manual value   false: Use the inline value | false                                                        |
| curvePx[64]   | Int[64]  | [0,12]       | The x point of manual curve                                  | [0, 0, 0, …,0, 0, 0]                                         |

Table 3.16‑1 Gamma 调试参数

### Tuning during phase one

通常情况下Gamma的初始tuning只需要设定一条初始Gamma Curve，保存并继续其它模块。gamma在第二阶段调试AE模块时需要重新确认是否需要调试来加强对比度。

在此初始调整阶段，按照《X5-Calibration tool工具指南》中CCM标定说明，先选定一组Gamma曲线或者使用前期项目中已有的Gamma Curve作为基准曲线。

### Tuning during phase three

在后续实际场景适配中，根据实际场景要求，再动态调整Gamma曲线，以满足图片对比度的要求。Gamma Curve的调整可能会导致图片颜色指标发生一定的浮动，若对颜色准确度指标有特定要求，修改Gamma Curve后，需要重新测定颜色表现，甚至需要重新标定CCM。

Gamma模块可以根据不同的Gain设定不同的Gamma 曲线，实际项目应用中，应根据实际场景的需求，来设定对应的Gamma曲线，相邻Gain间的Gamma曲线保持相对平滑。

## Edge Enhancement

### Overview

边缘增强（EE）可以增强图像的边缘对比度。

EE 算法主要目的是通过边缘检测检测出尽可能多的对象边缘。边缘检测结果描述不同边缘的锐度水平。可以根据不同的锐度级别对边缘进行平滑增强。

### Tuning Theory

调整过程的简要概述如下：

- 第一阶段：无需调整。

- 第二阶段：在实验室条件下针对大多数场景调整EE增强参数。

- 第三阶段：无需调整，除非先前调试参数或EE增强参数依赖的模块产生的图像效果比较差。

下图EE模块完整的处理流程图：

![](_static/_images/isp_tuning/image75.png)

Figure 3.17‑1 EE处理流程图

#### Edge Enhanced

边缘增强（EE）用于改善对象的边缘。高频信息被分为边缘和细节，因此可以分别控制边缘和细节的锐化风格。 各向同性滤波器用于细节，以获得更自然的锐化风格，而各向异性滤波器用于边缘，以获得更清晰的边缘。

该模块包括两个主要部分：

1）物体边缘Y通道的增强。该部分可以在不增加噪声的情况下提高图像的清晰度。

2）降低物体边缘UV通道的饱和度。该部分可以降低object边缘的色彩饱和度。随着色彩饱和度的降低，色差和彩边也得到了很好的降低。

3）提升图像对比度。该模块可以通过调整不同亮度段的对比度，改善图像的局部或整体对比度。

调整强度在当图像中的光照异常好（传感器模拟增益很小），例如室外图像或明亮的房间时，边缘增强将完全启用。边缘增强强度在低光照设置下会降低（传感器模拟增益高）。

| **Parameter**       | **Type** | **Range**    | **Description**                                              | **Default Value** |
| ------------------- | -------- | ------------ | ------------------------------------------------------------ | ----------------- |
| eeEnable            | bool     | {true,false} | true: enables edge enhancement (EE).  false: disables EE.    | true              |
| yuvDomain           | bool     | {true,false} | true: processes EE in the YUV domain.  false: processes EE in the RGB domain. | false             |
| strength            | int      | [0, 128]     | The EE strength, which determines the degree to  which the enhanced result is merged back to the input image.  If this parameter is set to 128, it indicates that  100% enhanced result is used. | 128               |
| srcStrengthskin     | int      | [0, 256]     | The low-frequency fusion by original Y value and  low-pass filter result.  This parameter affects only the detected skin  zones. | 256               |
| gradTh[2]           | int      | [0,1024]     | The distinguish threshold for edge and noise, and  the distinguish threshold for edge and details. | [8,12]            |
| edgeNrLvl           | int      | [0,5]        | The noise reduction level.  Value 0 indicates the lowest level and value 5  indicate the highest level. | 3                 |
| edgeScaler          | int      | [0,32]       | The scaler control for edge detection results.               | 4                 |
| edgeUseAuxiDir      | int      | [0,1]        | Indicates whether to take the auxiliary   direction into consideration for edge strength  generation during edge detection.  0: does not take the auxiliary direction into  consideration.  1: takes the auxiliary direction into  consideration. | 1                 |
| detailLvl           | int      | [0,7]        | The detail level, which determines the sharpen  style.  A smaller value leads to more fine-grained  enhancement. | 5                 |
| detailScaler        | int      | [0,32]       | The scaler control for texture/detail detection  results.    | 8                 |
| detailPreEnhanceStr | int      | [0,256]      | The texture/detail  strength. A greater value leads to a higher detail level. | 16                |

Table 3.17‑1 EE 调试参数

**gradTh 参数说明：**

根据图像的梯度信息区分边缘和噪声。

阈值值越小，边缘检测越完整，但噪声也会增加。值越大，检测到的边缘就越少。更具体地说，可能会检测到更大的边缘，而较弱的边缘和噪声会被抑制。

#### EE Sharpen

边缘锐化相关的参数如下

| **Parameter**   | **Type** | **Range**                                                    | **Description**                                              | **Default**   **Value** |
| --------------- | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ----------------------- |
| sharpCurveLvl   | int      | [0,7]                                                        | The enhancement curve selection.  0 to 6: Detail mode influence is increased as the  value increases.  7: The former part is the same as curve 3 and the  later part enhances the compression of strong edge. | 3                       |
| sharpGain[2]    | int      | [0,1024]                                                     | The strength of the brighter side and that of the  darker side in non-skin areas | [100,122]               |
| sharpGainUv     | int      | [0,255]                                                      | The UV sharpen strength near edges.                          | 0                       |
| sharpLimitEn    | bool     | {true,false}                                                 | true: enables sharpen extreme value constrain.  false: disables sharpen extreme value constrain. | true                    |
| sharpLimitType  | int      | [0,2]                                                        | The type of sharpen extreme value control.  1: High-frequency enhancement is within a certain  ratio of the original value.  2: High-frequency enhancement is within a certain  ratio of the local original value.  3: High-frequency enhancement is within a certain  ratio of the adjusted local original value.The default value 2 is  recommended. | 2                       |
| sharpLimit[2]   | int      | [0,512]                                                      | The upper limit and lower limit of the range  within which the difference after highfrequency enhancement is constrained.  You can determine the range by the local brightest  and darkest and the pre-set ratio. | [90,118]                |
| hfMergeCurve[4] | Int[4]   | Element 1: [0, 1024]  Element 2: [0, 10]  Element 3: [0, 1024]  Element 4: [0, 10] | The fusion cure of  noise, texture, and edge. Element 1: The threshold T1.   Element 2: The shift  to T1 which determines the threshold T2 as follows:   T2 = T1 + 2t2_shift    Element 3: The  threshold T3.   Element 4: The shift  to T3 which determines the threshold T4 as follows:   T4 = T3 + 2t4_shift | [4,4,24,8]              |

Table 3.17‑2 EE sharpen调试参数

**sharpCurveLvl参数说明：**

当此字段设置为介于\[0, 6\]之间的值时，值越大，细节部分的增强越大。

当此字段设置为7时，增强曲线与曲线3的前半部分保持一致，而后半部分抑制强烈的边缘增强。

通常将此字段设置为3或7。当需要增强细节或加强弱边缘时，增加此值。当需要在平坦区域抑制噪声时，减小此值。

**sharpLimitType参数说明：**

0: 高频增强的差异不超过原始值的一定比例（由 change_up/down 设置）。

1: 高频增强的差异不超过局部最亮/最暗值的一定比例（由 change_up/down 设置）。

2: 高频增强的差异不超过局部最亮/最暗值的一定比例（由整体局部亮度调整，并由 change_up/down 设置）

**hfMergeCurve参数说明：**

边缘和细节将图像分为两个部分：边缘区域和非边缘区域。边缘区域包含图像中的边缘和轮廓，而非边缘区域包含图像中的平滑区域和细节。这两个区域被分别处理，最后合并在一起。

![](_static/_images/isp_tuning/image76.png)

Figure 3.17‑2 EE Edge&Detail作用示意图

t0: 纹理区分阈值，在此阈值以下不应用增强。

t1_shift: 噪声和纹理的区分阈值，高于阈值（t0 + (1\<\<t1_shift)）的部分以细节的方式增强，增强强度逐渐从低阈值平滑过渡到高阈值。

t2: 区分边缘和纹理的低阈值：如果低于低阈值，则以细节的方式应用增强。

t3_shift: 区分边缘和纹理的高阈值：如果高于高阈值，则以边缘的方式应用增强。

#### Skin Protected

基于颜色模型的肤色检测通常在YCbCr颜色空间中进行，因为这个空间允许更容易地分离色度信息（Cb和Cr）和亮度信息（Y）。以下是该方法的基本步骤：

**阈值设置**：在YCbCr颜色空间中，为Cb（蓝色差分）和Cr（红色差分）通道设置特定的阈值范围。这些阈值是根据肤色的色度特性确定的。

**肤色区域检测：**通过这些阈值，可以从整个图像中识别出肤色区域。所有落在这个阈值范围内的像素点被认为是肤色。

**边缘和细节增强：**在检测到的肤色区域内，可以对边缘和细节进行单独的增强处理，以改善图像质量。通过但对调整针对肤色区域的锐化和细节增强参数，它可以增加图像中边缘的对比度，使得肤色区域看起来更加清晰和生动。

通过这种方法，可以在保持肤色自然的同时，增强图像中的肤色部分，使其在视觉上更加吸引人。

| **Parameter**       | **Type** | **Range**                                                    | **Description**                                              | **Default**   **Value** |
| ------------------- | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ----------------------- |
| skinProcEn          | int      | [0,7]                                                        | The skin protection mode.  0: disables skin protection.  1 to 3: enables skin protection in self-adaptive  mode.  l   1: uses 3x3 low-pass filter on the RGB  domain for self-adaptive mode skin detection.  l   2: uses 3x5 low-pass filter on the RGB domain for  self-adaptive mode skin detection.  l   3: uses 3x7 low-pass filter on the RGB  domain for self-adaptive mode skin detection.  4: enables skin protection in hard threshold mode.  5 to 7: enables skin detection with both  self-adaptive mode and hard threshold mode effective.  l   5: uses 3x3 low-pass filter on the RGB  domain for self-adaptive mode skin detection.  l   6: uses 3x5 low-pass filter on the RGB  domain for self-adaptive mode skin detection.  l   7: uses 3x7 low-pass filter on the RGB  domain for self-adaptive mode skin detection. | 3                       |
| srcStrengthSkin     | int      | [0,256]                                                      | The low-frequency fusion by original Y value and  low-pass filter result.  This parameter affects only the detected skin  zones. | 200                     |
| skinDetectStr       | int      | [0,255]                                                      | The skin detection strength for self-adaptive  mode.         | 110                     |
| YUpThreshold        | int      | [0, 1024]                                                    | The hard lower Y threshold for skin detection.               | 280                     |
| YDownThreshold      | int      | [0, 1024]                                                    | The hard upper Y threshold for skin detection.               | 900                     |
| CrUpThreshold       | int      | [-1024, 1023]                                                | The hard lower Cr (R - G) threshold for skin  detection.     | 355                     |
| CrDownThreshold     | int      | [-1024, 1023]                                                | The hard upper Cr (R - G) threshold for skin  detection.     | 984                     |
| CbUpThreshold       | int      | [-1024, 1023]                                                | The hard lower Cr (B - G) threshold for skin  detection.     | 60                      |
| CrDownThreshold     | int      | [-1024, 1023]                                                | The hard lower Cr (B - G) threshold for skin  detection.     | 764                     |
| sharpSkinCurveLvl   | int      | [0,7]                                                        | The enhancement curve selection for skin zones.  0 to 6: Detail mode influence is increased as the  value increases.  7: The former part is the same as curve 3 and the  later part enhances the compression of strong edge. | 0                       |
| sharpGainSkin[2]    | int      | [0, 1024]                                                    | The strength of the brighter side and that of the  darker side in skin areas. | [100,122]               |
| sharpLimitSkin[2]   | int      | [0,512]                                                      | The upper limit and lower limit of the range  within which the difference after high frequency enhancement in skin zones is  constrained.  You can determine the range by the local brightest  and darkest and the pre-set ratio. | [72,88]                 |
| hfMergeCurveSkin[4] | int[4]   | Element 1: [0, 1024]  Element 2: [0, 10]  Element 3: [0, 1024]  Element 4: [0, 10] | The fusion curve of texture and edge in skin  zones.  Element 1: The threshold T1.  Element 2: The shift to T1 which determines the  threshold T2 as follows:  T2 = T1 + 2t2_shift  Element 3: The threshold T3.  Element 4: The shift to T3 which determines the  threshold T4 as follows:  T4 = T3 + 2t4_shift | [8,5,52,9]              |

Table 3.17‑3 Skin Detection 调试参数

#### Depurple

紫边是在图像中观察到的紫色或紫红色边缘，通常在高对比度的区域或强光照条件下出现。紫边产生的原因主要与光学系统的色散效应有关，它在镜头中的色散、透镜的折射等过程中引起不同颜色的光线的偏移，从而导致紫边效应。

基于颜色通道之间的关系，将图像从RGB颜色空间转换到其他颜色空间YUV区间，在Y域设定对应阈值，选择出紫边区域，然后对U/V通道进行颜色平衡和校正减轻紫边。

| **Parameter**      | **Type** | **Range**    | **Description**                                              | **Default**   **Value** |
| ------------------ | -------- | ------------ | ------------------------------------------------------------ | ----------------------- |
| depurpleEnable API | bool     | {false,true} | true: enables depurple.  false: disables depurple.           | 3                       |
| depfDetectRange    | int      | [0,7]        | The depurple width.  The maximum value is 7 for horizontal  unidirectional processing. At most 15 pixels can be processed horizontally. | 7                       |
| depfLimit          | int      | [0,1024]     | The hard thresholds for purple fringing, in the   following order:  l   Lower U threshold  l   Upper U threshold  l   Lower V threshold  l   Upper V threshold | [460,900,420,880]       |
| depfDetectLumaTh   | int      | [0,1024]     | The brightest threshold during fringe detection.             | 800                     |
| depfDetectLumaDiff | int      | [0,1024]     | The difference between brightest and darkest   areas.        | 600                     |
| depfCompLumaDiff   | int      | [0,1024]     | The compensate candidate selection for nearby pixels.  Only pixels under the pre-set value is considered  for further depurple saturation correction. | 260                     |
| depfSatStr         | int      | [0,256]      | The saturation strength.  The default value is 256, which indicates no  saturation reduction. | 256                     |
| depfFixStr         | int      | [0,256]      | The strength of purple fringe correction.                    | 168                     |

Table 3.17‑4 EE Depurple 调试参数

#### CA

CA（Color/Contrast Adjustment，色彩/对比度调整）模块是图像处理中用于调整色彩和对比度的重要模块。它在YUV颜色空间中工作，通过预设的映射曲线来调整图像的饱和度。CA模块包含两条主要的曲线：

- **Y曲线**：用于调整图像的对比度。通过改变亮度通道Y的值，可以增强或减弱图像的对比度，从而使图像看起来更为清晰或柔和。

- **UV曲线**：用于调整图像的色彩饱和度。通过改变色度通道U和V的值，可以控制图像的色彩强度，使颜色更加鲜艳或自然。

CA提供一种灵活的方式来调整颜色和对比度，同时也具备简单的降噪功能：

- **Y曲线降噪**：可以减少图像中暗区域的亮度噪声，这对于提高低光照条件下的图像质量特别有用。

- **UV曲线降噪**：可以降低暗区或低饱和度区域的色度噪声，有助于保持色彩的均匀性和自然性。

实际应用中可以基于传感器的增益值来配置不同的CA Curve，以适应不同应用场景。

| **Parameter** | **Type** | **Range**    | **Description**                                              | **Default**   **Value** |
| ------------- | -------- | ------------ | ------------------------------------------------------------ | ----------------------- |
| caEnable      | bool     | {false,true} | true: enables the CA curve.  false: disables the CA curve.  This parameter is valid only if the value of  curveEnable is 1. | false                   |
| caCurve       | int[65]  | [0, 1024]    | The color adjustment curve.                                  | [1024,1024,…,1024]      |
| caMode        | init     | {0,1,2}      | The color adjustment mode.  0: color adjustment based on brightness  1: color adjustment based on saturation  2: color adjustment based on the lower value  between intensity and saturation | 1                       |

Table 3.17‑5 EE CA 调试参数

**EE camode介绍**

不同mode对应的详细描述和推荐使用的ca curve见Table 3.17‑6。

| **mode** | **Range** | **Description**                                              |
| -------- | --------- | ------------------------------------------------------------ |
| 0        | 2&3       | 输入为Y;  饱和度可以通过亮度调节                             |
| 1        | 0&1&3     | 输入为UV:(abs(u-512)+abs(v-512));  饱和度可以根据原来的饱和度进行调整。 |
| 2        | 0&1&3     | 输入为min(y,(abs(u-512)+abs(v-512));  饱和度可以两者进行调整亮度和原始饱和度 |

Table 3.17‑6 EE camode参数介绍

**CA curve形状介绍**

1.  shape0：伽玛形状

shape0_index决定曲线弯曲程度，越接近1，曲线弯曲程度越大，抑制虽度饱和度越高。

![](_static/_images/isp_tuning/image77.png)

Figure 3.17‑3 EE CA-Shape0作用示意图

2.  shape1：S形

建议拐点固定为零，如紫⾊线所⽰。shape1_index 决定曲线弯曲程度，越接近1，曲线弯曲程度越⼤，抑制强度饱和度越⾼。

![](_static/_images/isp_tuning/image78.png)

Figure 3.17‑4 EE CA-Shape1作用示意图

3.  shape2：抛物线形状

Shape2_a决定抛物线的开⼝⼤⼩，Shape2_a 越⼤，开⼝越⼩，抑制强度越饱和。

![](_static/_images/isp_tuning/image79.png)

Figure 3.17‑5 EE CA-Shape2作用示意图

4.  shape3:活动形状

激活设置五个锚点，自动生成曲线。一般第一个锚点会设置(0,0)，第3五个锚点会设置(64,1024)。

![](_static/_images/isp_tuning/image80.png)

Figure 3.17‑6 EE CA-Shape3作用示意图

#### DCI

DCI用于根据预先设定的曲线或直方图自动生成曲线来实现图像的全局对比度改善。DCI曲线是由64个point组成的曲线，可以通过工具自行调整曲线的形状。也可以通过外部工具生成，将dci_curve的值复制到JSON文档中。

| **Parameter** | **Type** | **Range**    | **Description**                                              | **Default**   **Value**                                      |
| ------------- | -------- | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| dciEnable     | bool     | {false,true} | true: enables the DCI curve.  false: disables the DCI curve.  This parameter is valid only if the value of  curveEnable is 1. | false                                                        |
| dciCurve[65]  | int[65]  | [0, 1024]    | The dynamic contrast improvement curve.                      | [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224,  240, 256, 272,288, 304, 320, 336, 352, 368, 384, 400, 416, 432, 448, 464,  480, 496, 512, 528, 544, 560, 576, 592, 608, 624, 640, 656, 672,688, 704,  720, 736, 752, 768, 784, 800, 816, 832, 848, 864, 880, 896, 912, 928, 944,  960, 976, 992, 1008, 1023] |

Table 3.17‑7 EE DCI 调试参数

## Color Processing

### Overview

颜色处理是通过调整亮度和色度值来完成的，可配置为根据 ITU‑R BT.601 标准或全值范围生成像素值。 输入像素范围也是可配置的，因为来自 ISP 的 YCbCr 路径的像素可能具有两个范围，具体取决于所使用的相机传感器。

### Tuning Theory

> 颜色相关项的计算方式为：

**对比度**：亮度值乘以寄存器中定义的对比度值来实现。

**亮度**：调整寄存器中定义的调整值来调整亮度。

**饱和度**：的将Cr值和Cb值与寄存器中定义的定点数相乘来调整饱和度。

**色调**：色度值的相移。

在参数的描述项中，对亮度、对比度、饱和度及色度的调整计算方式有更详细的说明。

Table3.18-1列举了颜色处理模块会用到的参数

| **Parameter** | **Type** | **Range**    | **Description**                                              | **Default**  **Value** |
| ------------- | -------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| enable        | bool     | {true,false} | Enable/disable the CPROC module                              | true                   |
| contrast      | float    | [0,1992]     | Y’=Y*(contrast), all pixels will be larger when   contrast > 1 | 1                      |
| bright        | float    | [-127,127]   | Real Bright= bright-64*(contrast-1)                          | 0                      |
| saturation    | float    | [0,1.992]    | UV’= 128 + (UV-128)*(saturation)                             | 1                      |
| hue           | float    | [-90,90]     | Rotation in HSV domain                                       | 0                      |
| chromaOut     | int      | [1,2]        | Different RGB->YUV conversion matrix  1: limited range [16, 240]  2: full range [0, 255] | 2                      |

Table 3.18‑1 CPROC 调试参数(8-bit)

### Tuning during phase three

CPROC作为后置模块，在调试的前两个阶段一般不需要做特殊调整，保持默认值即可。在实际应用中，CPROC模块中对比度、亮度、饱和度、色相均可以根据不同的Gain值来实现动态的调整。

## Color Noise Reduction (CNR)

### Overview

彩色噪声（Color Noise）通常表现为数字图像中的随机颜色偏移、颜色斑点或色彩不均匀，这些现象主要由图像采集或处理过程中的不确定性和噪声引起。为了解决这一问题，色度降噪（Chroma Noise Reduction, CNR）模块在图像信号处理器（ISP）的YUV域中被用来去除彩色噪声。

基本的调试流程如下：

- 第一阶段：不需要调试准备；

- 第二阶段：CNR模块在实验室环境下对主要的一个场景进行调试；

- 第三阶段：CNR参数精细调试来适应各种场景。主要基于增益来对相应的模块进行调试；

### Tuning Theory

色度降噪过程中使用的三层金字塔模型是一种多尺度技术，它允许在不同的分辨率层次上处理图像，以有效地去除噪声同时保留重要的图像细节。在这个模型中，高斯金字塔是一种常用的方法来构建这样的金字塔结构。具体步骤如下：

> **最底层**：直接使用原始图像作为金字塔的最底层。
>
> **中间层：**通过对最底层图像应用高斯模糊和下采样操作生成。这一步减少了图像的分辨率，同时平滑了颜色变化，有助于去除噪声。
>
> **顶层：**对中间层再次进行高斯模糊和下采样，得到分辨率更低的图像层。

在每一层上，可以独立地进行色度降噪处理，然后将处理后的图像层重新组合，以恢复到原始分辨率。这种方法允许算法在不同的尺度上捕捉和去除噪声，同时保持图像的结构和细节。通过这种方式，色度降噪算法能够更精细地控制降噪过程，避免过度平滑导致的细节丢失。

![](_static/_images/isp_tuning/image81.jpeg)

Figure 3.19‑1 CNR处理流程图

CNR调试相关的参数如下。

| **Parameter**     | **Type** | **Range**    | **Description**                                              | **Default**  **Value** |
| ----------------- | -------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| cnrEnable         | bool     | {true,false} | true: enables the chroma noise reduction (CNR)  function.  false: disables the CNR function. | false                  |
| cnrStrength       | int      | [0,128]      | The denoise strength, which determines the degree  to which the denoising result is merged back to the input image.  If this parameter is set to 128, it indicates that  100% denoising result is used. | 128                    |
| textureMaskSelect | int      | [0,8]        | Texture filter coefficient selection.  The smaller the noise, the larger the parameter  value should be set. | 0                      |
| cSigmaLayer       | float[3] | [1,96]       | The sigma for each layer.  The greater the noise intensity of a layer, the  larger the parameter value should be set. | [16,16,12]             |

Table 3.19‑1 CNR 调试参数

### Tuning CNR during phase two

CNR在第一阶段的调试中并不需要调试其他模块，但是在第二阶段的调试开始前需要先完成相关模块的调试，这些预先需要完成调试的模块如下表：

| **Prerequisite**    | **Status/Value** |
| ------------------- | ---------------- |
| Black  level        | Tuned            |
| CCM                 | Tuned            |
| DPC                 | Tuned            |
| 2DNR                | Tuned            |
| 3DNR                | Tuned            |
| Demosaic            | Tuned            |
| Green  Equalization | Tuned            |
| Set  Enable         | 0(disables CNR)  |

Table 3.19‑2 CNR phase two prerequisites

构建CNR调试的环境，环境照度应相对较低(例如10lux)，拍摄目标可以是灯箱内的色卡或者实景，场景内目标应具有丰富和色彩区域和灰板区域，便于评估彩噪的实时状态，CNR未调试前画面效果如Figure3.19-2所示。

![](_static/_images/isp_tuning/image82.png)

Figure 3.19‑2 image before CNR tuning

按照实际的使用需求，调整三层金字塔相关的参数，控制CNR的作用强度。一般来说，可先使用默认参数观画面效果是否正常。若彩噪仍较为明显，则继续增大cSigmaLayer的值，调整至彩噪状态满足需求；若已无明显彩噪，可以适当降低cnrStrength和cSigmaLayer，或者增大textureMaskSelect，减弱CNR对色彩还原效果的影响。调试过程中，不宜过渡追求高强度的降噪，过高的降噪强度会引入红/蓝色调偏色的风险。Figure 3.19-3是一个可供参考的调试后例子，实际调试后的噪声状态要按使用需求调整。

![](_static/_images/isp_tuning/image83.png)

Figure 3.19‑3 image after CNR tuning

### Fine tuning CNR phase three

改变光照环境来获得不同的gain，重复第二阶段的调试流程，在每个Gain下调试出适合的参数值。整个gain值范围内的参数调试完成后则CNR的调试就完成了。

## Auto Focus(AF)

### Overview

Auto focus功能需要依据使用场景来确定需要调试的频度，例如，安防摄像头通常是采用手动对焦的，在这种使用场景下就不需要对摄像头使用自动对焦功能。在一些需要用到自动对焦功能的场景，AF的调试通常是在第二阶段的早期完成。当然，因为AF模块的调试相对独立，也可以在其他时间来进行AF的调试。AF的具体调试过程如下：

- 第一阶段：不需要调试AF模块，但是需要手动调节对焦来满足拍照要求。在此阶段镜头的驱动需要启动并测试通过来满足拍照的基本功能。

- 第二阶段：调试AF功能来适应不同场景。

- 第三阶段：调试AF前需要验证马达精度，速度，可重复性及稳定性。

### Tuning theory

Auto Focus是一种常用的对焦技术，其基本原理是通过对比图像的清晰度来实现对焦。

在图像处理中，清晰度通常是通过图像的对比度和高频分量来衡量的。为了达到最清晰的图像效果，Auto Focus通过改变图像的焦距，不断调整图像的对比度和高频分量。

Auto Focus的实现过程包括三个步骤：检测清晰度、确定对焦位置和移动对焦位置。

在第一步中，Auto Focus会通过图像处理算法检测出图像的清晰度。

在第二步中，Auto Focus会根据清晰度检测结果确定当前对焦位置。

在第三步中，Auto Focus会根据当前对焦位置移动对焦位置，直到达到最清晰的图像效果。

重复上述3个步骤，直到图像达到最清晰为止

AF模块支持CDAF和PDAF两种不同的自动对焦技术，整体流程图如下：

![](_static/_images/isp_tuning/image84.jpeg)

Figure 3.20‑1 AF混合对焦处理流程

#### Function Descrtiption

CDAF（对比度检测自动对焦）是一种适用于静态拍摄场景的自动对焦技术，它通过比较图像中不同区域的对比度来判断焦点位置。通过最小和最大焦距范围移动马达，并形成清晰度和焦距的抛物线。通过抛物线的顶点，CDAF可以找到最佳焦距和最高清晰度。CDAF的优点是精确度高，适用于高分辨率的图像，但缺点是对于运动物体的追踪不够快速。

PDAF（相位差检测自动对焦）则是一种适用于运动物体的拍摄场景的自动对焦技术。它通过利用镜头中的相位差信息来判断焦点位置。通过相位差检测失焦强度，并使用失焦转换系数将相位差转换为马达的焦距。PDAF的优点是对于运动物体的追踪速度快，适用于高速运动的场景，但缺点是精确度相对较低，可能会产生误差。

X5中PDAF中 PD Split 和 PD Calibration 软体实现流程图如下，支持type2模式。

type2: sensor内部将PD 信息拆分完成后，输出给后端处理。

![](_static/_images/isp_tuning/image85.png)

Figure 3.20‑2 PDAF软体实现流程

#### AF Statistics

AF统计模块（ISP_AFM）用于支持AF控制。AF控制的大部分工作将在软件中完成。搜索算法用于寻找图像中的最大清晰度，软件依据统计输出清晰度值控制镜头的移动。硬件实现的AF模块通过寄存器接口提供图像清晰度的测量值。

| **Parameter** | **Type** | **Range**     | **Description**                                       | **Default**  **Value** |
| ------------- | -------- | ------------- | ----------------------------------------------------- | ---------------------- |
| enable        | bool     | {true, false} | Whether to enable AF                                  | true                   |
| maxFocal      | uint16_t | [0,1023]      | The maximum focal distance that the  motor can reach. | 600                    |
| minFocal      | uint16_t | [0,1023]      | The minimum focal distance that the  motor can reach. | 300                    |

Table 3.20‑1 AF基础调试参数

**AF控制和窗口选择-CDAF**

硬件中的AF模块根据软件指令控制镜头的移动。允许软件选择图像中的特定窗口或感兴趣区域，以进行对焦测量。这种窗口选择有助于对图像中的特定对象或区域进行对焦。

窗口大小将通过寄存器进行配置，最多支持 3 个ROI区域，默认3列，可以通过调整每个ROI的(LT/RB）坐标来调整ROI的位置，每个ROI的weight由软件端控制。

![](_static/_images/isp_tuning/image86.jpeg)

Figure 3.20‑3 CDAF ROI区域配置

**AF控制和窗口选择-PDAF**

最多可配48个窗口。将指定的ROI 区域平均分配成48个窗口，每个窗口权重是可以配置

软件内部支持Auto模式和Manual模式。Auto模式默认拆分成3x3 窗口，权重是默认配置。Manual模式可以自定义窗口的多少和权重。

**IIR/FIR**

AF中IIR/FIR 滤波器设计流程图

![](_static/_images/isp_tuning/image87.png)

Figure 3.20‑4 IIR AF 处理流程

IIR滤波器将ROI区域分成15x15窗口，可通过配置 blk_xpos和blk_ypos 调整ROI的偏移位置。blk_width和blk_height用来设定每个block的大小。

![](_static/_images/isp_tuning/image88.jpeg)

Figure 3.20‑5 IIR AF ROI 窗口配置

#### AF Statistical Sharpness Calculation

自动对焦模块（AFM）可以通过控制寄存器单元中的配置寄存器进行编程。在启用AFM时，不允许更改配置，否则会导致不可预测的结果。

AF的硬件统计子模块将图像分为多个ROI。对于硬件统计子模块V1，ROI数量为9；对于硬件统计子模块V3，ROI数量为225。

对于每个ROI，其清晰度使用FIR和IIR过滤计算，其权重由weightWindow（用于子模块V1）和afmV3WeightWindow（用于子模块V3）指定。整个图像的清晰度是每个ROI区域加权清晰度的总和。可以通过修改weightWindow\[9\]和afmV3WeightWindow\[225\]数组中ROI区域的权重来优先考虑某些ROI区域的对焦。

| **Parameter**     | **Type**       | **Range** | **Description**                                            | **Default**  **Value** |
| ----------------- | -------------- | --------- | ---------------------------------------------------------- | ---------------------- |
| wightWindow       | float[9]       | [0,255]   | ROI  weight array for hardware statistics   submodule  V1. | 1 for all   elements   |
| afmV3WeightWindow | float32_t[255] | [0,255]   | ROI  weight array for hardware statistics   submodule  V3. | 1 for all   elements   |

Table 3.20‑2 ROI参数

#### AF Mode Introduction

前面提到，AF包含两种自动对焦模式PDAF和CDAF，实际可用于对焦调整的模式如下：

- PDAF模式 仅使用PDAF。对焦过程包括初始化、搜索、锁定和等待。

- CDAF模式 仅使用CDAF。对焦过程包括初始化、搜索、跟踪、锁定和等待。

- 混合模式 同时使用PDAF和CDAF。对焦过程最初经历PDAF初始化和搜索，然后通过CDAF搜索、跟踪、锁定和等待。

可以使用Table 3.20‑3中的参数进行模式选择

| **Parameter** | **Type** | **Range/****Description**                                    | **Default Value**           |
| ------------- | -------- | ------------------------------------------------------------ | --------------------------- |
| mode          | enum     | Selects  the auto focus mode.  The value  range is:  l (Default)  CAMDEV_CDAF_INDIVIDUAL_MODE: CDAF mode.  l CAMDEV_PDAF_INDIVIDUAL_MODE:  PDAF mode.  l CAMDEV_PDAF_CDAF_HYBRID_MODE:  hybrid mode. | CAMDEV_CDAF_INDIVIDUAL_MODE |

Table 3.20‑3 AF模式选择参数

##### PDAF paraments introduction

**PDAF Statistical Calculation**

PDAF搜索需要ROI的相位差。ROI可以是用户定义的，也可以是PDAF统计计算找到的默认ROI。

如果使用默认ROI，将找到图像中所有块的相位差最小的块，并将该块视为ROI。如果使用用户定义的ROI，可以使用pdRoiIndex参数选择一个块作为ROI。

| **Parameter** | **Type** | **Range** | **Description**                              | **Default**  **Value** |
| ------------- | -------- | --------- | -------------------------------------------- | ---------------------- |
| pdRoiIndex    | uint8_t  | [0,48]    | The  selected ROI regions for PDAF focusing. | 0                      |

Table 3.20‑4 PDAF统计计算参数

**PDAF Focusing**

仅当PDAF置信度大于cPdConfThreshold设置的阈值时，才能进行PDAF对焦。

阈值越高，对图像置信度的要求越严格，使其更难进入PDAF对焦过程。然而，阈值过低可能导致由于相位检测偏移计算不可靠而产生的对焦错误。

| **Parameter**    | **Type** | **Range** | **Description**             | **Default**  **Value** |
| ---------------- | -------- | --------- | --------------------------- | ---------------------- |
| cPdConfThreshold | float    | [0,1023]  | PDAF  confidence threshold. | 300                    |

Table 3.20‑5 PDAF对焦计算参数

**PDAF Searching**

如果相位差的绝对值在连续帧的数量（由pdStableCountMax指示）内小于pdShiftThreshold，则PDAF计算的马达移动距离是正确的。然后，如果AF处于PDAF模式，则PDAF锁定；如果AF处于混合模式，则进入CDAF搜索。

| **Parameter**    | **Type**  | **Range** | **Description**                                              | **Default**  **Value** |
| ---------------- | --------- | --------- | ------------------------------------------------------------ | ---------------------- |
| pdShiftThreshold | float32_t | (0,1)     | The  threshold for the absolute value of phase difference.  The  greater the parameter value, the faster the PDAF searching. However, PDAF  stability cannot be guaranteed. | 0.1                    |
| pdStableCountMax | float32_t | [1,10]    | The  number of frames to determine whether the PDAF focusing is completed.  The  smaller the parameter value, the faster the PDAF searching. However, PDAF  stability cannot be guaranteed. | 2                      |

Table 3.20‑6 PDAF搜索速度参数

##### CDAF paraments introduction

CDAF通过最小和最大焦距范围移动马达，并形成清晰度和焦距的抛物线，通过抛物线的顶点，CDAF可以找到最佳焦距和最高清晰度。为了控制计算速度，可以设置CDAF的爬坡算法相关参数cPointsOfCurve进行调节。参数值越大，计算速度越慢，最佳对焦位置越准确。参数值越小，步长越大，计算速度越快。然而，由于步长较大，马达可能跳过最佳对焦位置，导致对焦不准确。

| **Parameter**  | **Type** | **Range** | **Description**                                        | **Default**  **Value** |
| -------------- | -------- | --------- | ------------------------------------------------------ | ---------------------- |
| cPointsOfCurve | uint8_t  | [3,20]    | Number of  steps for the CDAF hill climbing algorithm. | 12                     |

Table 3.20‑7 CDAF爬坡速度参数

##### Hybrid Mode introduction

在大多数情况下，PDAF和CDAF一起使用在混合模式下。然而，使用下表中的参数，可能存在以下特殊情况：

- 仅使用PDAF而不使用CDAF 可以通过设置参数accurateFocusEnable和accurateFocusStep来配置是否在PDAF搜索后使用CDAF，以及CDAF搜索的速度。如果禁用CDAF，混合模式与PDAF模式完全相同。

- 仅使用CDAF而不使用PDAF 当PDAF搜索期间的置信度连续若干帧保持为0时，就会出现这种情况。此时，PDAF搜索被认为失败，AF模块将跳过PDAF并直接开始CDAF搜索。 可以设置lossConfidenceFrameNum来控制PDAF搜索失败的阈值。

| **Parameter**          | **Type** | **Range**    | **Description**                                              | **Default**  **Value** |
| ---------------------- | -------- | ------------ | ------------------------------------------------------------ | ---------------------- |
| accurateFocusEnable    | bool     | {true,false} | Whether  to enable CDAF search after the PDAF search in hybrid mode.   If it is  set to false, the focus searching will stop after the PDAF search completes. | false                  |
| accurateFocusStep      | uint8_t  | [1,20]       | The  number of steps CDAF searches each time if CDAF search is enabled in hybrid  mode.   The  smaller the parameter value, the faster the CDAF search and the poorer the  focusing result. | 5                      |
| lossConfidenceFrameNum | uint8_t  | [1,20]       | The  number of frames to wait after PDAF loses confidence in hybrid mode.  The  greater the parameter value, the less likely to skip the PDAF search in  hybrid focus mode. | 3                      |

Table 3.20‑8混合模式使用的参数

### AF tuning during phase one

如前面介绍中所提到，AF功能在第一阶段是不需要调试的。因此可以在VTuner中对model进行设定，将mode设定为AF_manual 模式。在AF manual 模式下可以通过FocusControl中position的滑块或填入具体的数值来手动调节镜头的位置获得清晰的图像。

![](_static/_images/isp_tuning/image89.png)

Figure 3.20‑6 Manual AF 示意图

### AF tuning during phase two

从摄像头水平放置方位开始AF 基本功能调试，步骤如下：

1.  将ISO12233解析力卡或SFR梯度卡放置在1000lux的照度环境下，用于识别图片的清晰度。摄像头和图卡之间的距离为无穷远（大于2米）。

2.  在VTuner中将AF_mode_id设置为AF_calibration，在这种模式下命令窗口会输出镜头的位置和图像的锐化参数，参数以逗号隔开，如下图。

    ![](_static/_images/isp_tuning/image90.png)

Figure 3.20‑7 镜头位置（左）和锐化参数（右）

3.  将以上数据使用画图工具，将镜头位置和锐化参数在同一坐标系中画出对应的关系图，以此可以获得在无穷远处镜头位置和锐化效果的对应关系。

    ![](_static/_images/isp_tuning/image91.png)

Figure 3.20‑8无穷远对焦反应曲线

4.  从对焦反应曲线上可以看到在190LP的位置之前锐化度是比较平稳的，算法识别理想位置点需要识别到锐化在移动镜头时会产生一定的降低。因此可以判断190LP是在无穷远状态下的对焦点。

5.  重复以上步骤多做几次来确定LP值的准确性，通常1%的偏差范围是可以接受的。如果测试的结果在此精度范围内，则可以将此lens的位置值填写到AF_lms infinity对应的地方。

6.  将获得的无穷远处的镜头位置LP降低15%可以获取远端对焦情况下的镜头位置，即无穷远处的LP\*0.85.将此值写到LUT对应的位置处。

7.  要获取微距情况下的对焦位置，可以在1000lux的光照条件下使用小的解析力卡，设置摄像头和解析力图卡的距离为10cm。运行Calibration模式获取对焦反应曲线。

    ![](_static/_images/isp_tuning/image92.png)

Figure 3.20‑9微距对焦反应曲线

8.  从上图中可以获取锐化最高点对应的LP，将此值写入到AF_lms 对应微距的位置处。从数据中读取到在384 LP处达到锐化最高点，可以重复几次确认对焦的准确度。

9.  可以通过将微距的LP值增加10%得到近端对焦点的LP值，即微距LP\*1.1。将此值填入到Calibration的LUT中。

    重复以上操作来获取镜头朝上及镜头朝下两种位置下的LP值，并将这些值填入到dynamic_calibration.c文件的对应位置中，如下表所示。

    | **Parameter** **name** | **Description**                                 |
    | ---------------------- | ----------------------------------------------- |
    | Down_FarEnd            | Downward orientation FarEnd lens position       |
    | Horizontal_FarEnd      | Horizontal Orientation FarEnd lens  position    |
    | Up_FarEnd              | Upward Orientation FarEnd lens position         |
    | Down_Infinity          | Downward orientation Infinity lens  position    |
    | Horizontal_Infinity    | Horizontal orientation inifinity lens  position |
    | Up_Infinity            | Upward orientation inifinity lens position      |
    | Down_Macro             | Downward orientation macro lens position        |
    | Horizontal_Macro       | Horizontal orientation macro lens position      |
    | Up_Macro               | Upward orientation macro lens position          |
    | Down_NearEnd           | Downward orientation NearEnd lens position      |
    | Horizontal_NearEnd     | Horizontal orientation NearEnd lens  position   |
    | Up_NearEnd             | Upward orientation NearEnd lens  position       |

Table 3.20‑9 AF 基本校正参数表

AF控制操作的校正参数如下表。

| **Parameter** **name** | **Description**                                              |
| ---------------------- | ------------------------------------------------------------ |
| Step_Number            | The total steps  from FarEnd to NearEnd                      |
| Skip_frames-in         | Number of frames be  skipped before AF start                 |
| Skip_frames_moves      | Number of frames be  skipped before each AF iteration        |
| Dynamic_range_th       | Focus Value  Contrast threshold                              |
| Spot_tolerance         | Focus value dynamic  range minimum threshold of zones which used to filter out unqualified ROI in  multi-spot |
| Exit_th                | Focus Value  downhill threshold                              |
| Caf_trigger_th         | CAF scene change  trigger threshold                          |
| Caf_stable_th          | CAF scene change stable threshold                            |

Table 3.20‑10 AF 扩展校正参数表

在VTunerClinet工具中Caf_trigger_th 需要进行调试来检测到实际场景的改变，当实际场景的特性值变化幅度大于Caf_trigger_th阈值则会触发CAF的调整。CAF_stable_th 参数用于判断场景的稳定性，实际场景特性值的变化幅度要小于Caf_stable_th的设定值。一旦场景的特性值大于Caf_trigger_th或小于Caf_stable_th将会进行CAF的调整。

### AF tuning during phase three

在第二阶段完成auto focus的调试后，基本不太需要重新进行调试，AF功能已经可以用于对焦各种场景。可以在VTuner中选定AF_mode_id的具体模式AF_auto_single或AF_auto_continues进行使用了。

AF_auto_single-每次新场景变换都需要进行手动对焦时，选择AF_auto_single模式。摄像头会对当前场景进行对焦并将VCM稳定在最后的LP。重新对焦或更换其他场景，则重复以上的操作。

AF_auto_continuous-当选择AF_auto_continuous模式时，系统会持续的刷新对焦数据以此来寻找最佳的对焦位置。在这种模式下系统在持续的提供不同场景的最佳对焦点，这意味着使用这种模式需要比AF_auto_single更强的处理能力。
