- 遍历单通道图像三种方式
#include
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat image = imread("/home/chang/projects/opencv_GPU_example/test.jpg");
/遍历单通道图像方式***/
/************************************************************************************/
/ [指针偏移读取像素点] */
Mat testImage1 = image.clone();
for(int i = 0; i < testImage1.rows; i++)
{
uchar* ptr = testImage1.data + i * testImage1.step; // *ptr指向每一行的首地址
// 遍历每一行的像素值
for(int j = 0; j < testImage1.step; j++)
{
*(ptr + j) = i % 255; // Blue,每行每个像素点的值对255取余
// cout << "(ptr+j) = " << (int)((ptr+j)) << endl;
}
}
namedWindow(“testImage1”);
imshow(“testImage1”, testImage1);
/* [指针偏移读取像素点] */
/************************************************************************************/
/ [C++Vec读取像素点数据] /
Mat testImage2 = image.clone();
for(int i = 0; i < testImage2.rows; i++)
{
for(int j = 0; j < testImage2.cols; j++)
{
Vec3b pixel;
pixel[0] = i % 255; // Blue
pixel[1] = j % 255; // Green
pixel[2] = 0; // Red
testImage2.at(i, j) = pixel;
}
}
namedWindow(“testImage2”);
imshow(“testImage2”, testImage2);
/ [C++Vec读取像素点数据] */
/************************************************************************************/
/ [迭代器方式遍历图像像素] */
Mat testImage3 = image.clone(); //Creates a full copy of the array and the underlying data.
MatIterator_ iterBegin, iterEnd;
for(iterBegin = testImage3.begin(), iterEnd = testImage3.end(); iterBegin != iterEnd; ++iterBegin)
{
(*iterBegin)[0] = rand() % 255;
(*iterBegin)[1] = rand() % 255;
(iterBegin)[2] = rand() % 255;
}
namedWindow(“testImage3”);
imshow(“testImage3”, testImage3);
/ [迭代器方式遍历图像像素] */
waitKey(0);
return 0;
}
- 创建单通道Mat并遍历每个像素点举例
#include
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
Mat M = Mat::eye(4, 4, CV_8UC1);
cout << "M = " << endl << " " << M.channels() << endl << endl;
for(int i = 0; i < M.rows; i++)
{
uchar* ptr = M.data + i * M.step; // *ptr指向每一行的首地址
// 遍历每一行的像素值
for(int j = 0; j < M.step; j++)
{
cout << i << " " << j << ": " << (int)(*(ptr+j)) << endl;
}
cout << "*****************" << endl;
}
return 0;
}