Count the pixel (black or white) in real time.
I need to count the black and white pixels of the object in REAL TIME. What is the best method to use for this ? In my program, First I get the biggest contour .The next process is to count the pixels(black) of the object that have no mask but I don't know how to do it. Thanks in advance.
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
int main(int argc, char** argv)
{
vector<Vec4i> hierarchy;
CvCapture* capture = cvCaptureFromCAM(0);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 270);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 190);
cv::Mat src;
while(true) {
src = cvQueryFrame( capture );
Mat gray;
cvtColor(~src, gray, CV_BGR2GRAY);
//medianBlur(gray,gray,27);
threshold(gray, gray, 220, 255, THRESH_BINARY);
vector<vector<Point> > contours;
findContours( gray.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(gray.rows, gray.cols, CV_8UC1);
drawContours( mask, contours, i, CV_RGB(255,255,255), -1, 8,
vector<Vec4i>(), 0,Point() ); //masking//
Mat crop(src.rows, src.cols, CV_8UC3);
crop.setTo(Scalar(0,0,255));
src.copyTo(crop, mask);
Mat masked;
gray.copyTo(masked, mask);
int count_black = cv::countNonZero(masked == 255);
printf("count_black = %d\n",count_black);
printf("ContourArea = %.0f\n\n",
((contourArea(contours[i]))+( arcLength( contours[i],
true )/2)));
imshow("cropped", crop);
imshow("source", src);
waitKey(33);
}
}
}
}
5 peso coin cool.