opencv学习笔记:矩阵的掩膜操作
获取图像像素指针
-
Mat.ptr<uchar>(int i=0) 获取像素矩阵的指针,索引i表示第几行,从0开始计行数。
-
获得当前行指针const uchar* current= myImage.ptr<uchar>(row );
-
获取当前像素点P(row, col)的像素值 p(row, col) =current[col]
像素范围处理saturate_cast<uchar>
-
saturate_cast<uchar>(-100),返回 0。
-
saturate_cast<uchar>(288),返回255
-
saturate_cast<uchar>(100),返回100
-
这个函数的功能是确保RGB值得范围在0~255之间
实现代码块
1 #include <opencv2/opencv.hpp> 2 #include <opencv2/highgui.hpp> 3 #include <iostream> 4 #include "math.h" 5 using namespace cv; 6 int main() 7 { 8 Mat src, dst; 9 src = imread("C:/Users/92881/Pictures/d33fc490df2aef9165ebba9cefd1602.jpg");//获取图像 10 if (!src.data) 11 printf("loading fail...\n"); 12 namedWindow("input image", WINDOW_AUTOSIZE);//创建窗口 13 imshow("input image", src);//显示图像 14 int cols = (src.cols - 1)*src.channels();//定义列 15 int offsetx = src.channels(); 16 int rows = src.rows - 1;//定义行 17 dst = Mat::zeros(src.size(), src.type()); 18 for (int row = 1; row < rows; row++) 19 { 20 const uchar* previous = src.ptr<uchar>(row - 1);//读取指针 21 const uchar* current = src.ptr<uchar>(row); 22 const uchar* next = src.ptr<uchar>(row + 1); 23 uchar* output = dst.ptr<uchar>(row); 24 for (int col = offsetx; col < cols; col++) 25 { 26 output[col] = saturate_cast<uchar>(5 * current[col] - (current[col - offsetx] + current[col + offsetx] + next[col] + previous[col])); 27 } 28 } 29 namedWindow("change image", WINDOW_AUTOSIZE); 30 imshow("change image", dst); 31 imwrite("C:/Users/92881/Desktop/3.jpg", dst); 32 waitKey(0); 33 return 0; 34 }