C++ – Accessing RGB values of all pixels in a certain image in openCV

copencvpixelrgb

I have searched internet and stackoverflow thoroughly, but I didn't find what exactly I'm looking for!

How can I get RGB (BGR actually) values of a certain image (all pixels of the image) in OpenCV? I'm using C++, the image is stored in cv::Mat variable.

I'm showing some of my efforts so far: I tried this code from another stackoverflow link. But every time I re-run the code the value in Hexadecimal changed! For example once its 00CD5D7C, in next run it is 00C09D7C.

cv::Mat img_rgb = cv::imread("img6.jpg");
Point3_<uchar>* p = img_rgb.ptr<Point3_<uchar> >(10,10);
p->x; //B
p->y; //G
p->z; //R
std::cout<<p;

In another try I used this code from another answer. Here output is always -858993460.

img_rgb.at<cv::Vec3b>(10,10);
img_rgb.at<cv::Vec3b>(10,10)[0] = newval[0];
img_rgb.at<cv::Vec3b>(10,10)[1] = newval[1];
img_rgb.at<cv::Vec3b>(10,10)[2] = newval[2];

cout<<newval[0]; //For cout<<newval[1]; cout<<newval[2]; the result is still same

NOTE: I used (10,10) as a test to get the RGB, my target is get the RGB values if the whole image!

Best Answer

Since you are loading a color image (of type CV_8UC3), you need to access its elements with .at<Vec3b>(row, col). The elements are in BGR order:

Mat img_bgr = imread("path_to_img");

for(int r = 0; r < img_bgr.rows; ++r) {
    for(int c = 0; c < img_bgr.cols; ++c) {
        std::cout << "Pixel at position (x, y) : (" << c << ", " << r << ") =" <<
             img_bgr.at<Vec3b>(r,c) << std::endl;
    }
}

You can also simplify using Mat3b (aka Mat_<Vec3b>), so you don't need to use the .at function, but using directly the parenthesis:

Mat3b img_bgr = imread("path_to_img");

for(int r = 0; r < img_bgr.rows; ++r) {
    for(int c = 0; c < img_bgr.cols; ++c) {
        std::cout << "Pixel at position (x, y) : (" << c << ", " << r << ") =" <<
             img_bgr(r,c) << std::endl;
    }
}

To get each single channel, you can easily do:

 Vec3b pixel = img_bgr(r,c); // or img_bgr.at<Vec3b>(r,c)
 uchar blue = pixel[0];
 uchar green = pixel[1];
 uchar red = pixel[2];