在Opencv中,进行像素访问时,可以用at,返回对应位置的值;ptr,返回对应位置的地址。
示例:
Mat image = imread("../123.jpg", 1);
uchar * data = image.ptr<uchar>(i); //返回第i+1行的首地址;
int data1 = image.at<uchar>(2, 1); //读取第3行第2列对应像素的值
if (image.type() == CV_8UC1)
{
image.at<uchar>(j, i) = 255; // Read & Write the data of a pixel image.at<uchar>(j, i); //255; //给每个像素赋值,单通道
}
else if (image.type() == CV_8UC3) //给每个像素赋值,三通道
{
image.at<Vec3b>(j, i)[0] = 255; //at(cols,rows) 列,行
image.at<Vec3b>(j, i)[1] = 255;
image.at<Vec3b>(j, i)[2] = 255;
}
低层次指针算法:
uchar *data = image.data; //图像的起点位置
data += image.step; //下一行,step得到一行的总字节数(包括填充像素)
data = image.data + j*image.step+i*image.elemSize(); //第j行,第i列的像素的地址(j,i) 像素的地址,即image.at(j,i);
//NOTE: image.at(j,i) 代表第j行第i列 行,列; 但在画图工具中对应像素坐标显示为(i,j) 列,行
处理过程中稍加注意即可。
迭代器扫描图像:
Mat Iterator_<Vec3b> it;
或 Mat_<Vec3b>::iterator it;
it = image.begin<Vec3b>(); //在初始位置获得迭代器
itend = image.end<Vec3b>(); //获得结束位置
for(; it != itend; ++it)
{ //处理每个像素
(*it)[0] = ...;
(*it)[1] = ...;
(*it)[2] = ...;
//像素处理结束
}