Best method to count the black and white pixels of the image.
After I masked the image and get the part I wanted. The next process is to count the black and white pixels of the unmasked part of the image but I don't know how to do it. Anyone who can give me the method to solve this.
#include "opencv\cvaux.h" #include "opencv\cxmisc.h" #include "opencv\highgui.h" #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <stdlib.h>
using namespace std; using namespace cv;
int main(int, char**) { Mat threshold_output; vector<vector<point> > contours; vector<vec4i> hierarchy; RNG rng(12345);
CvCapture* capture = cvCaptureFromCAM(0);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 270);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 190);
cv::Mat frame; cv::Mat src_gray;
while(true) {
frame = cvQueryFrame( capture );
cvtColor( frame,src_gray, CV_BGR2GRAY );
medianBlur( src_gray, src_gray, 25 );
threshold( src_gray.clone(), threshold_output, 20, 255,CV_THRESH_BINARY_INV);
findContours( threshold_output.clone(), contours,hierarchy,CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
for (int i = 0; i < contours.size(); i++)
{
double area =contourArea(contours[i]);
Rect rect = boundingRect(contours[i]);
if (area >= 30 && abs(1 - ((double)rect.width /(double)rect.height)) <= 0.1)
{
Mat mask = Mat::zeros(threshold_output.rows, threshold_output.cols, CV_8UC1);
drawContours( mask, contours,i , Scalar::all(255), -1);
Mat crop(frame.rows, frame.cols, CV_8UC3);
crop.setTo(Scalar(255,255,255));
frame.copyTo(crop, mask);
int count_black = 0;
int count_white = 0;
int black_total;
int white_total;
for( int y = 0; y < frame.rows; y++ )
{
for( int x = 0; x < frame.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 ( frame.at<cv::Vec3b>(y,x) == cv::Vec3b(0,0,0) )
{
count_black++;
black_total = count_black + count_black ;
printf("black= %d",black_total);
}
}
}
}
imshow( "frame", frame );
imshow("crop",crop);
waitKey(33);
}
}
}
}
Excuse me, but you have been adapting your topic for various times now, nevertheless you assigned it as solved. This is quite irritating, since it keeps popping back to the beginning and people get notices about problems. However, with each edit, you forget to mention what you are doing. Please keep an edit history to mark why it changes.