转自:http://monkeycoding.com/?p=538
at()可用來讀取和修改某個像素值,通常用來對隨機位置的像素進行讀寫,就效率考量,並不適合用在循序查訪影像所有像素,以下用at()來讀取img的所有像素,並讓所有像素值加20:
int widthLimit = img.channels() * img.cols;
for(int height=0; height<img.rows; height++){
for(int width=0; width<widthLimit; width++){
img.at<uchar>(height, width) += 20;
}
}
ptr()函式返回指標,指向影像指定列的首像素,使用時須輸入像素位元深度和第幾列,對於一個深度8位元的圖,我們可用img.ptr(j)指到第j列的第一個像素,接著逐列查訪,最後可查訪影像所有像素,這種方法運行速度較at()快,在解析度大或是重視效率的地方,是比較好的方法,以下用ptr()來讀取img的所有像素,並讓所有像素值加20:
int widthLimit = img.channels() * img.cols;
for(int height=0; height<img.rows; height++){
uchar *data = img.ptr<uchar>(height);
for(int width=0; width<img.widthLimit ; width++){
data[width] += 20;
}
}
OpenCV有為Mat提供了與STL迭代器兼容的迭代器,使用時須指定影像數據類型,以下用迭代器來讀取img的所有像素,並讓所有像素值加20:
if(img.channels()==1){
Mat_<uchar>::iterator it = img.begin<uchar>();
Mat_<uchar>::iterator itend = img.end<uchar>();
for(;it!=itend;it++){
(*it) = (*it) + 20;
}
}
if(img.channels()==3){
Mat_<Vec3b>::iterator it = img.begin<Vec3b>();
Mat_<Vec3b>::iterator itend = img.end<Vec3b>();
for(;it!=itend;it++){
(*it)[0] = (*it)[0] + 20;
(*it)[1] = (*it)[1] + 20;
(*it)[2] = (*it)[2] + 20;
}
}