Ask Your Question

Revision history [back]

Why not start with naming your valuables into something senseworthy, like rows, cols, i and j. It would make your code much clearer. That being said, I am unsure why you need 3 for loops to go over a 2D matrix, when in principle 2 should be enough.

Some sample code that should work just fine

int counter = 0;
for (int row=0; row<image.rows; row++){
    for(int col=0; col<image.cols; col++){
        if(image.at<uchar>(row,col) == 0){
            counter++;
        }
    }
}

This will only work IF

  • The image is 8UC1, because the uchar is for an 8 bit jump.
  • The black is actually black, so not very small values like 1 or 3 or so.
  • Your image/mask is single channel. For a 3 channel you will need to use Vec3b iterators.

Why not start with naming your valuables into something senseworthy, like rows, cols, i and j. It would make your code much clearer. That being said, I am unsure why you need 3 for loops to go over a 2D matrix, when in principle 2 should be enough.

Some sample code that should work just fine

int counter = 0;
for (int row=0; row<image.rows; row++){
    for(int col=0; col<image.cols; col++){
        if(image.at<uchar>(row,col) == 0){
            counter++;
        }
    }
}

This will only work IF

  • The image is 8UC1, because the uchar is for an 8 bit jump.
  • The black is actually black, so not very small values like 1 or 3 or so.
  • Your image/mask is single channel. For a 3 channel you will need to use Vec3b iterators.

ADDITION: adding sample code for looking at transitions in columns

int previous = 0, current = 0, int counter = 0;
for (int col=1; col<image.rows; col++){
    for(int row=1; row<image.cols; row++){
        previous = image.at<uchar>(row-1,col-1);
        current = image.at<uchar>(row,col);
        if(previous  != current){
            counter++;
        }
    }
}

Notice that I start calculating from the second element, because else we cannot compare. Also I am expecting white to be 255 or 1 and black to be 0, so only 2 possible values.