Search code examples
opencvpixelimage-sizeroi

how to count the pixels in roi opencv


I have an cropped image of a coin. and I've already applied mask so i can focus on the coin itself. Next is I want to count the number of pixels of this coin. I've already read similar posts but i they just don't seem to work for me.

here is the original image: http://s30.postimg.org/eeh3lp99d/IMG_20150414_121300.jpg

and the cropped coin: http://s3.postimg.org/4k2pdst73/cropped.png

HEre is my code so far:

//get the number of pixels of the coin 
//STEP 1: CROP THE COIN 
//get the Rect containing he circl 
Rect rectCircle(center.x - radius, center.y - radius, radius * 2, radius * 2); //obtain the image ROI: 
Mat roi(src_gray, rectCircle); 
//make a black mask, same size: 
Mat mask(roi.size(), roi.type(), Scalar::all(0)); 
//with a white,filled circle in it: 
circle(mask, Point(radius, radius), radius, Scalar::all(255), -1); 
//combine roi and mask: 
cv::Mat coin_cropped = roi & mask;

How do i count the number of pixels of the cropped coin?


Solution

  • You need to use countnonzero

    countNonZero

    Counts non-zero array elements.

    C++: int countNonZero(InputArray src)

    Use this on the ROI matrix and it will return an int of the number of pixels, in your code it will look like this:

    numberOfPixelsInMask = cv::countNonZero(mask);