1

I want to do processing on images with C++ and have been using OpenCV. I've gotten a bit stuck though when it comes to trying to access each pixel individually. I can output the whole gray scaled image just fine using:

cout << image;

and get the expected output of values like so:

[143, 147, 164, 177, 177, 185, 196, 195, 185, 186, 178, 190, 178, 163, 183...

But when I try to output one pixel at a time using:

for (int y = 0; y < image.rows; ++y) {
    for (int x = 0;x < image.cols; ++x) {
        std::cout<<image.at<double>(y, x)<<" ";
    }
            cout << endl;}

my output is a bunch of large numbers like these:

-2.98684e+18 -1.21685e-83 -1.91543e-113 -1.8525e-59 -2.73052e-127 -2.08731e-35 -3.72066e-103 ...

Any thoughts as to what I am missing or doing wrong?

2 Answers2

1

since your values [143, 147, 164, 177...] look like uchar type your Mat type should be either CV_8U=0 or CV_8UC3=16, which you can check with image.type(). So your output should be (as @Micka noted)

std::cout<<image.at<uchar>(y, x)<<" "; // gray
or
std::cout<<image.at<Vec3b>(y, x)<<" "; // color

In the future just use this in order to stop worrying about the type:

Rect rect(0, 0, 10, 10); // print 10x10 block
cout<<image(rect)<<endl;

Not to say that knowing type isn't important though.

Vlad
  • 4,330
  • 1
  • 29
  • 39
0

If you want to print all pixels of the image, you can simply use:

cout << image << endl;

If you want to print a pixel, use:

cout << image.at<Vec3b>(y, x) << endl; // for color image

or

cout << (int) image.at<uchar>(y, x) << endl; // for gray-scale image

Note that, in the last line, casting it to int is needed. For details, check out Why "cout" works weird for "unsigned char"?.

Community
  • 1
  • 1
herohuyongtao
  • 47,739
  • 25
  • 124
  • 164