<pre name="code" class="cpp"><span style="background-color: rgb(255, 255, 255); font-family: Arial, Helvetica, sans-serif;font-size:18px;"> 在图像处理领域,我们经常需要遍历一幅图像,opencv提供多种方法完成对图像的遍历,但是他们的效率是不同的。程序中我们常使用指针或者迭代器的方法遍历图像,下面的程序将对两种方法的效率做对比。</span>
条件:单线程,主频3.4GHz计算机运行,图像image.jpg尺寸为768×576。
// readImage.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace cv; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { Mat image = imread("image.jpg",0); Mat gray1 = Mat::zeros(image.rows,image.cols,image.type()); Mat gray2 = Mat::zeros(image.rows,image.cols,image.type()); long int count = 0; uchar num = 0; double t = (double)getTickCount(); for (int i = 0; i < image.rows; i++) { uchar* ptr = image.ptr<uchar>(i); uchar* g_ptr = gray1.ptr<uchar>(i); for (int j = 0; j < image.cols; j++) { g_ptr[j] = ptr[j]; } } t = ((double)getTickCount() - t)/getTickFrequency(); double t1 = (double)getTickCount(); for (int i=0;i<image.rows;i++) { for (int j=0;j<image.cols;j++) { gray1.at<uchar>(i,j) = image.at<uchar>(i,j); } } t1 = ((double)getTickCount() - t1)/getTickFrequency(); double t2 = (double)getTickCount(); for (int i = 0; i < image.rows; i++) { uchar* ptr = image.ptr<uchar>(i); for (int j = 0; j < image.cols; j++) { num = ptr[j]; } } t2 = ((double)getTickCount() - t2)/getTickFrequency(); double t3 = (double)getTickCount(); for (int i=0;i<image.rows;i++) { for (int j=0;j<image.cols;j++) { num = image.at<uchar>(i,j); } } t3 = ((double)getTickCount() - t3)/getTickFrequency(); cout << t <<endl; cout << t1 << endl; cout << t2 << endl; cout << t3 << endl; getchar(); return 0; }
从图中的时间可以看出,对于这个尺寸的图像遍历,使用指针的方法要比使用迭代器的方法快了30倍,使用迭代器只需要1毫秒,而是用迭代器则需要30ms左右。
时间: 2024-10-22 00:04:08