一、訪問
對於Mat的訪問有兩種方式
第一種,利用Mat::at進行訪問
//讀取3通道彩色圖像 Mat img = imread("圖片地址"); int px; //讀取圖像中第一行第一列,Blue通道數據 int px = img.at<Vec3b>(0, 0)[0];
第二種,利用Mat的成員ptr指針進行訪問
//讀取3通道彩色圖像 Mat img = imread("圖片地址"); //將Mat中的第一行地址賦予pxVec uchar* pxVec=img.ptr<uchar>(0); //遍歷訪問Mat中各個像素值 int i, j; int px; for (i = 0; i < img.rows; i++) { pxvec = img.ptr<uchar>(i); //三通道數據都在第一行依次排列,按照BGR順序 //依次賦值為1 for (j = 0; j < img.cols*img.channels(); j++) { px=pxvec[j]; //do anything
} }
二、賦值
不能用Mat::at進行賦值,只能用ptr對Mat中的像素點進行賦值
一個完整的例子如下:
#include "stdafx.h" #include <opencv2\core\core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2\imgproc\imgproc.hpp> #include <vector> int main() { //對Mat進行遍歷賦值 //初始化Mat數據結構,256*256,三通道8位(256色)圖像 Mat myimg(256,256,CV_8UC3); //取像素數據首地址 uchar* pxvec = myimg.ptr<uchar>(0); int i, j; for (i = 0; i < myimg.rows; i++) { pxvec = myimg.ptr<uchar>(i); //三通道數據都在第一行依次排列,按照BGR順序 //依次賦值為1 for (j = 0; j < myimg.cols*myimg.channels(); j++) { pxvec[j] = 1; } } //展示圖像 imshow("abc", myimg); waitKey(10000); }
結果如下: