OpenCV outputing odd pixel values

折月煮酒 提交于 2021-01-28 19:14:34

问题


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?


回答1:


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"?.




回答2:


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.



来源:https://stackoverflow.com/questions/22570107/opencv-outputing-odd-pixel-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!