read pixel values of a binary image in opencv

2.9k views Asked by At

I'm new in openCV.I want to read an binary grayscale image.I printed value of pixels in matlab and It was only 0 and 1 but when I read the same image in openCV the value of pixels is between 0 and 255 (and not just 0 and 255). I want to read the image in a way that pixels are just 0 or 1 (OR 0 and 255). This is how I read the image and print the pixels value:

Mat watermarkImage;  
watermarkImage = imread("C:\\path\\to\\image\\logo.png");
Mat wmrk = watermarkImage.clone();
Mat tmp2(64, 64, CV_32FC1);
resize(wmrk, wmrk , tmp2.size());
//wmrk.convertTo(wmrk,CV_32FC1, 1.0/255.0);
for(int i=0 ; i<64; i++)
{
    for(int j=0 ; j<64 ; j++)
    {
        cout<<int(wmrk.at<uchar>(i,j))<<"  ";
    }
    cout<<endl;
}
1

There are 1 answers

0
Micka On

Please try the following:

Mat watermarkImage;  
// make sure you have a single channel image (grayscale):
watermarkImage = imread("C:\\path\\to\\image\\logo.png",CV_LOAD_IMAGE_GRAYSCALE);

Mat wmrk = watermarkImage .clone();
resize(wmrk, wmrk , cv::Size(64,64));

// create a binary image where each value is either 0 or 255
Mat mask = wmrk > 0; // or take any other threshold to mask values > thres

Mat binaryOnes = mask/255;



cout << binaryOnes<< endl;

/*
for(int i=0 ; i<wmrk.rows; i++)
{
    for(int j=0 ; j<wmrk.cols ; j++)
    {
        cout<< (int)(wmrk.at<uchar>(i,j))<<"  ";
    }
cout<<endl;
}
*/

one way to get a binary image is to apply a threshold. In OpenCV binary images are typically 0 and 255 instead of 0 and 1, but if you need it, you can easily create a binary image and divide the values by 255.