saturate_cast<uchar>主要是为了防止颜色溢出操作

原理大致如下
if(data<0) 
        data=0; 
elseif(data>255) 
    data=255;

比如我们对像素进行线性操作。

<1> 不使用saturate_cast<uchar>

	//三个for循环,执行运算 g_dstImage(i,j) =a*g_srcImage(i,j) + b
	for (int y = 0; y < g_srcImage.rows; y++)
	{
		for (int x = 0; x < g_srcImage.cols; x++)
		{
			for (int c = 0; c < 3; c++)
			{
				//g_dstImage.at<Vec3b>(y, x)[c] = saturate_cast<uchar>((g_nContrastValue*0.01)*(g_srcImage.at<Vec3b>(y, x)[c]) + g_nBrightValue);
				g_dstImage.at<Vec3b>(y, x)[c] = (g_nContrastValue*0.01)*(g_srcImage.at<Vec3b>(y, x)[c]) + g_nBrightValue;
			}
		}
	}

 

 <2> 使用saturate_cast<uchar>

	//三个for循环,执行运算 g_dstImage(i,j) =a*g_srcImage(i,j) + b
	for (int y = 0; y < g_srcImage.rows; y++)
	{
		for (int x = 0; x < g_srcImage.cols; x++)
		{
			for (int c = 0; c < 3; c++)
			{
				g_dstImage.at<Vec3b>(y, x)[c] = saturate_cast<uchar>((g_nContrastValue*0.01)*(g_srcImage.at<Vec3b>(y, x)[c]) + g_nBrightValue);
			}
		}
	}

 

总结:

相当于是对图像色彩变化时做的保护! 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐