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);
}
}
}

本文详细介绍了saturate_cast<uchar>函数在图像处理中的作用,特别是如何防止颜色溢出,保护图像色彩在进行线性操作时不会超出有效范围。通过对比使用与未使用该函数的代码片段,展示了其在图像色彩调整过程中的重要性。
912

被折叠的 条评论
为什么被折叠?



