Note · 2024-11-11

相机成像与 ISP

相机的成像原理,以及从 RAW 图到彩色图像的 ISP(Image Signal Processing)流程和常用算法。

相机成像

CCD vs CMOS

  • CCD:全称 Charge Coupled Device,即电荷耦合器件
  • CMOS:全称 Complementary Metal Oxide Semiconductor,即互补金属氧化物半导体

这两种传感器都由光电二极管阵列组成,每个光电二极管把接收到的光信号转化为电荷。两者的基本工作原理相似:传感器在曝光时间内积累电荷,得到每个像素的光强。随后,电荷被转换为电压并放大,再经模数转换(ADC)变成数字值,最终得到原始的 RAW 图像数据。

在具体的实现方式上,两者有一定的区别:

  • CCD:每个像素的电荷按行逐级移位,转移到传感器边缘的公共输出节点,在那里统一转换为电压信号,即一行行读出。这种方式噪声低、一致性好、图像质量高,但电荷转移需要多路高压时钟驱动,功耗较高,读出速度也较慢。
  • CMOS:每个像素都有独立的放大器,能在像素内直接把电荷转换为电压并放大。各像素的转换过程相对独立,读出更快、功耗更低,但早期 CMOS 在低光照环境下噪声较多。

CCD vs CMOS 工作原理CCD vs CMOS 工作原理

总的来看,CMOS 传感器相比 CCD 工艺简单、成本更低。随着 CMOS 在降低噪声、提高低光照性能和图像质量方面不断进步,它已经逐渐取代 CCD 成为主流。如今 CCD 主要用于一些对图像质量要求极高的专业领域。

Bayer 阵列与 RAW 图像

上一节提到,sensor 把光强信号转化为电压信号,从而得到 RAW 图像。光电二极管本身只感知光强、不区分颜色,因此如果不加任何处理,得到的 RAW 图只有亮度,是一张黑白图像。

为了合成彩色图像,需要得到每个像素处 R、G、B 三个通道的亮度值。要获得某个通道的亮度值,可以在光电二极管前加上只允许红 / 绿 / 蓝色光通过的滤光片。常用的排列方式是每 2×2 个像素按 R、G、G、B 排列。为什么是两个绿色?因为人眼对绿色更敏感,用两个绿色像素可以提高亮度细节的解析力。这种排列方式称为 Bayer 阵列(Bayer Pattern),由柯达工程师 Bryce Bayer 提出,1976 年获得专利。

Bayer 阵列(局部)Bayer 阵列(局部) Bayer 阵列(整体)Bayer 阵列(整体)

除了最常用的 Bayer 阵列,一些厂商也采用了其他排列方式,例如索尼的 RGBE(红、绿、蓝、翠绿 Emerald),华为的 RYYB(红、黄、黄、蓝),以及富士 X-Trans 的乱七八糟排列(bushi,实际是 6×6 的非周期性排列,用来减少摩尔纹)。

索尼 RGBE索尼 RGBE 华为 RYYB华为 RYYB 富士 X-Trans富士 X-Trans

把这些按 Bayer 排列的电信号转换成数字信号并保存下来,就得到了 RAW 图像。

RAW 图像RAW 图像

此时的图像依旧是黑白的,放大局部还会看到马赛克一样的纹理。为了得到最终的图像,需要完成一系列图像信号处理,即 Image Signal Processing(ISP)。

Image Signal Processing(ISP)

坏点校正(Dead Pixel Correction,DPC)

根据是否会发生变化,坏点可以分为静态坏点和动态坏点。

  • 静态坏点:不随时间、增益等改变,通常是 sensor 制造时因工艺原因产生的。
  • 动态坏点:由增益、温度等因素引起,会随时间变化。

在 ISP 阶段需要对图像中的坏点进行校正。静态坏点通常在传感器产线上标定,其位置会被记录到 OTP(One Time Programmable)存储器中,用于后续校正。

动态坏点的校正在静态坏点校正之后进行。校正时逐一检查每个像素与其周围一定范围内同通道像素的差异,如果与周围所有像素的差都超过设定阈值,则判定为坏点。对于坏点,通常用同通道内周围像素的平均值(或沿梯度最小方向的插值)替代,从而恢复图像的完整性。

坏点校正坏点校正

示例代码
/**
 * @brief Performs dead pixel correction (DPC) on RAW image data by identifying
 * and correcting pixels that differ significantly from their neighbors.
 *
 * @param raw       Reference to the input RAW image data.
 * @param thres     Threshold value for detecting dead pixels. A pixel is
 * considered dead if it deviates from its neighboring pixels by more than this
 * threshold.
 * @param mode      DPC correction mode. Options are:
 *                  - DPC_MODE_MEAN: Replaces the dead pixel value with the
 * average of its immediate neighbors.
 *                  - DPC_MODE_GRADIENT: Replaces the dead pixel based on the
 * smallest gradient among neighboring pixels.
 *                  - DPC_MODE_UNKNOWN: Throws an error if the mode is
 * unrecognized.
 * @param clip      Maximum allowable pixel value after correction. Values
 * exceeding this are clipped.
**/
void DPC(ImageRaw& raw, uint16_t thres, DPC_MODE mode, uint16_t clip)
{
	ImageRaw* raw_pad = new ImageRaw(raw);
	raw_pad->padding(2, PADDING_MODE_REFLECT);
 
	for (int y = 0; y < raw_pad->getHeight() - 4; y++)
	{
		for (int x = 0; x < raw_pad->getWidth() - 4; x++)
		{
			uint16_t p0, p1, p2, p3, p4, p5, p6, p7, p8;
			uint16_t dv, dh, ddl, ddr, minimal;
 
			p0 = raw_pad->at(y + 2, x + 2);
			p1 = raw_pad->at(y, x);
			p2 = raw_pad->at(y, x + 2);
			p3 = raw_pad->at(y, x + 4);
			p4 = raw_pad->at(y + 2, x);
			p5 = raw_pad->at(y + 2, x + 4);
			p6 = raw_pad->at(y + 4, x);
			p7 = raw_pad->at(y + 4, x + 2);
			p8 = raw_pad->at(y + 4, x + 4);
			if ((ABS(p1 - p0) > thres) && (ABS(p2 - p0) > thres) && (ABS(p3 - p0) > thres) && (ABS(p4 - p0) > thres) && 
				(ABS(p5 - p0) > thres) && (ABS(p6 - p0) > thres) && (ABS(p7 - p0) > thres) && (ABS(p8 - p0) > thres))
			{
				switch (mode)
				{
				case DPC_MODE_MEAN:
					p0 = (p2 + p4 + p5 + p7) / 4;
					break;
				case DPC_MODE_GRADIENT:
					dv			= ABS(2 * p0 - p2 - p7);
					dh			= ABS(2 * p0 - p4 - p5);
					ddl		= ABS(2 * p0 - p1 - p8);
					ddr		= ABS(2 * p0 - p3 - p6);
					minimal	= MIN(MIN(MIN(dv, dh), ddl), ddr);
					if (minimal == dv)			p0 = (p2 + p7 + 1) / 2;  // Adding +1 here helps prevent rounding errors in integer division.
					else if (minimal == dh)		p0 = (p4 + p5 + 1) / 2;
					else if (minimal == ddl)	p0 = (p1 + p8 + 1) / 2;
					else						p0 = (p3 + p6 + 1) / 2;
					break;
				case DPC_MODE_UNKNOWN:
					TRACE_DEBUG_LOG_ERROR("Unknown DPC Mode:%s\n", mode);
					throw "Unknown DPC mode";
					break;
				default:
					TRACE_DEBUG_LOG_ERROR("Unknown DPC Mode:%s\n", mode);
					throw "Unknown DPC mode";
					break;
				}
				raw.at(y, x) = p0;
			}
		}
	}
	raw.clip(0, clip);
	delete raw_pad;
}

黑电平校正(Black Level Correction,BLC)

黑电平校正又称暗电流校正。即使完全没有光照,传感器的输出也不为零,图像的「黑」与真实情况存在偏差。这个偏移量主要有两个来源:一是 sensor 在 A/D 转换前人为加入的固定偏置(见下面的说明);二是暗电流,即温度等物理因素在没有光照时产生的电荷。黑电平校正模块通过标定确定这个偏移量,后续的 ISP 模块要先减掉它,才能保证图像亮度的准确性。

模拟信号很微弱时,可能无法被 A/D 转换出来,导致光线很暗时图像细节丢失。因此 sensor 会在 A/D 转换前给模拟信号加一个固定偏置,让输出的数字信号保留更多暗部细节。

常用的标定方法是在传感器完全遮光的情况下拍摄「暗帧」,记录每个像素的数字输出,计算整幅图像(或每个 Bayer 通道)的平均值,有时也用中值。这个值就是传感器的黑电平偏移。校正时把它从每个像素值中减去,恢复图像的真实亮度。

黑电平校正黑电平校正

示例代码

示例沿用 ISPLab 的写法:r / gr / gb / b 是加到对应通道上的校正量(相当于负的黑电平),alpha / beta 用来补偿绿色通道与相邻红 / 蓝像素之间的串扰。

/**
 * @brief Performs black level correction (BLC) on RAW image data based on the
 * specified Bayer pattern.
 *
 * @param raw          Reference to the input RAW image data.
 * @param r            Black level correction value for the red channel.
 * @param gr           Black level correction value for the green channel (red
 * row).
 * @param gb           Black level correction value for the green channel (blue
 * row).
 * @param b            Black level correction value for the blue channel.
 * @param alpha        Alpha coefficient for adjusting the green channel (red
 * row).
 * @param beta         Beta coefficient for adjusting the green channel (blue
 * row).
 * @param bayer_pattern The Bayer pattern used in the RAW data (e.g., RGGB,
 * BGGR, GBRG, GRBG).
 * @param clip         Maximum allowable pixel value after correction. Values
 * exceeding this are clipped.
 */
void BLC(ImageRaw& raw, uint16_t r, uint16_t gr, uint16_t gb, uint16_t b, float alpha, float beta, BAYER_PATTERN bayer_pattern, uint16_t clip)
{
	switch (bayer_pattern)
	{
	case BAYER_PATTERN_RGGB:
		for (int y = 0; y < raw.getHeight(); y+=2)
		{
			for (int x = 0; x < raw.getWidth(); x+=2)
			{
				raw.at(y, x)			+= r;									// r
				raw.at(y + 1, x + 1)	+= b;									// b
				raw.at(y, x + 1)		+= gr + alpha * raw.at(y, x);			// gr
				raw.at(y + 1, x)		+= gb + beta * raw.at(y + 1, x + 1);	// gb
			}
		}
		break;
	case BAYER_PATTERN_BGGR:
		for (int y = 0; y < raw.getHeight(); y+=2)
		{
			for (int x = 0; x < raw.getWidth(); x+=2)
			{
				raw.at(y, x) += b;
				raw.at(y + 1, x + 1) += r;
				raw.at(y, x + 1) += gb + beta * raw.at(y, x);
				raw.at(y + 1, x) += gr + alpha * raw.at(y + 1, x + 1);
			}
		}
		break;
	case BAYER_PATTERN_GBRG:
		for (int y = 0; y < raw.getHeight(); y+= 2)
		{
			for (int x = 0; x < raw.getWidth(); x+= 2)
			{
				raw.at(y, x + 1) += b;
				raw.at(y + 1, x) += r;
				raw.at(y, x) += gb + beta * raw.at(y, x + 1);
				raw.at(y + 1, x + 1) += gr + alpha * raw.at(y + 1, x);
			}
		}
		break;
	case BAYER_PATTERN_GRBG:
		for (int y = 0; y < raw.getHeight(); y+= 2)
		{
			for (int x = 0; x < raw.getWidth(); x+= 2)
			{
				raw.at(y + 1, x) += b;
				raw.at(y, x + 1) += r;
				raw.at(y + 1, x + 1) += gb + beta * raw.at(y + 1, x);	
				raw.at(y, x) += gr + alpha * raw.at(y, x + 1);
			}
		}
		break;
	case BAYER_PATTERN_UNKNOWN:
	default:
		TRACE_DEBUG_LOG_ERROR("Unknown Bayer Pattern:%s\n", bayer_pattern);
		throw "Unknown bayer pattern";
		break;
	}
	raw.clip(0, clip);
}

镜头阴影校正(Lens Shading Correction,LSC)

Lens Shading 是镜头与图像传感器的光学特性共同造成的现象:图像的亮度和颜色在视场(Field of View,FOV)内分布不均匀,通常中心亮、边缘暗,并可能伴随颜色偏移。它是暗角(Vignetting)的扩展,包括亮度阴影(Luma Shading)和色彩阴影(Chroma Shading)。

亮度(Luma)阴影

Luma Shading 也称渐晕(Vignetting)。由于透镜组的光学特性,入射光偏离光轴的角度越大,越多的光被光阑遮挡而无法到达感光平面,因此越靠近边缘的像素越暗。

镜头入射光传递路径镜头入射光传递路径 Lens Shading 导致的暗角Lens Shading 导致的暗角

此外,对于 FSI(前照式)工艺的 sensor,Luma Shading 还有一个重要成因:边缘像素的入射光角度大,经过微透镜后焦点偏离感光区,造成能量损失。解决办法是让微透镜相对感光区产生偏移:从中心到边缘,微透镜的排列间距略小于像素间距,越靠近边缘,微透镜向中心偏移得越多,正好补偿大角度入射光造成的焦点偏移,使 sensor 能接受的主光线角(CRA,Chief Ray Angle)与镜头匹配,光线能更好地汇聚到感光区。

焦点错位导致能量损失焦点错位导致能量损失 边缘微透镜偏移补偿焦点错位边缘微透镜偏移补偿焦点错位

扩展阅读:FSI vs BSI、什么是 CRA

色彩(Chroma)阴影

Chroma Shading 是 Lens Shading 的一种特殊情况,主要表现为从中心向边缘的色晕。

Chroma Shading 色晕Chroma Shading 色晕

关于 Chroma Shading 的成因,看了很多博客和文章,说法不一,总结起来主要有两个:

  1. 镜头材料对不同波长的光折射率不同,不同色光的焦平面并不重合,从而产生色差。
  2. 干涉型红外截止滤光片(IR-Cut Filter)的截止波长会随入射角变化:入射角越大,截止波长越向短波方向偏移,导致边缘处红光通过率下降、各通道响应比例改变,形成从中心向边缘的色晕。

不同色光的焦平面不重合不同色光的焦平面不重合 不同入射角下 IR 滤光片的通过率不同入射角下 IR 滤光片的通过率

校正算法

目前常用的镜头阴影校正算法是增益法。存储每个像素的校正系数会占用大量空间,所以实际实现通常把图像划分为 n×n 网格(一般 16×16 左右),只存储网格点处的校正系数,网格之间的像素通过双线性(或双三次)插值得到校正系数。

亮度衰减的理论基础是余弦四次方定律:Iθ=I0cos⁡4θI_\theta = I_0 \cos^4 \theta,即像素亮度随离轴视场角 θ\theta 的增大按 cos⁡4θ\cos^4\theta 的比例下降。

网格点处的校正系数通过标定得到:在均匀光源下拍摄参考图像,记录每个像素的实际亮度值,与理想亮度相比,两者的比值就是校正系数。

G(i,j)=Iideal(i,j)Iobserved(i,j)G(i,j)=\frac{I_{\mathrm{ideal}}(i,j)}{I_{\mathrm{observed}}(i,j)}

镜头阴影校正前后对比镜头阴影校正前后对比

示例代码:Luma Shading Correction(按半径的简化模型)
/**
 * @brief Performs lens shading correction (LSC) on RAW image data to compensate
 * for brightness falloff towards the edges.
 *
 * @param raw       Reference to the input RAW image data.
 * @param intensity Intensity of the lens shading correction. Higher values
 * apply stronger correction.
 * @param minR      Minimum radius (distance from the center) for applying
 * correction. If less than 0, defaults to 0.
 * @param maxR      Maximum radius (distance from the center) for applying
 * correction. If less than 0, defaults to the distance from the center to the
 * farthest corner of the image.
 * @param clip      Maximum allowable pixel value after correction. Values
 * exceeding this are clipped.
 */
 
void LSC(ImageRaw& raw, uint16_t intensity, int minR, int maxR, uint16_t clip)
{
	if (minR < 0) minR = 0;
	if (maxR < 0) maxR = sqrt(pow(raw.getHeight() / 2, 2) + pow(raw.getWidth() / 2, 2));
	for (int y = 0; y < raw.getHeight(); y++)
	{
		for (int x = 0; x < raw.getWidth(); x++)
		{
			int r = sqrt(pow((y - raw.getHeight() / 2), 2) + pow((x - raw.getWidth() / 2), 2));
			float factor = (float)(r - minR) / (maxR - minR);  // 先转 float,避免整数除法恒为 0
			raw.at(y, x) = raw.at(y, x) * (1 + intensity * (factor + 0.5));
		}
	}
	raw.clip(0, clip);
}
示例代码:色度噪声滤波(Chroma Noise Filtering,CNF)

注意:这段代码来自 ISPLab 的 CNF 模块,作用是抑制 R / B 通道上的色度噪点,并不是严格意义上的 Chroma Shading 校正。Chroma Shading 的标准做法是对 R、Gr、Gb、B 四个通道分别标定增益网格,方法和上面的 Luma Shading 相同。放在这里作为「按通道处理颜色偏差」的参考。

float __cnc(const char* is_color, float center, float avgG, float avgC1, float avgC2, float r_gain, float gr_gain, float gb_gain, float b_gain)
{
	float dampFactor = 1.0;
	float signalGap = center - MAX(avgG, avgC2);
	if (strcmp(is_color, "r") == 0)
	{
		if (r_gain <= 1.0) dampFactor = 1.0;
		else if (r_gain > 1.0 && r_gain <= 1.2) dampFactor = 0.5;
		else if (r_gain > 1.2) dampFactor = 0.3;
	}
	if (strcmp(is_color, "b") == 0)
	{
		if (b_gain <= 1.0) dampFactor = 1.0;
		else if (b_gain > 1.0 && b_gain <= 1.2) dampFactor = 0.5;
		else if (b_gain > 1.2) dampFactor = 0.3;
	}
	float chromaCorrected = MAX(avgG, avgC2) + dampFactor * signalGap;
	float signalMeter = 0.299 * avgC2 + 0.587 * avgG + 0.114 * avgC1;
	if (strcmp(is_color, "r") == 0) signalMeter = 0.299 * avgC1 + 0.587 * avgG + 0.114 * avgC2;
	else if (strcmp(is_color, "b") == 0) signalMeter = 0.299 * avgC2 + 0.587 * avgG + 0.114 * avgC1;
	float fade1 = 0, fade2 = 0;
	if (signalMeter <= 30) fade1 = 1.0;
	else if (signalMeter > 30 && signalMeter <= 50) fade1 = 0.9;
	else if (signalMeter > 50 && signalMeter <= 70) fade1 = 0.8;
	else if (signalMeter > 70 && signalMeter <= 100) fade1 = 0.7;
	else if (signalMeter > 100 && signalMeter <= 150) fade1 = 0.6;
	else if (signalMeter > 150 && signalMeter <= 200) fade1 = 0.3;
	else if (signalMeter > 200 && signalMeter <= 250) fade1 = 0.1;
	else fade1 = 0;
	if (avgC1 <= 30) fade2 = 1.0;
	else if (avgC1 > 30 && avgC1 <= 50) fade2 = 0.9;
	else if (avgC1 > 50 && avgC1 <= 70) fade2 = 0.8;
	else if (avgC1 > 70 && avgC1 <= 100) fade2 = 0.6;
	else if (avgC1 > 100 && avgC1 <= 150) fade2 = 0.5;
	else if (avgC1 > 150 && avgC1 <= 200) fade2 = 0.3;
	else fade2 = 0;
	float fadeTot = fade1 * fade2;
	return (1 - fadeTot) * center + fadeTot * chromaCorrected;
}
 
 
void __cnd(int y, int x, ImageRaw* img, float thres, int& is_noise, float& avgG, float& avgC1, float& avgC2)
{
	avgG = 0, avgC1 = 0, avgC2 = 0;
	is_noise = 0;
 
	for (int i = y - 4; i < y + 4; i++)
	{
		for (int j = x - 4; j < x + 4; j++)
		{
			if ((i % 2 == 1) && (j % 2 == 0))		avgG = avgG + img->at(i, j);
			else if ((i % 2 == 0) && (j % 2 == 1))	avgG = avgG + img->at(i, j);
			else if ((i % 2 == 0) && (j % 2 == 0))	avgC1 = avgC1 + img->at(i, j);
			else if ((i % 2 == 1) && (j % 2 == 1))	avgC2 = avgC2 + img->at(i, j);
		}
	}
	avgG = avgG / 40;
	avgC1 = avgC1 / 25;
	avgC2 = avgC2 / 16;
	float center = img->at(y, x);
	if ((center > avgG + thres) && (center > avgC2 + thres))
	{
		if ((avgC1 > avgG + thres) && (avgC1 > avgC2 + thres))
		{
			is_noise = 1;
		}
		else
		{
			is_noise = 0;
		}
	}
	else
	{
		is_noise = 0;
	}
}
 
 
float __cnf(const char* is_color, int y, int x, ImageRaw* img, float thres, float r_gain, float gr_gain, float gb_gain, float b_gain)
{
	int is_noise;
	float avgG, avgC1, avgC2;
	__cnd(y, x, img, thres, is_noise, avgG, avgC1, avgC2);
 
	float pix_out;
	if (is_noise == 1)
	{
		pix_out = __cnc(is_color, img->at(y, x), avgG, avgC1, avgC2, r_gain, gr_gain, gb_gain, b_gain);
	}
	else
	{
		pix_out = img->at(y, x);
	}
 
	return pix_out;
}
 
 
void CNF(ImageRaw& img, BAYER_PATTERN bayer_pattern, float threshold, float r_gain, float gr_gain, float gb_gain, float b_gain, uint16_t clip)
{
	ImageRaw* img_pad = new ImageRaw(img);
	img_pad->padding(4, PADDING_MODE_REFLECT);
 
	uint16_t r, gr, gb, b;
 
	for (int y = 0; y < img_pad->getHeight() - 8 - 1; y += 2) {
		for (int x = 0; x < img_pad->getWidth() - 8 - 1; x += 2) {
			switch (bayer_pattern) {
			case BAYER_PATTERN_RGGB:
 
				r = img_pad->at(y + 4, x + 4);
				gr = img_pad->at(y + 4, x + 5);
				gb = img_pad->at(y + 5, x + 4);
				b = img_pad->at(y + 5, x + 5);
 
				img.at(y, x) = __cnf("r", y + 4, x + 4, img_pad, threshold, r_gain, gr_gain, gb_gain, b_gain);
				img.at(y, x + 1) = gr;
				img.at(y + 1, x) = gb;
				img.at(y + 1, x + 1) = __cnf("b", y + 5, x + 5, img_pad, threshold, r_gain, gr_gain, gb_gain, b_gain);
 
				break;
			case BAYER_PATTERN_BGGR:
 
				b = img_pad->at(y + 4, x + 4);
				gb = img_pad->at(y + 4, x + 5);
				gr = img_pad->at(y + 5, x + 4);
				r = img_pad->at(y + 5, x + 5);
 
				img.at(y, x) = __cnf("b", y + 4, x + 4, img_pad, threshold, r_gain, gr_gain, gb_gain, b_gain);
				img.at(y, x + 1) = gb;
				img.at(y + 1, x) = gr;
				img.at(y + 1, x + 1) = __cnf("r", y + 5, x + 5, img_pad, threshold, r_gain, gr_gain, gb_gain, b_gain);
 
				break;
			case BAYER_PATTERN_GBRG:
 
				gb = img_pad->at(y + 4, x + 4);
				b = img_pad->at(y + 4, x + 5);
				r = img_pad->at(y + 5, x + 4);
				gr = img_pad->at(y + 5, x + 5);
 
				img.at(y, x) = gb;
				img.at(y, x + 1) = __cnf("b", y + 4, x + 5, img_pad, threshold, r_gain, gr_gain, gb_gain, b_gain);
				img.at(y + 1, x) = __cnf("r", y + 5, x + 4, img_pad, threshold, r_gain, gr_gain, gb_gain, b_gain);
				img.at(y + 1, x + 1) = gr;
 
				break;
			case BAYER_PATTERN_GRBG:
 
				gr = img_pad->at(y + 4, x + 4);
				r = img_pad->at(y + 4, x + 5);
				b = img_pad->at(y + 5, x + 4);
				gb = img_pad->at(y + 5, x + 5);
 
				img.at(y, x) = gr;
				img.at(y, x + 1) = __cnf("r", y + 4, x + 5, img_pad, threshold, r_gain, gr_gain, gb_gain, b_gain);
				img.at(y + 1, x) = __cnf("b", y + 5, x + 4, img_pad, threshold, r_gain, gr_gain, gb_gain, b_gain);
				img.at(y + 1, x + 1) = gb;
 
				break;
			case BAYER_PATTERN_UNKNOWN:
			default:
				TRACE_DEBUG_LOG_ERROR("Unknown Bayer Pattern:%s\n", bayer_pattern);
				break;
 
			}
		}
	}
 
	img.clip(0, clip);
	delete img_pad;
}

抗锯齿滤波(Anti-aliasing Filtering,AAF)

如果图像中含有大量高频成分,在降采样时就会产生锯齿(aliasing)。要去除锯齿,需要先对原图像做平滑(低通滤波)。常用的方法有高斯滤波器(Gaussian Filter)和双边滤波器(Bilateral Filter)。

高斯滤波器

G(x,y)=12πσ2exp⁡(−x2+y22σ2)G(x,y)=\frac1{2\pi\sigma^2}\exp\left(-\frac{x^2+y^2}{2\sigma^2}\right)

其中:

  • G(x,y)G(x,y) 是高斯核在坐标 (x,y)(x,y) 处的值;
  • σ\sigma 是高斯分布的标准差,决定平滑强度;
  • x,yx,y 是相对核中心的坐标。

双边滤波器

W(p,q)=exp⁡(−∥p−q∥22σs2)⋅exp⁡(−∣I(p)−I(q)∣22σr2)W(p,q)=\exp\left(-\frac{\|p-q\|^2}{2\sigma_s^2}\right)\cdot\exp\left(-\frac{|I(p)-I(q)|^2}{2\sigma_r^2}\right)

其中:

  • W(p,q)W(p,q) 是像素 qq 对 pp 的权重;
  • ∥p−q∥\|p-q\| 是两像素在空间上的距离;
  • ∣I(p)−I(q)∣|I(p)-I(q)| 是两像素灰度值的差异;
  • σs\sigma_s 是空间域高斯标准差;
  • σr\sigma_r 是强度域高斯标准差。

滤波结果:

I′(p)=∑q∈SW(p,q)⋅I(q)∑q∈SW(p,q)I^{\prime}(p)=\frac{\sum_{q\in S}W(p,q)\cdot I(q)}{\sum_{q\in S}W(p,q)}

其中 SS 是滤波窗口,I′(p)I^{\prime}(p) 是像素 pp 的滤波值。

两者对比:

特性高斯滤波器双边滤波器
性质线性滤波非线性滤波
边缘保留不保留边缘,模糊边缘保留边缘,对边缘影响较小
计算复杂度低高
实现难度简单较复杂
适用场景快速平滑、高频噪声较少的场景高质量抗锯齿,保留纹理和边缘

抗锯齿滤波前抗锯齿滤波前 抗锯齿滤波后抗锯齿滤波后

示例代码(双边滤波器)
/**
 * @brief Computes the Gaussian weight for a given difference.
 * 
 * @param x The difference (distance in space or intensity).
 * @param sigma The standard deviation of the Gaussian function.
 * @return The computed Gaussian weight.
 */
double gaussian(double x, double sigma) {
    return std::exp(-x * x / (2.0 * sigma * sigma));
}
 
/**
 * @brief Applies a bilateral filter to an ImageRaw object.
 * 
 * @param src Input image.
 * @param dst Output image (should be pre-initialized to the same size as src).
 * @param d The diameter of the filter kernel (must be an odd number).
 * @param sigmaColor The standard deviation in the intensity space.
 * @param sigmaSpace The standard deviation in the spatial space.
 */
void applyBilateralFilter(const ImageRaw& src, ImageRaw& dst, int d, double sigmaColor, double sigmaSpace) {
    int height = src.getHeight();
    int width = src.getWidth();
    
    // Ensure kernel size is odd
    if (d % 2 == 0) {
        throw std::invalid_argument("Kernel size must be odd.");
    }
 
    // Precompute spatial Gaussian weights
    int radius = d / 2;
    std::vector<std::vector<double>> spatialKernel(d, std::vector<double>(d, 0.0));
    for (int i = -radius; i <= radius; ++i) {
        for (int j = -radius; j <= radius; ++j) {
            spatialKernel[i + radius][j + radius] = gaussian(std::sqrt(i * i + j * j), sigmaSpace);
        }
    }
 
    // Perform bilateral filtering
    for (int i = 0; i < height; ++i) {
        for (int j = 0; j < width; ++j) {
            double weightedSum = 0.0;
            double normalizationFactor = 0.0;
 
            uint16_t centerPixel = src.at(i, j);
 
            for (int ki = -radius; ki <= radius; ++ki) {
                for (int kj = -radius; kj <= radius; ++kj) {
                    int ni = i + ki;
                    int nj = j + kj;
 
                    // Skip out-of-bound pixels
                    if (ni < 0 || ni >= height || nj < 0 || nj >= width) {
                        continue;
                    }
 
                    uint16_t neighborPixel = src.at(ni, nj);
 
                    // Compute intensity Gaussian weight
                    double intensityWeight = gaussian(std::abs((int)centerPixel - (int)neighborPixel), sigmaColor);
 
                    // Compute final weight
                    double weight = spatialKernel[ki + radius][kj + radius] * intensityWeight;
 
                    // Accumulate weighted sum and normalization factor
                    weightedSum += neighborPixel * weight;
                    normalizationFactor += weight;
                }
            }
 
            // Assign the filtered value to the destination image
            dst.at(i, j) = static_cast<uint16_t>(weightedSum / normalizationFactor);
        }
    }
}

自动白平衡(Auto White Balance,AWB)

人的视觉系统具有色彩恒常性:看白色物体时,基本不受环境光源变化的影响。image sensor 不能像人眼一样自动调节,在不同色温的光源下,拍出的白色会偏色。自动白平衡就是模拟人的色彩恒常能力,去除光源引起的偏色,还原自然的色彩。

自动白平衡算法按技术路线可以归为几大类:

  • 场景假设模型:灰度世界、完美反射
  • 点统计模型:白点估计、分块加权

1. 灰度世界算法

该算法假设:对于一幅色彩丰富的图片,R、G、B 三个通道的平均值应该相等,都等于一个「灰色」值 KK。KK 的一种取法是三个通道均值的平均。确定 KK 之后,各通道的校正系数分别为 kr=K/Rmeank_r=K/R_{mean}、kg=K/Gmeank_g=K/G_{mean}、kb=K/Bmeank_b=K/B_{mean},其中 RmeanR_{mean}、GmeanG_{mean}、BmeanB_{mean} 分别是图像 R、G、B 通道的均值。

示例代码
#include <iostream>
#include <vector>
#include <numeric>
#include <stdexcept>
 
/**
 * @brief Apply the Gray World Algorithm to an ImageRaw.
 * 
 * This algorithm adjusts the R, G, and B channels of the input image so that their
 * mean values are equal to a common gray level \( K \). This corrects the overall
 * color balance of the image.
 * 
 * @param src Input image. Must have 3 channels (RGB format).
 * @param dst Output image. Must have the same size as the input image.
 */
void grayWorldAlgorithm(const ImageRaw& src, ImageRaw& dst) {
    // Validate input image dimensions
    if (src.getWidth() != dst.getWidth() || src.getHeight() != dst.getHeight()) {
        throw std::invalid_argument("Input and output images must have the same dimensions.");
    }
 
    int width = src.getWidth();
    int height = src.getHeight();
 
    // Accumulators for R, G, B channel sums
    uint64_t sumR = 0, sumG = 0, sumB = 0;
    int numPixels = width * height;
 
    // Compute channel-wise sums
    for (int i = 0; i < height; ++i) {
        for (int j = 0; j < width; ++j) {
            uint16_t r = src.at(i, j * 3);     // Assume RGB channels are stored in sequence
            uint16_t g = src.at(i, j * 3 + 1);
            uint16_t b = src.at(i, j * 3 + 2);
            sumR += r;
            sumG += g;
            sumB += b;
        }
    }
 
    // Compute mean values for each channel
    double meanR = static_cast<double>(sumR) / numPixels;
    double meanG = static_cast<double>(sumG) / numPixels;
    double meanB = static_cast<double>(sumB) / numPixels;
 
    // Compute the target gray value \( K \) as the average of all channel means
    double K = (meanR + meanG + meanB) / 3.0;
 
    // Compute correction factors
    double kR = K / meanR;
    double kG = K / meanG;
    double kB = K / meanB;
 
    // Apply correction to each pixel
    for (int i = 0; i < height; ++i) {
        for (int j = 0; j < width; ++j) {
            uint16_t r = src.at(i, j * 3);
            uint16_t g = src.at(i, j * 3 + 1);
            uint16_t b = src.at(i, j * 3 + 2);
 
            // Adjust each channel and clip the values to the valid range
            dst.at(i, j * 3) = static_cast<uint16_t>(std::min(std::max(r * kR, 0.0), 65535.0));
            dst.at(i, j * 3 + 1) = static_cast<uint16_t>(std::min(std::max(g * kG, 0.0), 65535.0));
            dst.at(i, j * 3 + 2) = static_cast<uint16_t>(std::min(std::max(b * kB, 0.0), 65535.0));
        }
    }
}

2. 完美反射法

该算法假设:图像中存在一个「镜面」,能完全反射照到它上面的光线。那么在特定光源下,这个「镜面」的颜色就是光源的颜色。理想情况下,镜面应该呈现三刺激值为 [255, 255, 255] 的纯白色(白点有多种定义,这是其中一种),因此各通道的校正系数分别为 kr=255/Rmaxk_r=255/R_{max}、kg=255/Gmaxk_g=255/G_{max}、kb=255/Bmaxk_b=255/B_{max},其中 RmaxR_{max}、GmaxG_{max}、BmaxB_{max} 分别是图像 R、G、B 通道的最大值。实际实现中为了抗噪,通常取亮度最高的前若干百分比像素的均值,而不是单个最大值。

3. 统计加权白点法(通常在对画质要求较高时使用)

该算法首先对传感器做光源标定,得到色温曲线:在产线上用标准白 / 灰卡,在不同光源(D65、A 光、H 光等)下拍照,算出每种光源下的 R/G=Rmean/GmeanR/G = R_{mean}/G_{mean} 和 B/G=Bmean/GmeanB/G = B_{mean}/G_{mean},连成一条折线。校正时把图片分成 M 块,分别计算每块的 R/GR/G 和 B/GB/G,作为一个候选「白点」;靠近折线区域(红色)的白点权重高,远离的(蓝色)权重低。加权平均得到最终白点后,再用折线上相邻的标定点插值,得到最终的白平衡增益(R、B 通道增益分别为 G/RG/R 和 G/BG/B)。

色温曲线色温曲线

去马赛克(Demosaicing)

前面提到,普通的 CMOS 图像传感器无法直接「捕获」色彩,解决方法是通过 Bayer 阵列让每个像素只记录一个通道的亮度,最后插值得到每个像素的 RGB 三通道值。由于 Bayer 格式的 RAW 图放大后看起来像马赛克,这个从单通道数据还原色彩的过程又叫去马赛克(Demosaicing)。

RAW 图放大RAW 图放大 去马赛克后的图像去马赛克后的图像

Demosaicing 的插值一般遵循以下几个原则:

  1. 先插值 G 分量,因为 G 通道的像素数量是 R、B 通道的两倍。
  2. 采用方向性插值:如果是垂直边缘,就用上下的像素插值,而不用左右的。
  3. 色差恒定假设(Hamilton–Adams 算法中使用):R(i,j)−G(i,j)=R(i,j+1)−G(i,j+1)R(i,j)-G(i,j)=R(i,j+1)-G(i,j+1),即相邻像素的色差近似相同。
  4. 同一像素处各颜色分量的高频分量可认为相同。

一个简单的去马赛克流程可以是:

  1. 获取图像中物体的边缘;
  2. 根据边缘信息插值重建 G 分量;
  3. 根据色差恒定假设,用色差插值重建 R 和 B 分量;
  4. 后处理,包括伪彩色抑制(false color suppression)和拉链效应抑制(zipper cancelling)等。

扩展阅读:低成本边缘与色差插值去马赛克算法(LED)

示例代码:LED 法
// 示例代码:去马赛克算法实现(基于方向性插值和色差恒定理论)
 
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
 
// 获取梯度信息
void compute_gradients(const vector<vector<int>>& image, vector<vector<int>>& grad_h, vector<vector<int>>& grad_v) {
    int rows = image.size();
    int cols = image[0].size();
    grad_h.resize(rows, vector<int>(cols, 0));
    grad_v.resize(rows, vector<int>(cols, 0));
 
    for (int i = 1; i < rows - 1; ++i) {
        for (int j = 1; j < cols - 1; ++j) {
            grad_h[i][j] = abs(image[i][j + 1] - image[i][j - 1]);
            grad_v[i][j] = abs(image[i + 1][j] - image[i - 1][j]);
        }
    }
}
 
// 方向性插值重建G分量
void reconstruct_green(const vector<vector<int>>& bayer, vector<vector<int>>& green, const vector<vector<int>>& grad_h, const vector<vector<int>>& grad_v) {
    int rows = bayer.size();
    int cols = bayer[0].size();
    green = bayer; // 初始为 Bayer 图像
 
    for (int i = 1; i < rows - 1; ++i) {
        for (int j = 1; j < cols - 1; ++j) {
            if ((i + j) % 2 == 0) { // 当前像素不是 G
                if (grad_h[i][j] < grad_v[i][j]) {
                    green[i][j] = (bayer[i][j - 1] + bayer[i][j + 1]) / 2;
                } else {
                    green[i][j] = (bayer[i - 1][j] + bayer[i + 1][j]) / 2;
                }
            }
        }
    }
}
 
// 根据色差恒定理论重建 R 和 B 分量
void reconstruct_red_blue(const vector<vector<int>>& bayer, const vector<vector<int>>& green, vector<vector<int>>& red, vector<vector<int>>& blue) {
    int rows = bayer.size();
    int cols = bayer[0].size();
    red = bayer; // 初始为 Bayer 图像
    blue = bayer;
 
    for (int i = 1; i < rows - 1; ++i) {
        for (int j = 1; j < cols - 1; ++j) {
            if ((i % 2 == 0 && j % 2 == 1) || (i % 2 == 1 && j % 2 == 0)) { // 当前像素是 G
                red[i][j] = green[i][j] + (bayer[i][j + 1] - green[i][j + 1] + bayer[i][j - 1] - green[i][j - 1]) / 2;
                blue[i][j] = green[i][j] + (bayer[i + 1][j] - green[i + 1][j] + bayer[i - 1][j] - green[i - 1][j]) / 2;
            } else if ((i % 2 == 0 && j % 2 == 0)) { // 当前像素是 B
                red[i][j] = green[i][j] + (bayer[i + 1][j + 1] - green[i + 1][j + 1] + bayer[i - 1][j - 1] - green[i - 1][j - 1]) / 2;
            } else { // 当前像素是 R
                blue[i][j] = green[i][j] + (bayer[i + 1][j + 1] - green[i + 1][j + 1] + bayer[i - 1][j - 1] - green[i - 1][j - 1]) / 2;
            }
        }
    }
}
 
// 伪彩色抑制与拉链效应去除的后处理
void post_process(vector<vector<int>>& red, vector<vector<int>>& green, vector<vector<int>>& blue) {
    int rows = red.size();
    int cols = red[0].size();
 
    for (int i = 1; i < rows - 1; ++i) {
        for (int j = 1; j < cols - 1; ++j) {
            red[i][j] = min(max(red[i][j], 0), 255);
            green[i][j] = min(max(green[i][j], 0), 255);
            blue[i][j] = min(max(blue[i][j], 0), 255);
        }
    }
}
 
// 主函数:去马赛克
void demosaic(const vector<vector<int>>& bayer, vector<vector<int>>& red, vector<vector<int>>& green, vector<vector<int>>& blue) {
    vector<vector<int>> grad_h, grad_v;
    compute_gradients(bayer, grad_h, grad_v); // 计算梯度
    reconstruct_green(bayer, green, grad_h, grad_v); // 重建 G 分量
    reconstruct_red_blue(bayer, green, red, blue); // 重建 R 和 B 分量
    post_process(red, green, blue); // 后处理
}

色彩校正(Color Correction)

CMOS 传感器各颜色通道的光谱响应曲线与标准 RGB 色彩空间并不一致,因此需要一个色彩校正矩阵(CCM,Color Correction Matrix),把传感器捕获的原始颜色值转换到标准色彩空间,使颜色符合人眼的感知。CCM 通过拍摄标准色卡、比较测量值与标准值拟合得到。校正公式:

[R′G′B′]=[m11m12m13m21m22m23m31m32m33][RGB]\begin{bmatrix}R'\\G'\\B'\end{bmatrix}=\begin{bmatrix}m_{11}&m_{12}&m_{13}\\m_{21}&m_{22}&m_{23}\\m_{31}&m_{32}&m_{33}\end{bmatrix}\begin{bmatrix}R\\G\\B\end{bmatrix}

其中 R′G′B′R'G'B' 是校正后的颜色值,RGBRGB 是传感器捕获的原始颜色值。为了不改变白平衡后的白色,CCM 每一行的系数之和通常约束为 1。

色彩校正示例色彩校正示例

示例代码
#include <vector>
#include <array>
 
// 色彩校正矩阵定义(每行系数之和为 1)
const std::array<std::array<float, 3>, 3> CCM = {{
    {1.2f, -0.1f, -0.1f},
    {-0.2f, 1.3f, -0.1f},
    {-0.1f, -0.3f, 1.4f}
}};
 
// 对单个像素点进行色彩校正
std::array<float, 3> colorCorrection(const std::array<float, 3>& input) {
    std::array<float, 3> output = {0.0f, 0.0f, 0.0f};
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            output[i] += CCM[i][j] * input[j];
        }
    }
    return output;
}

色彩校正后,还可以按需求对颜色做进一步调节,例如色彩增强或风格化。

伽马校正(Gamma Correction)

人对亮度的感知并非线性,而是接近幂函数 L∝I0.43L\propto I^{0.43}:对暗部变化更敏感,对亮部变化不敏感。为了高效利用有限的位深(bit 数),图像编码时会按人眼特性做非线性变换,把更多编码精度分配给暗部,减少亮部的精度。这种非线性编码称为 Gamma 编码:V=L1/γV = L^{1/\gamma},γ\gamma 常取 2.2。显示设备(如显示器)则执行相反的解码 L=VγL = V^{\gamma},把编码值还原为线性亮度,使图像看起来正确。

为什么需要 Gamma 编码:如果直接对线性亮度做量化编码并存储或传输,暗部只能分到很少的编码值,暗部细节被过度压缩,出现色带和细节丢失;而亮部却浪费了大量人眼分辨不出的编码值。因此,为了在有限位深下保留暗部细节,并让显示设备的解码得到预期的亮度和对比度,图像需要在编码阶段做 Gamma 编码。

图像编码前为什么要进行 Gamma 校正图像编码前为什么要进行 Gamma 校正

示例代码
#include <cmath>
 
// Gamma 编码:value 为归一化到 [0, 1] 的线性亮度,gamma 常取 2.2
float gammaCorrection(float value, float gamma) {
    return std::pow(value, 1.0f / gamma);
}
 
// 对整幅图像进行 Gamma 编码
void processImageGammaCorrection(std::vector<std::array<float, 3>>& image, float gamma) {
    for (auto& pixel : image) {
        for (int i = 0; i < 3; ++i) {
            pixel[i] = gammaCorrection(pixel[i], gamma);
        }
    }
}

其他图像处理算法

直方图均衡化(Histogram Equalization)

直方图均衡化通过调整图像的灰度分布来提升对比度,但对本身对比度较高的图像使用时,可能导致细节丢失或噪声被放大。它更适合曝光不足、对比度低的图像,例如医学影像、卫星图像,或计算机视觉中的图像预处理。

直方图均衡化直方图均衡化

示例代码
#include <vector>
#include <algorithm>
#include <numeric>
 
// 计算累积分布函数(CDF)
std::vector<float> calculateCDF(const std::vector<int>& histogram) {
    std::vector<float> cdf(histogram.size(), 0.0f);
    std::partial_sum(histogram.begin(), histogram.end(), cdf.begin());
    float maxValue = cdf.back();
    for (float& val : cdf) {
        val /= maxValue;
    }
    return cdf;
}
 
// 应用直方图均衡化
void histogramEqualization(std::vector<std::vector<int>>& image, int maxValue) {
    std::vector<int> histogram(maxValue + 1, 0);
 
    // 统计直方图
    for (const auto& row : image) {
        for (int value : row) {
            ++histogram[value];
        }
    }
 
    // 计算CDF
    std::vector<float> cdf = calculateCDF(histogram);
 
    // 应用均衡化
    for (auto& row : image) {
        for (int& value : row) {
            value = static_cast<int>(cdf[value] * maxValue);
        }
    }
}

颜色空间转换(Color Space Conversion)

  • RGB(Red, Green, Blue)是基于加色模型的颜色空间,表示红、绿、蓝三个通道的强度,广泛用于显示设备(如显示器、电视)。它通过不同强度的红、绿、蓝光组合出各种颜色,混合方式是加法的:各通道的光叠加越多,颜色越亮。
  • CMYK(Cyan, Magenta, Yellow, Black)是印刷用的四种颜色,青、品红、黄分别是红、绿、蓝的补色,基于减色模型。实际印刷中青、品红、黄很难叠加出纯正的黑色,因此引入了 K(黑色),用来强化暗调、加深暗部。

RGB 与 CMYKRGB 与 CMYK

  • YUV(Y, U, V)是由亮度和色度分量组成的颜色空间,常用于视频压缩和广播。Y 表示亮度(即灰度信息),U、V 表示色度:U 与蓝色和亮度的差 B′−Y′B'-Y' 成正比,V 与红色和亮度的差 R′−Y′R'-Y' 成正比。YUV 的好处是把亮度和色度分开处理。人眼对亮度的敏感度远高于色度,所以可以对色度做更强的压缩(如 4:2:0 下采样),而不明显影响观感。
RGB-YUV 转换公式(BT.601)Y′=WRR′+WGG′+WBB′=0.299R′+0.587G′+0.114B′U=UmaxB′−Y′1−WB≈0.492(B′−Y′)V=VmaxR′−Y′1−WR≈0.877(R′−Y′)⇒[Y′UV]=[0.2990.5870.114−0.14713−0.288860.4360.615−0.51499−0.10001][R′G′B′]R′=Y′+V1−WRVmax=Y′+V0.877=Y′+1.14VB′=Y′+U1−WBUmax⁡=Y′+U0.492=Y′+2.033UG′=Y′−WRR′−WBB′WG⇒[R′G′B′]=[101.139831−0.39465−0.5806012.032110][Y′UV]\begin{aligned} &Y'=W_RR^{\prime}+W_GG^{\prime}+W_BB^{\prime}=0.299R^{\prime}+0.587G^{\prime}+0.114B^{\prime} \\ &U=U_{\mathrm{max}}\frac{B^{\prime}-Y^{\prime}}{1-W_{B}}\approx0.492(B^{\prime}-Y^{\prime}) \\ &V=V_{\mathrm{max}}\frac{R^{\prime}-Y^{\prime}}{1-W_{R}}\approx0.877(R^{\prime}-Y^{\prime}) \\ &\Rightarrow \begin{bmatrix}Y'\\U\\V\end{bmatrix}=\begin{bmatrix}0.299&0.587&0.114\\-0.14713&-0.28886&0.436\\0.615&-0.51499&-0.10001\end{bmatrix}\begin{bmatrix}R'\\G'\\B'\end{bmatrix} \\ &R^{\prime}=Y^{\prime}+V\frac{1-W_{R}}{V_{\mathrm{max}}}=Y^{\prime}+\frac{V}{0.877}=Y^{\prime}+1.14V \\ &B^{\prime}=Y^{\prime}+U\frac{1-W_{B}}{U_{\max}}=Y^{\prime}+\frac{U}{0.492}=Y^{\prime}+2.033U \\ &G^{\prime}=\frac{Y'-W_RR'-W_BB'}{W_G} \\ &\Rightarrow \begin{bmatrix}R'\\G'\\B'\end{bmatrix}=\begin{bmatrix}1&0&1.13983\\1&-0.39465&-0.58060\\1&2.03211&0\end{bmatrix}\begin{bmatrix}Y'\\U\\V\end{bmatrix} \end{aligned}
  • HSV(Hue, Saturation, Value)是 A. R. Smith 在 1978 年根据颜色的直观特性提出的颜色空间,也称六角锥体模型(Hexcone Model)。三个参数分别是色调(H)、饱和度(S)、明度(V)。
  • HSL(Hue, Saturation, Lightness)是 HSV 的变体,同样用色调、饱和度和亮度描述颜色。区别在于:HSL 的亮度(Lightness)从黑色经纯色到白色,纯色位于 L = 50%;HSV 的明度(Value)从黑色到最亮的纯色,纯色位于 V = 100%。HSV 和 HSL 都是 RGB 的几何变换,便于直观地调色和取色,常用于图形软件的取色器,但并不是感知均匀的颜色空间。

RGB 到 HSV 和 HSL 的转换比较复杂,参考维基百科 HSL and HSV。

色彩空间模型色彩空间模型

色彩空间模型的几何关系色彩空间模型的几何关系

示例代码
// RGB 转 YUV
std::array<float, 3> rgbToYuv(const std::array<float, 3>& rgb) {
    float y = 0.299f * rgb[0] + 0.587f * rgb[1] + 0.114f * rgb[2];
    float u = 0.492f * (rgb[2] - y);
    float v = 0.877f * (rgb[0] - y);
    return {y, u, v};
}
 
// YUV 转 RGB
std::array<float, 3> yuvToRgb(const std::array<float, 3>& yuv) {
    float r = yuv[0] + 1.14f * yuv[2];
    float g = yuv[0] - 0.394f * yuv[1] - 0.581f * yuv[2];
    float b = yuv[0] + 2.032f * yuv[1];
    return {r, g, b};
}

参考资料