Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to get number of white pixels in a binary image using OpenCV

Tags:

c#

opencv

emgucv

What is the fastest way to get number of white pixels in a binary picture using OpenCV? Is there something faster than using two for loops and accessing the image pixel by pixel?

like image 257
xx77aBs Avatar asked Jun 04 '13 23:06

xx77aBs


People also ask

How do you count white pixels in Opencv?

Counting PixelsNumPy provides a function sum() that returns the sum of all array elements in the NumPy array. This sum() function can be used to count the number of pixels on the basis of the required criteria.


1 Answers

The most succinct way to accomplish this is:

cv::Mat image, mask;    //image is CV_8UC1
cv::inRange(image, 255, 255, mask);
int count = cv::countNonZero(mask);

If you are operating on a binary image, then the call to cv::inRange() is unnecessary, and simply cv::countNonZero() will suffice.

Although any method must iterate through all the pixels, this may be able to harness OpenCV's built-in parallel_for_(), which allows parallel execution.

If your image is continuous, you can iterate through all the data using a single loop.

like image 110
Aurelius Avatar answered Sep 21 '22 07:09

Aurelius