Qt 5.3 下OpenCV 2.4.11 开发(5)最高效的像素引用

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;  
}


你可能感兴趣的:(C++,opencv,图像处理算法)