How to access RGB values ​​in Opencv?

I am confused about using the number of channels. Which one is correct:

// roi is the image matrix for(int i = 0; i < roi.rows; i++) { for(int j = 0; j < roi.cols; j+=roi.channels()) { int b = roi.at<cv::Vec3b>(i,j)[0]; int g = roi.at<cv::Vec3b>(i,j)[1]; int r = roi.at<cv::Vec3b>(i,j)[2]; cout << r << " " << g << " " << b << endl ; } } 

Or

 for(int i = 0; i < roi.rows; i++) { for(int j = 0; j < roi.cols; j++) { int b = roi.at<cv::Vec3b>(i,j)[0]; int g = roi.at<cv::Vec3b>(i,j)[1]; int r = roi.at<cv::Vec3b>(i,j)[2]; cout << r << " " << g << " " << b << endl ; } } 
+7
source share
3 answers

the second is correct, the rows and columns inside the matrix represent the number of pixels, while the channel has nothing to do with the number of rows and columns. and CV use BGR by default, therefore, assuming Mat is not converted to RGB, the code is correct

link, personal experience, OpenCV docs

+2
source

A faster way to get color components from an image is to represent the image as an IplImage structure, and then use the pixel size and the number of channels to iterate through it using pointer arithmetic.

For example, if you know that your image is a three-channel image with 1 byte per pixel, and its format is BGR (by default in OpenCV), the following code will access its components:

(In the following code, img is of type IplImage .)

 for (int y = 0; y < img->height; y++) { for(int x = 0; x < img->width; x++) { uchar *blue = ((uchar*)(img->imageData + img->widthStep*y))[x*3]; uchar *green = ((uchar*)(img->imageData + img->widthStep*y))[x*3+1]; uchar *red = ((uchar*)(img->imageData + img->widthStep*y))[x*3+2]; } } 

For a more flexible approach, you can use the CV_IMAGE_ELEM macro defined in types_c.h :

 /* get reference to pixel at (col,row), for multi-channel images (col) should be multiplied by number of channels */ #define CV_IMAGE_ELEM( image, elemtype, row, col ) \ (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)]) 
+1
source

I guess the second one is correct, however, a lot of time to get the data.

A faster method is to use the IplImage * data structure and increment the address specified with the size of the data contained in roi ...

0
source

All Articles