在圖形處理中,遍歷每個像素點是最基本的功能,是做算法的基礎(chǔ),這篇文章來總結(jié)一下OpenCV遍歷圖像的幾種方法。
本文章參考文檔OpenCV tutorials的how_to_scan_images.cpp例子。
最有效率--指針
用c語言直接訪問是最有效率的,最快的,下面是簡單的示例。
int scan_image_c(Mat &I)
{
int channels = I.channels();
if (channels != 3)
{
printf("test support only three channel.\\n");
return -1;
}
for (int i = 0; i < I.rows; i++)
{
Vec3b *ptr = I.ptr
最安全--迭代器
迭代器是C++中的一個概念,因為迭代器從用戶手中接管了一些工作,它會保證訪問的安全,所以必然會導(dǎo)致一些性能上的降低,簡單例子如下。
int scan_image_iterator(Mat &I)
{
int channels = I.channels();
if (channels != 3)
{
printf("test support only three channel.\\n");
return -1;
}
MatIterator_
最便捷--at方法
OpenCV的Mat類中有一個at方法,它可以直接返回某個像素點,示例如下。
int scan_image_random(Mat &I)
{
int channels = I.channels();
if (channels != 3)
{
printf("test support only three channel.\\n");
return -1;
}
for( int i = 0; i < I.rows; ++i)
{
for( int j = 0; j < I.cols; ++j
{
I.at
完整例子
#include
#include
using namespace std;
using namespace cv;
int scan_image_c(Mat &I);
int scan_image_iterator(Mat &I);
int scan_image_random(Mat &I);
int main( int argc, char* argv[])
{
if (argc != 2)
{
cout << "input parameters failed!" << endl;
return -1;
}
Mat I;
I = imread(argv[1], IMREAD_COLOR);
if (I.empty())
{
cout << "The image" << argv[1] << " could not be loaded." << endl;
return -1;
}
const int times = 100;
double t = 0;
t = (double)getTickCount();
for (int i = 0; i < times; ++i)
{
cv::Mat clone_i = I.clone();
scan_image_c(clone_i);
}
t = 1000*((double)getTickCount() - t)/getTickFrequency();
t /= times;
cout << "Time of scan_image_c (averaged for "
<< times << " runs): " << t << " ms."<< endl;
t = (double)getTickCount();
for (int i = 0; i < times; ++i)
{
cv::Mat clone_i = I.clone();
scan_image_iterator(clone_i);
}
t = 1000*((double)getTickCount() - t)/getTickFrequency();
t /= times;
cout << "Time of scan_image_iterator (averaged for "
<< times << " runs): " << t << " ms."<< endl;
t = (double)getTickCount();
for (int i = 0; i < times; ++i)
{
cv::Mat clone_i = I.clone();
scan_image_random(clone_i);
}
t = 1000*((double)getTickCount() - t)/getTickFrequency();
t /= times;
cout << "Time of scan_image_random (averaged for "
<< times << " runs): " << t << " ms."<< endl;
return 0;
}
int scan_image_c(Mat &I)
{
int channels = I.channels();
if (channels != 3)
{
printf("test support only three channel.\\n");
return -1;
}
for (int i = 0; i < I.rows; i++)
{
Vec3b *ptr = I.ptr
運行結(jié)果如下:
Time of scan_image_c (averaged for 100 runs): 2.04884 ms.
Time of scan_image_iterator (averaged for 100 runs): 4.77701 ms.
Time of scan_image_random (averaged for 100 runs): 3.64237 ms.
從數(shù)據(jù)上看,c語言的方法確實是最快的,和其他兩種方式拉開了一定的差距。而at遍歷比迭代器遍歷快了不少。
在平常使用中,我們可以根據(jù)每個方法的優(yōu)點去選擇不同的方法。
審核編輯:劉清
-
C語言
+關(guān)注
關(guān)注
180文章
7594瀏覽量
135858 -
OpenCV
+關(guān)注
關(guān)注
29文章
624瀏覽量
41214 -
迭代器
+關(guān)注
關(guān)注
0文章
43瀏覽量
4296
發(fā)布評論請先 登錄
相關(guān)推薦
評論