- 指针方式
- at方式
- 迭代器方式
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
using namespace std;
using namespace cv;
void ptr_cost(Mat img) {
for (int i = 0; i < img.rows; ++i)
{
Vec3b* p =img.ptr<Vec3b>(i);
for (int j = 0; j < img.cols; ++j)
{
p[j][0] = i % 255; //Blue
p[j][1] = j % 255; //Gree
p[j][2] = 0; //Red
}
}
}
void iterate_cost(Mat img) {
MatIterator_<Vec3b> colorit, colorend;
for (colorit =img.begin<Vec3b>(), colorend = img.end<Vec3b>(); colorit != colorend; ++colorit)
{
(*colorit)[0] = rand() % 255; //Blue
(*colorit)[1] = rand() % 255; //Green
(*colorit)[2] = rand() % 255; //Red
}
}
void at_cost(Mat img) {
for (int i = 0; i < img.rows; ++i) //遍历行
for (int j = 0; j < img.cols; ++j) //遍历列
{
Vec3b pixel; //定义三通道像素值变量
pixel[0] = i % 255; //Blue
pixel[1] = j % 255; //Green
pixel[2] = 0; //Red
img.at<Vec3b>(i, j) = pixel;
}
}
int main()
{
Mat image = cv::imread("./002.jpg");
double ptrtimeConsume = static_cast<double>(getTickCount());
ptr_cost(image);
ptrtimeConsume = ((double)getTickCount() - ptrtimeConsume) / getTickFrequency();
cout << "ptr_cost: " << ptrtimeConsume << endl;
double attimeConsume = static_cast<double>(getTickCount());
at_cost(image);
attimeConsume = ((double)getTickCount() - attimeConsume) / getTickFrequency();
cout << "at_cost: " << attimeConsume << endl;
double itertimeConsume = static_cast<double>(getTickCount());
iterate_cost(image);
itertimeConsume = ((double)getTickCount() - itertimeConsume) / getTickFrequency();
cout << "iterate_cost: " << itertimeConsume << endl;
namedWindow("Image", WINDOW_AUTOSIZE);
imshow("Image", image);
waitKey(0);
return 0;
}
测试图片
耗时打印
小结:
1、工程化时建议使用指针方式遍历图像。