Convert binary image values to '0' '1' integers

asked 2015-04-30 04:22:50 -0500

Irenicus gravatar image

updated 2015-04-30 04:25:11 -0500

I'm trying to convert a binary mask (for an image) to an integer array, and so far I'm having trouble understanding how to regard the type and value of the pixels in this image.

I used a binary image file containing imgMask:

threshold(bgIsolation, imgMask, 10, 255, THRESH_BINARY);

image description

Then tried to convert it to an integer vector for later classification, using the following function:

void color_imgreshape_2_1(Mat &img, int *class_labels){
    int i = 0;
    cout << "rows: " << img.rows << " cols: " << img.cols << endl;
    for (int x = 0; x < img.cols; ++x){
        for (int y = 0; y < img.rows; ++y){
            class_labels[i++] = (int)<uchar>(y,x);
    ofstream out("out.txt");
    cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
    for (int i = 0; i < img.rows * img.cols; i++)
        cout << class_labels[i] << endl;

Redirecting the labels vector output to a file, it appears that it contains different values, and no 1's or 0's.

So can anyone tell me how to convert those pixel values to integers?

edit retag flag offensive close merge delete


  • "I'm trying to convert a binary mask (for an image) to an integer array" - why ?
  • "it contains different values, and no 1's or 0's" - try to use threshold(bgIsolation, imgMask, 10, 1, THRESH_BINARY); then
berak gravatar imageberak ( 2015-04-30 04:40:00 -0500 )edit

changing maxval produced a completely black image.

In any case, my goal is to understand which pixels are considered 'white', and which are 'black', in order to build class labels for classification, like I said. From what I see, there aren't just 2 values representing two colours, but much more.

I'm new to opencv, so I'm still unclear about how binary images are represented in it.

Irenicus gravatar imageIrenicus ( 2015-04-30 04:58:37 -0500 )edit

hmm, at least the image shown above seem to have only 0 and 255 values.

and yes, if you use 1 for maxVal it will be hard to spot the difference with imshow (that's probably , why 255 is used for 'on' normally)

(can it be, you're simply using the wrong image ?)

berak gravatar imageberak ( 2015-04-30 05:03:12 -0500 )edit

I don't think so, I used imshow before use, maybe the problem stem from a different source, the Eclipse IDE behaves strangely for the last few days.

Thanks anyway.

Irenicus gravatar imageIrenicus ( 2015-04-30 05:14:13 -0500 )edit