简体   繁体   中英

Fastest way to extract individual pixel data?

I have to get information about the scalar value of a lot of pixels on a gray-scale image using OpenCV. It will be traversing hundreds of thousands of pixels so I need the fastest possible method. Every other source I've found online has been very cryptic and hard to understand. Is there a simple line of code that should just hand a simple integer value representing the scalar value of the first channel (brightness) of the image?

for (int row=0;row<image.height;row++) {
    unsigned char *data = image.ptr(row);
    for (int col=0;col<image.width;col++) {
       // then use *data for the pixel value, assuming you know the order, RGB etc           
       // Note 'rgb' is actually stored B,G,R
       blue= *data++;
       green = *data++;
       red = *data++;
    }
}

You need to get the data pointer on each new row because opencv will pad the data to 32bit boundary at the start of each row

With regards to Martin's post, you can actually check if the memory is allocated continuously using the isContinuous() method in OpenCV's Mat object. The following is a common idiom for ensuring the outer loop only loops once if possible:

#include <opencv2/core/core.hpp>

using namespace cv;

int main(void)
{

    Mat img = imread("test.jpg");
    int rows = img.rows;
    int cols = img.cols;

    if (img.isContinuous())
    {
        cols = rows * cols; // Loop over all pixels as 1D array.
        rows = 1;
    }

    for (int i = 0; i < rows; i++)
    {
        Vec3b *ptr = img.ptr<Vec3b>(i);
        for (int j = 0; j < cols; j++)
        {
            Vec3b pixel = ptr[j];
        }
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM