在图像处理方面,无论是加是减,乘除,都会超出一个像素灰度值的范围(0~255),saturate_cast函数的作用即是:当运算完之后,结果为负,则转为0,结果超出255,则为255。
https://blog.csdn.net/piaoxuezhong/article/details/60570919
拉普拉斯锐化的例子:
1 //////https://blog.csdn.net/piaoxuezhong/article/details/60570919 2 #include <iostream> 3 #include<core/core.hpp> 4 #include<highgui/highgui.hpp> 5 6 using namespace cv; 7 8 void sharpen(const Mat& img, Mat& result) 9 { 10 result.create(img.size(), img.type()); 11 //处理边界内部的像素点, 图像最外围的像素点暂不处理 12 for (int row = 1; row < img.rows - 1; row++) 13 { 14 //前一行像素点 15 const uchar* previous = img.ptr<const uchar>(row - 1); 16 //待处理的当前行 17 const uchar* current = img.ptr<const uchar>(row); 18 //下一行 19 const uchar* next = img.ptr<const uchar>(row + 1); 20 uchar *output = result.ptr<uchar>(row); 21 int ch = img.channels(); 22 int starts = ch; 23 int ends = (img.cols - 1) * ch; 24 for (int col = starts; col < ends; col++) 25 { 26 //输出图像的遍历指针与当前行的指针同步递增, 以每行的每一个像素点的每一个通道值为一个递增量, 因为要考虑到图像的通道数 27 *output++ = saturate_cast<uchar>(5 * current[col] - current[col - ch] - current[col + ch] - previous[col] - next[col]); 28 } 29 } 30 //外围像素点设为 0 31 result.row(0).setTo(Scalar::all(0)); 32 result.row(result.rows - 1).setTo(Scalar::all(0)); 33 result.col(0).setTo(Scalar::all(0)); 34 result.col(result.cols - 1).setTo(Scalar::all(0)); 35 } 36 37 int main() 38 { 39 Mat kobe = imread("D:\小女孩与熊.jpg"); 40 Mat sharpenedKobe; 41 sharpen(kobe, sharpenedKobe); 42 43 imshow("kobe", kobe); 44 imshow("sharpened kobe", sharpenedKobe); 45 cvWaitKey(); 46 return 0; 47 }
原图:
锐化后: