Count white pixels in opencv binary (effective)

I am trying to count all 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 found this to be a very slow piece of code and a big bottleneck in the program.

Is there a way that calculates the same value faster?

+5
source share
4 answers

cvCountNonZero. Typically, the implementation of an OpenCV task is highly optimized.

+20
source

paralell. N , , .

0

The last pixel in a row is usually followed by the first pixel in the next row (C code):

limit=width*height;
i=0;
while (i<limit)
{
  if (binary.at<int>(0,i) != 0) ++whitePixels;
  ++i;
}
-2
source

Actually binary.at<int>(i, j)is slow access!

Here is a simple code that works faster than yours.

for (int i = 0; i < height; ++i)
{
uchar * pixel = image.ptr<uchar>(i);
    for (int j = 0; j < width; ++j)
{
  if(pixel[j]!=0)
   {
      //do your job
   }
}
}
-2
source

All Articles