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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With