Cycle through pixels with opencv

后端 未结 7 2206
情深已故
情深已故 2020-12-07 17:46

How would I be able to cycle through an image using opencv as if it were a 2d array to get the rgb values of each pixel? Also, would a mat be preferable over an iplimage for

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 18:34

    The docs show a well written comparison of different ways to iterate over a Mat image here.

    The fastest way is to use C style pointers. Here is the code copied from the docs:

    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(i);
        for ( j = 0; j < nCols; ++j)
        {
            p[j] = table[p[j]];
        }
    }
    return I;
    }
    

    Accessing the elements with the at is quite slow.

    Note that if your operation can be performed using a lookup table, the built in function LUT is by far the fastest (also described in the docs).

提交回复
热议问题