[转]OpenCV学习--saturate_cast防止数据溢出
//使用图像混合例子中的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;