#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat src = imread("C:/Users/ChangShuang/Pictures/Lena.jpg");
imshow("Src", src);
int nr = src.rows;
int nl = src.cols;
//Mat的方法at<>()
double duration1;
duration1 = static_cast<double>(getTickCount());
for (int i = 0;i < nr;i++) {
for (int j = 0;j < nl;j++) {
src.at<Vec3b>(j, i)[0] = 0;
src.at<Vec3b>(j, i)[1] = 0;
src.at<Vec3b>(j, i)[2] = 0;
}
}
duration1 = static_cast<double>(getTickCount()) - duration1;
duration1 /= getTickFrequency();
cout << "duration1 = " << duration1 << endl;
//使用迭代器
Mat_<Vec3b>::iterator begin = src.begin<Vec3b>();
Mat_<Vec3b>::iterator end = src.end<Vec3b>();
double duration2;
duration2 = static_cast<double>(getTickCount());
for (;begin != end;begin++) {
(*begin)[0] = 0;
(*begin)[1] = 0;
(*begin)[2] = 0;
}
duration2 = static_cast<double>(getTickCount()) - duration2;
duration2 /= getTickFrequency();
cout << "duration2 = " << duration2 << endl;
//使用指针
double duration3;
duration3 = static_cast<double>(getTickCount());
for (int i = 0;i < nr;i++) {
Vec3b* ptr = src.ptr<Vec3b>(i);
for (int j = 0;j < nl;j++) {
(*ptr)[0] = 0;
(*ptr)[1] = 0;
(*ptr)[2] = 0;
ptr++;
}
}
duration3 = static_cast<double>(getTickCount()) - duration3;
duration3 /= getTickFrequency();
cout << "duration3 = " << duration3 << endl;
//使用指针 获取类型为uchar
double duration4;
duration4 = static_cast<double>(getTickCount());
//判断图像是否连续
if (src.isContinuous()) {
nl = nr*nl;
nr = 1;
}
for (int i = 0;i < nr;i++) {
uchar* ptr = src.ptr<uchar>(i);
for (int j = 0;j < nl;j++) {
(*ptr++) = 0;
(*ptr++) = 0;
(*ptr++) = 0;
}
}
duration4 = static_cast<double>(getTickCount()) - duration4;
duration4 /= getTickFrequency();
cout << "duration3 = " << duration4 << endl;
waitKey(0);
return 0;
}
测试结果: