1

I am trying this code to calculate my binary image pixels value by this code :

int main()
{
    Mat img;

    img=imread("/home/2b.jpeg", CV_LOAD_IMAGE_UNCHANGED);
    namedWindow("win", WINDOW_AUTOSIZE);
    imshow("win", img);

    for(int i=0; i< img.rows ;i++)
    {
        for(int j=0; j< img.cols ; j++)
        {
            cout<<setw(10)<<img.at<int>(i,j);
        }
        cout<<endl<<endl<<endl;
    }

    waitKey(0);

    return 0;
}

But I get 3 types of value: 0, -1 and some big different numbers like (24342234 , 1324244242, etc)

What is the problem? I drew one black line in paint programs and save the image, or download binary image from internet but I get same results!

I thought when I use binary images I must get 0 for white pixels and 255 for black ones.

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
Hasani
  • 3,543
  • 14
  • 65
  • 125

3 Answers3

2

First, you should access its pixels with type uchar (unsigned char) instead of int.

And when cout, you must explicitly convert to other types like int in order to print it correctly because cout will work weird when printing unsigned char when its value is larger than 127. Otherwise, it will print some garbage value (or nothing) as it is just a non-printable ASCII character which is getting printed anyway. Check out Why "cout" works weird for "unsigned char"?.

cout << setw(10) << (int) img.at<uchar>(i,j);
                    ^^^^^        ^^^^^             
Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
0

Try loading it as CV_IMAGE_GRAYSCALE, and accessing pixel values with image.at< uchar>(y,x).

edu_
  • 850
  • 2
  • 8
  • 16
  • Thank you! It worked but I want to know why when I choose CV_LOAD_IMAGE_(other options) , it doesn't work true? – Hasani May 09 '14 at 05:12
  • @user3486308 For gray-scale images, it should work for both `CV_IMAGE_GRAYSCALE` and `CV_LOAD_IMAGE_UNCHANGED` (<0, i.e. loads the image as is (including the alpha channel if present). – herohuyongtao May 09 '14 at 05:20
  • Thank you herohuyongtao. – Hasani May 09 '14 at 05:38
0

You are trying to access integer value while actually your mat is uchar. Try changing inside loop line to:

cout<<setw(10)<<img.at<uchar>(i,j);
bheliom
  • 121
  • 3