Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count 'white' pixels in opencv binary image (efficiently)

I am trying to count all the white pixels in an OpenCV binary image. My current code is as follows:

  whitePixels = 0;
  for (int i = 0; i < height; ++i)
    for (int j = 0; j < width; ++j)
      if (binary.at<int>(i, j) != 0)
        ++whitePixels;

However, after profiling with gprof I've found that this is a very slow piece of code, and a large bottleneck in the program.

Is there a method which can compute the same value faster?

like image 988
Bill Cheatham Avatar asked Dec 07 '11 17:12

Bill Cheatham


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

cv::CountNonZero. Usually the OpenCV implementation of a task is heavily optimized.

like image 127
Josh Bleecher Snyder Avatar answered Oct 18 '22 21:10

Josh Bleecher Snyder