OpenCV实践(1)-怎样扫描图像、查找表和运行效率的测定

来源:互联网 发布:zbrush for mac 编辑:程序博客网 时间:2024/04/28 05:48

1、目标

在本文中我们要回答下面这4个问题:
(1)怎样遍历图像中的每一个像素;
(2)OpenCV中矩阵值怎样存储;
(3)怎样测试我们的算法的效率;
(4)什么是查找表,我们为什么要是用它?

2 关于测试demo

这里,我们考虑一种非常简单的色彩降低方法。我们已经知道,使用了unsigned char类型的矩阵项最高可以拥有256种不同的值。那么对于3通道图像来说,那就有16,000,000种值。处理这么多的像素差,对于我们的算法性能是个很大的考验。但是,有时候,只处理其中的一部分就能得到相同的最终结果。
在这些情况中,常用的方法就是色彩空间压缩。这意味着,我们通过将现在的色彩空间值除以一个我们新给定的值,得到更少的色彩。在demo中,我们将0-9取为新值0,10-19取值为10,以此类推。
当你把一个uchar类型的值除以整数值,结果还是char形,利用这个特点,上面的操作满足于下面这个表达式:

Inew = (Iold / 10) * 10;

那么,上面提到的简单的色彩空间压缩算法就是把图像矩阵的每一个像素都应用该公式,就可以了。值得注意是,我们这里使用了乘除操作。这些操作对系统的开销比较大。如果可能的话,尽量避免使用这些操作,取而代之的是,使用加减操作,更好的情况就是直接使用简单的赋值操作。进一步注意到,对于上面的操作,我们只需要有限的输入值就可以了。假设使用uchar类型,这个有限的值就是256。
因此,对于更大的图像,明智的做法就是,预先计算所有的可能值,在赋值阶段只需通过查找表进行赋值。查找表是简单的数组(1维或者多维都可以),每一个输入变量都对应这个表中的某个值,最为输出值。
我们的测试deme程序将会实现下面这些功能:从命令行读入图像(彩色或者灰度图都可以,这由另一个命令行参数控制),以及从命令行指定要压缩使用的整数值。OpenCV,现在有三种实现图像像素点的遍历方法。为了使这个测试更为有趣,这三种方法我们都将使用,且打印出它最终花费了多长时间。
基本的使用方法是:

how_to_scan_images imageName.jpg intValueToReduce [G]

最后的参数是可选的。如果使用,图像将会以灰度格式载入,否则就会使用RGB格式。首先要做的就是计算查找表。

    int divideWith = 0; // 转换输入字符串为数字-C++风格    stringstream s;    s << argv[2];    s >> divideWith;    if (!s || !divideWith)    {        cout << "Invalid number entered for dividing. " << endl;        return -1;    }    uchar table[256];    for (int i = 0; i < 256; ++i)       table[i] = (uchar)(divideWith * (i/divideWith));

另一个问题就是我们如何计算算法运行的时间?好在OpenCV提供了两个函数getTickCount()和getTickFrequency()。getTickCount返回从某一个时间点你的系统CPU发生的Tick数,例如,从你的系统开始计数。getTickFrequency返回的是,在1s内你的CPU经过了多少个Ticks。所以,可以测量两个操作之间经过了多长时间,如下所示:

double t = (double)getTickCount();// do something ...t = ((double)getTickCount() - t)/getTickFrequency();cout << "Times passed in seconds: " << t << endl;

3 图像矩阵在内存中怎样存储?

这一段我们就不多做介绍了,因为我们在介绍Mat类的时候已经介绍过了。
需要注意的是,Mat类矩阵的保存方式是BGR,而不是我们常用的RGB格式。因为,大多数情况下,内存足以用连续的方式存储所有的行,即一行接一行,从而创建一个长的单行矩阵。这种在内存中的存储方式,可以加速我们对图像矩阵的扫描处理。在内存中是不是以这样方式存储的,可以使用isConstinous()函数进行判断。在后面的例子中,我们会使用这个函数。

4 最有效的方法

使用典型C风格的操作符[] (pointer)访问是非常有效率的。因此,对于赋值操作,我们推荐最有效的方式就是[] (pointer):

Mat& ScanImageAndReduceC(Mat& I, const uchar* const table){    // 只接受 uchar 类型的矩阵    CV_Assert(I.depth() != sizeof(uchar));    int channels = I.channels();    int nRows = I.rows;    int nCols = I.cols * channels;    if (I.isContinuous())    {        nCols *= nRows;        nRows = 1;    }    int i,j;    uchar *p;    for( i = 0; i < nRows; ++i)    {        p = I.ptr<uchar>(i);        for ( j = 0; j < nCols; ++j)        {            p[j] = table[p[j]];        }    }    return I;}

在这儿,我们基本上仅仅获取每行的起始指针,然后遍历这行直到结束。如果矩阵在内存中的存储是连续的,那么我们只需请求一次指针,然后就可以一路遍历到底。我们需要留意彩色图像:它有3通道,所以对于每一行,我们需要遍历3次。
这还有另外一种方法。Mat对象的data成员返回的是它第一行,第一列的指针。如果该指针是null,说明对象中的data输入是不合法的。检查这个,是检查你的图像是否载入成功最简单的方法。假设在内存中的存储是连续的,我们可以使用这个指针遍历整个数据成员。对于灰度图像,应该像下面这样:

uchar *p = I.data;for( unsigned int i = 0; i < ncol * nrows; ++i)    *p++ = table[*p];

你将会得到相同的结果。但是,这段代码的可读性比较差。重要的是,从demo的实现效果来看,你将会得到相同的性能结果。(大多数现在的编译器,都会自动地为你做一下优化)。
5 迭代器方法(比较安全)
使用指针访问,虽然非常高效,但是要保证传递的数据的安全性。使用迭代器这些问题就不会存在了。你所需要做的就是找出矩阵的开头和结尾。

Mat& ScanImageAndReduceIterator(Mat& I, const uchar* const table){    // accept only char type matrices    CV_Assert(I.depth() != sizeof(uchar));    const int channels = I.channels();    switch(channels)    {    case 1:        {            MatIterator_<uchar> it, end;            for( it = I.begin<uchar>(), end = I.end<uchar>(); it != end; ++it)                *it = table[*it];            break;        }    case 3:        {            MatIterator_<Vec3b> it, end;            for( it = I.begin<Vec3b>(), end = I.end<Vec3b>(); it != end; ++it)            {                (*it)[0] = table[(*it)[0]];                (*it)[1] = table[(*it)[1]];                (*it)[2] = table[(*it)[2]];            }        }    }    return I;}

在彩色图像中,每通道有三个uchar值。OpenCV提供了一个Vec3b矢量表示。因为OpenCV迭代器遍历完一列后会自动跳到下一行,所以如果我们还使用uchar类型迭代器,只能访问到蓝色通道的值。所以,在这里,我们使用[]访问每个通道的子列值。
6 On-the-fly address calculation with reference returning
对于遍历图像,本段描述的这一方法,并不推荐使用。它被用来获取或修改图像中某一个随机的元素。它的基本使用方法是,指定你想访问的项的行号或列号。在介绍前面的扫描图像方法的时候,你可以观察到,图像的类型是非常重要的。在这里,没有什么不同,你也需要手动指定类型。看下面的灰度图的扫描,使用at()函数进行遍历。

Mat& ScanImageAndReduceRandomAccess(Mat& I, const uchar* const table){    // accept only char type matrices    CV_Assert(I.depth() != sizeof(uchar));    const int channels = I.channels();    switch(channels)    {    case 1:        {            for( int i = 0; i < I.rows; ++i)                for( int j = 0; j < I.cols; ++j )                    I.at<uchar>(i,j) = table[I.at<uchar>(i,j)];            break;        }    case 3:        {         Mat_<Vec3b> _I = I;         for( int i = 0; i < I.rows; ++i)            for( int j = 0; j < I.cols; ++j )               {                   _I(i,j)[0] = table[_I(i,j)[0]];                   _I(i,j)[1] = table[_I(i,j)[1]];                   _I(i,j)[2] = table[_I(i,j)[2]];            }         I = _I;         break;        }    }    return I;}

函数根据你的输入类型和坐标,计算运行时想要查询的项的地址。然后返回一个引用。当你取值时,这可能是一个constant常数,当你设置值时,这可能是non-constant值。与使用指针进行访问的方法相比,唯一的不同就是,对于图像中的每一个元素,你都需要重新得到一个新的row指针,然后配合[]操作符,对列进行访问。
如果扫描多通道的时候,使用这个方法是比较麻烦的,传递类型和对每一个元素使用at关键字进行访问也是比较花费时间的。为了解决这些问题,OpenCV又提供了一个新类Mat_,它仅仅是对Mat类的再封装,并没有实现什么新的特性。在使用的时候也和Mat类没有什么不一样,只是在定义的时候需要指定数据类型,最为回报就是,你可以使用()操作符快速的访问项。它和Mat类的数据转换也是非常方便的。

7 使用Core模块提供的函数

这是一个额外的查表修改图像值的方法。因为在图像处理中,常用的就是,把图像给定的值取代为其它值,OpenCV有一个函数,LUT(),该函数可以让你无需在图像的遍历过程中查表作出修改。
首先,我们构建一个Mat类型的查询表:

    Mat lookUpTable(1, 256, CV_8U);    uchar *p = lookUpTable.data;    for( int i = 0; i < 256; ++i)        p[i] = table[i];

最后,调用这个函数(I是我们输入的图像,J是输出的图像):

    LUT(I, lookUpTable, J);

8 性能差异
编译运行程序,图像500x375;使用彩色图像;为了更准确,我对函数调用100次,取其平均值。
图像如下:
这里写图片描述
(1)最有效方法:1.61256 ms
(2)迭代器方法:5.99329 ms
(3)On-the-Fly RA: 6.52525 ms
(4)LUT函数:0.640021 ms
结论:
(1)尽可能的使用OpenCV已经存在的函数,代替使用重构的函数;
(2)最快的方法是LUT函数。这是因为OpenCV库通过Intel Threading Building Blocks使能了多线程。
(3)迭代器方法比较安全,但是效率比较低。at函数处理可读性比较高以外,不建议使用。
完整代码如下:

#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <iostream>#include <sstream>using namespace std;using namespace cv;static void help(){    cout        << "\n--------------------------------------------------------------------------" << endl        << "This program shows how to scan image objects in OpenCV (cv::Mat). As use case"        << " we take an input image and divide the native color palette (255) with the "  << endl        << "input. Shows C operator[] method, iterators and at function for on-the-fly item address calculation."<< endl        << "Usage:"                                                                       << endl        << "./howToScanImages imageNameToUse divideWith [G]"                              << endl        << "if you add a G parameter the image is processed in gray scale"                << endl        << "--------------------------------------------------------------------------"   << endl        << endl;}Mat& ScanImageAndReduceC(Mat& I, const uchar* table);Mat& ScanImageAndReduceIterator(Mat& I, const uchar* table);Mat& ScanImageAndReduceRandomAccess(Mat& I, const uchar * table);int main( int argc, char* argv[]){    help();    if (argc < 3)    {        cout << "Not enough parameters" << endl;        return -1;    }    Mat I, J;    if( argc == 4 && !strcmp(argv[3],"G") )        I = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);    else        I = imread(argv[1], CV_LOAD_IMAGE_COLOR);    if (!I.data)    {        cout << "The image" << argv[1] << " could not be loaded." << endl;        return -1;    }    int divideWith = 0; // convert our input string to number - C++ style    stringstream s;    s << argv[2];    s >> divideWith;    if (!s || !divideWith)    {        cout << "Invalid number entered for dividing. " << endl;        return -1;    }    uchar table[256];    for (int i = 0; i < 256; ++i)       table[i] = (uchar)(divideWith * (i/divideWith));    const int times = 100;    double t;    t = (double)getTickCount();    for (int i = 0; i < times; ++i)    {        cv::Mat clone_i = I.clone();        J = ScanImageAndReduceC(clone_i, table);    }    t = 1000*((double)getTickCount() - t)/getTickFrequency();    t /= times;    cout << "Time of reducing with the C operator [] (averaged for "         << times << " runs): " << t << " milliseconds."<< endl;    t = (double)getTickCount();    for (int i = 0; i < times; ++i)    {        cv::Mat clone_i = I.clone();        J = ScanImageAndReduceIterator(clone_i, table);    }    t = 1000*((double)getTickCount() - t)/getTickFrequency();    t /= times;    cout << "Time of reducing with the iterator (averaged for "        << times << " runs): " << t << " milliseconds."<< endl;    t = (double)getTickCount();    for (int i = 0; i < times; ++i)    {        cv::Mat clone_i = I.clone();        ScanImageAndReduceRandomAccess(clone_i, table);    }    t = 1000*((double)getTickCount() - t)/getTickFrequency();    t /= times;    cout << "Time of reducing with the on-the-fly address generation - at function (averaged for "        << times << " runs): " << t << " milliseconds."<< endl;    Mat lookUpTable(1, 256, CV_8U);    uchar* p = lookUpTable.data;    for( int i = 0; i < 256; ++i)        p[i] = table[i];    t = (double)getTickCount();    for (int i = 0; i < times; ++i)        LUT(I, lookUpTable, J);    t = 1000*((double)getTickCount() - t)/getTickFrequency();    t /= times;    cout << "Time of reducing with the LUT function (averaged for "        << times << " runs): " << t << " milliseconds."<< endl;    return 0;}Mat& ScanImageAndReduceC(Mat& I, const uchar* const table){    // accept only char type matrices    CV_Assert(I.depth() != sizeof(uchar));    int channels = I.channels();    int nRows = I.rows;    int nCols = I.cols * channels;    if (I.isContinuous())    {        nCols *= nRows;        nRows = 1;    }    int i,j;    uchar* p;    for( i = 0; i < nRows; ++i)    {        p = I.ptr<uchar>(i);        for ( j = 0; j < nCols; ++j)        {            p[j] = table[p[j]];        }    }    return I;}Mat& ScanImageAndReduceIterator(Mat& I, const uchar* const table){    // accept only char type matrices    CV_Assert(I.depth() != sizeof(uchar));    const int channels = I.channels();    switch(channels)    {    case 1:        {            MatIterator_<uchar> it, end;            for( it = I.begin<uchar>(), end = I.end<uchar>(); it != end; ++it)                *it = table[*it];            break;        }    case 3:        {            MatIterator_<Vec3b> it, end;            for( it = I.begin<Vec3b>(), end = I.end<Vec3b>(); it != end; ++it)            {                (*it)[0] = table[(*it)[0]];                (*it)[1] = table[(*it)[1]];                (*it)[2] = table[(*it)[2]];            }        }    }    return I;}Mat& ScanImageAndReduceRandomAccess(Mat& I, const uchar* const table){    // accept only char type matrices    CV_Assert(I.depth() != sizeof(uchar));    const int channels = I.channels();    switch(channels)    {    case 1:        {            for( int i = 0; i < I.rows; ++i)                for( int j = 0; j < I.cols; ++j )                    I.at<uchar>(i,j) = table[I.at<uchar>(i,j)];            break;        }    case 3:        {         Mat_<Vec3b> _I = I;         for( int i = 0; i < I.rows; ++i)            for( int j = 0; j < I.cols; ++j )               {                   _I(i,j)[0] = table[_I(i,j)[0]];                   _I(i,j)[1] = table[_I(i,j)[1]];                   _I(i,j)[2] = table[_I(i,j)[2]];            }         I = _I;         break;        }    }    return I;}
0 0
原创粉丝点击