The fastest way to extract individual pixel data?

I need to get information about the scalar value of a large number of pixels in a gray image using OpenCV. It will go through hundreds of thousands of pixels, so I need the fastest way. Every other source that I found on the Internet was very mysterious and difficult to understand. Is there a simple line of code that should just pass a simple integer value representing the scalar value of the first channel (brightness) of the image?

+4
source share
2 answers
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 a pointer to each new line, because opencv will put data on a 32-bit border at the beginning of each line

+4
source

As for Martin's post, you can check if memory is constantly allocated using the isContinuous () method in the OpenCV Mat object. The following is a general idiom to ensure that the outer loop includes only one cycle, 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; } 
+3
source

Source: https://habr.com/ru/post/1392351/


All Articles