OpenCV 提供一个函数 getTickCount() ,能够用来測量一段代码的执行时间。另一个函数 getTickFrequency() 用来返回每秒内的时钟周期。代码操作例如以下:
double duration; duration = static_cast<double>(getTickCount()); colorReduce(src); duration = static_cast<double>(getTickCount()) - duration; duration /= getTickFrequency();//执行时间以ms为单位
通过时间计算函数。对上小节中的像素引用方法做出对照。终于得出运算速度最快的 colorReduce() 函数。代码例如以下:
#include <QCoreApplication> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; void colorReduce(Mat &source, int div = 64) { int row = source.rows; int rowN = source.cols; if ( source.isContinuous() )//检測图像内存是否连续 { rowN = rowN * row; row = 1; } for ( int j = 0; j < row; j ++ ) { uchar* data = source.ptr<uchar>(j); for ( int i = 0; i < rowN; i ++ ) { *data = *data/div*div + div/2; data++; *data = *data/div*div + div/2; data++; *data = *data/div*div + div/2; data++; } } } int main() { Mat src = imread("lena.jpg",1); colorReduce(src); namedWindow("src",0); imshow("src",src); waitKey(0); return 0; }