在OpenCV学习中经常看见saturate_cast的使用,下面的代码会展示它的作用,详细的代码可以参见文章http://blog.csdn.net/mjlsuccess/article/details/12400787
- //使用图像混合例子中的C语言版本演示
- for (int i=0; i<src1.rows; i++)
- {
- const uchar* src1_ptr = src1.ptr<uchar>(i);
- const uchar* src2_ptr = src2.ptr<uchar>(i);
- uchar* dst_ptr = dst.ptr<uchar>(i);
- for (int j=0; j<src1.cols*nChannels; j++)
- {
- dst_ptr[j] = saturate_cast<uchar>(src1_ptr[j]*alpha + src2_ptr[j]*beta + gama);//gama = -100, alpha = beta = 0.5
- // dst_ptr[j] = (src1_ptr[j]*alpha + src2_ptr[j]*beta + gama);
- }
- }
- imshow("output2",dst);
这里加入了溢出保护,结果如下
- //没加入溢出保护
- for (int i=0; i<src1.rows; i++)
- {
- const uchar* src1_ptr = src1.ptr<uchar>(i);
- const uchar* src2_ptr = src2.ptr<uchar>(i);
- uchar* dst_ptr = dst.ptr<uchar>(i);
- for (int j=0; j<src1.cols*nChannels; j++)
- {
- // dst_ptr[j] = saturate_cast<uchar>(src1_ptr[j]*alpha + src2_ptr[j]*beta + gama);//gama = -100, alpha = beta = 0.5
- dst_ptr[j] = (src1_ptr[j]*alpha + src2_ptr[j]*beta + gama);
- }
- }
- imshow("output2",dst);
- if(data<0)
- data=0;
- else if(data>255)
- data=255;