Opencv中三种遍历元素的方法及程序计时方法

来源:互联网 发布:linux rc5.d 编辑:程序博客网 时间:2024/06/05 19:18

//第一种,用指针遍历

#include<opencv2/opencv.hpp>

#include <highgui.h>

#include <iostream>
#include <cv.h>
using namespace cv;
using namespace std;

void colorReduce(Mat &dst,uchar a)
{
for(int i=0;i<dst.rows;i++)
{
uchar* data=dst.ptr<uchar>(i);
for(int j=0;j<dst.cols*dst.channels();j++ )
{
data[j]=data[j]/a*a;
}
}
}
int main ()
{
double time0=(double)getTickCount();  //计时函数头
Mat src=imread("logo.png");
Mat dst=src.clone();
colorReduce(dst,10);
double time1=((double)getTickCount()-time0)/getTickFrequency(); //计时函数尾
imshow("xxx",dst);
waitKey(0);
cout<<time1<<"s"<<endl;
}

时间:0.00704616

//第二种 用迭代器遍历

#include<opencv2/opencv.hpp>
#include <highgui.h>
#include <iostream>
#include <cv.h>
#include <opencv2/core/core.hpp>
using namespace cv;
using namespace std;
void colorReduce(Mat &dst,uchar a)
{
Mat_<Vec3b>::iterator it=dst.begin<Vec3b>();
Mat_<Vec3b>::iterator itend=dst.end<Vec3b>();
for(;it!=itend;it++)
{
(*it)[0]=(*it)[0]/a*a;  //it相当于一个指针,it存储的是是每一个像素的地址,对它取内容,就得到像素值。
(*it)[1]=(*it)[1]/a*a;
(*it)[2]=(*it)[2]/a*a;
}
}
int main ()
{
double time0=(double)getTickCount();  //计时函数头
Mat src=imread("logo.png");
Mat dst=src.clone();
colorReduce(dst,10);
double time1=((double)getTickCount()-time0)/getTickFrequency(); //计时函数尾
imshow("xxx",dst);
waitKey(0);
cout<<time1<<"s"<<endl;
}

时间:0.0511044


//第三种,最基础的,用三层循环来遍历,这里省去过程

 dst.at<Vec3b>[x,y](z);

0 0