Question

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.

Was it helpful?

Solution

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);
                    ^^^^^        ^^^^^             

OTHER TIPS

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);

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top