Mat 像素读取方式---at()和ptr()

转自: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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值