OpenCV Tutorial: 像素巡訪(at、ptr)

来源:互联网 发布:索尼z3v电信4g网络 编辑:程序博客网 时间:2024/05/28 04:54

像素巡訪(at、ptr)

當我們進行影像處理時,可能有操作是要查訪所有像素,比如說我們想要改變一張影像的灰階值,讓所有的像素值加20,這時我們就需掃過影像所有的像素,這邊介紹OpenCV的at()和ptr()函式以及迭代器,來查訪Mat所有像素。

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;    }}
0 0
原创粉丝点击