opencv中访问Mat的三种方法

转载自官方教程 https://docs.opencv.org/master/db/da5/tutorial_how_to_scan_images.html

官方给出的代码: https://github.com/opencv/opencv/blob/master/samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp

分为三种不同的访问方式:

1. 通过Mat的ptr指针的[]操作符号,按照数组的方式遍历--->效率最高

2. 通过迭代器 cv::MatIterator_进行访问--->效率次之,但是是安全的

3. 不通过ptr指针,直接通过Mat进行访问--->效率最低, 不适合遍历操作,常用于随机位置的访问, "The final method isn't recommended for scanning. It was made to acquire or modify somehow random elements in the image."


#include 
#include 
#include "opencv2/imgcodecs.hpp"
#include 
#include 
#include 

cv::Mat& ScanImageAndReduceC(cv::Mat& I, const uchar* const table);
cv::Mat& ScanImageAndReduceIterator(cv::Mat& I, const uchar* const table);
cv::Mat& ScanImageAndReduceRandomAccess(cv::Mat& I, const uchar* const table);


int main(int argc, char** argv)
{
    std::string imageName( "../data/lei.jpeg" ); // by default

    //cv::imread(imageName, cv::IMREAD_COLOR);
    cv::Mat I = cv::imread(imageName, cv::IMREAD_GRAYSCALE);
    cv::Mat J;

    int dividewith = 8;
    uchar table[256];

    for(int i=0; i<256; ++i)
    {
        table[i] = (uchar)(dividewith * (table[i]/dividewith));
    }

    const int times = 100;

    double t;

    t = (double)cv::getTickCount();

    for(int i=0; i(i);
        for(j=0; j it, end;
            for(it=I.begin(), end=I.end(); it!=end; ++it)
            {
                *it = table[*it];
            }
            break;
        }

    case 3:
        {
            cv::MatIterator_ it, end;
            for(it=I.begin(), end=I.end(); it != end; ++it)
            {
                (*it)[0] = table[(*it)[0]];
                (*it)[1] = table[(*it)[1]];
                (*it)[2] = table[(*it)[2]];
            }

        }

    }

    return I;
}


cv::Mat& ScanImageAndReduceRandomAccess(cv::Mat& I, const uchar* const table)
{
    CV_Assert(I.depth() == CV_8U);

    const int channels = I.channels();

    switch(channels)
    {
    case 1:
        {
            for(int i=0; i(i,j) = table[I.at(i,j)];
                }
            }

            break;
        }

    case 3:
    {
        cv::Mat_ _I = I;

        for(int i=0; i

 

你可能感兴趣的:(OpenCV)