问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/16929190/fastest-way-to-get-number-of-white-pixels-in-a-binary-image-using-opencv