Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

What do you mean with 'unmasked', guess the small round part, which is not red marked, then all black and white pixels in this area can be counted as follows:

int count_black = 0;
int count_white = 0;
for( int y = 0; y < src.rows; y++ ) {
  for( int x = 0; x < src.cols; x++ ) {
    if ( mask.at<uchar>(y,x) != 0 ) {
      // change this to to 'src.atuchar>(y,x) == 255' 
      // if your img has only 1 channel
      if ( src.at<cv::Vec3b>(y,x) == cv::Vec3b(255,255,255) ) {
        count_white++;
      } 
      else if ( src.at<cv::Vec3b>(y,x) == cv::Vec3b(0,0,0) ) {
        count_black++;
      } 
    }
}

Note: if you know that you deal with a binary image, than this can be accomplished easier with cv::countNonZero(), hope you got the idea.

What do you mean with 'unmasked', guess the small round part, which is not red marked, then all black and white pixels in this area can be counted as follows:

int count_black = 0;
int count_white = 0;
for( int y = 0; y < src.rows; y++ ) {
  for( int x = 0; x < src.cols; x++ ) {
    if ( mask.at<uchar>(y,x) != 0 ) {
      // change this to to 'src.atuchar>(y,x) == 255' 
      // if your img has only 1 channel
      if ( src.at<cv::Vec3b>(y,x) == cv::Vec3b(255,255,255) ) {
        count_white++;
      } 
      else if ( src.at<cv::Vec3b>(y,x) == cv::Vec3b(0,0,0) ) {
        count_black++;
      } 
    }
}

Note: if you know that you deal with a binary image, than this can be accomplished easier with cv::countNonZero(), hope you got the idea.


EDIT

If you actually want the black & white pixels of the binary image 'gray', then you need to replace

findContours(gray, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

with

findContours(gray.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

(since findContours modifies the matrix). Furthermore replace each instance of 'src' with gray, i.e.:

int count_black = 0;
int count_white = 0;
for( int y = 0; y < gray.rows; y++ ) {
  for( int x = 0; x < gray.cols; x++ ) {
    if ( mask.at<uchar>(y,x) != 0 ) {
      if ( gray.at<uchar>(y,x) == 255 ) {
        count_white++;
      } 
      else {
        count_black++;
      } 
    }
}