简体   繁体   中英

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?

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

You can use paralell computing. You divide the image in N parts and run your code in differents threads then you get the result of each threads and after this you can add this results for obtain the finally amount.

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

Here is simple code that access 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
   }
}
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM