使用at<Vec3b>结构来获取Mat中的像素值
例如
1 #include <iostream> 2 #include <opencv2/opencv.hpp> 3 using namespace cv; 4 using namespace std; 5 6 int main(int args,char** argv) 7 { 8 Mat src = imread("E:/OpenCV/bin/Resource/lena.jpg",IMREAD_UNCHANGED); 9 if (src.empty()) { 10 printf("could not find image"); 11 return -1; 12 } 13 namedWindow("input", WINDOW_FULLSCREEN); 14 imshow("input", src); 15 imwrite("D:/test.png", src); 16 17 //visit each pixel 18 int height = src.rows; //高度 19 int width = src.cols; //宽度 20 int ch = src.channels(); //通道数 21 for (int row = 0; row < height; row++) { 22 for (int col = 0; col < width; col++) { 23 if (ch == 3) { 24 Vec3b pixel = src.at<Vec3b>(row, col); 25 int blue = pixel[0]; 26 int green = pixel[1]; 27 int red = pixel[2]; 28 src.at<Vec3b>(row, col)[0] = 255 - blue; 29 src.at<Vec3b>(row, col)[1] = 255 - green; 30 src.at<Vec3b>(row, col)[2] = 255 - red; 31 } 32 33 if (ch == 1) { 34 int pv=src.at<uchar>(row, col); 35 src.at<uchar>(row, col) = (255 - pv); 36 } 37 } 38 } 39 imshow("after_mod", src); 40 41 while (waitKey(50) != 27) 42 { 43 44 } 45 destroyAllWindows(); 46 return 0; 47 }
显示为:
对图片进行反色。
使用指针来获取Mat中的像素值
将上面代码at<Vec3b>用指针代替如下
1 Mat result = Mat::zeros(src.size(), src.type()); 2 for (int row = 0; row < height; row++) { 3 uchar* cur_row = src.ptr<uchar>(row); 4 uchar* result_row = result.ptr<uchar>(row); 5 for (int col = 0; col < width; col++) { 6 if (ch == 3) { 7 int blue = *cur_row++; 8 int green = *cur_row++; 9 int red = *cur_row++; 10 11 *result_row++ = blue; 12 *result_row++ = green; 13 *result_row++ = red; 14 } 15 if (ch == 1) { 16 int pv = *cur_row++; 17 *result_row++ = pv; 18 } 19 } 20 } 21 imshow("after_mod", result);
可以获得原图的一个拷贝