简体   繁体   English

计算opencv二进制图像中的“白色”像素(有效)

[英]Count 'white' pixels in opencv binary image (efficiently)

I am trying to count all the white pixels in an OpenCV binary image.我正在尝试计算 OpenCV 二进制图像中的所有白色像素。 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.但是,在使用 gprof 进行分析后,我发现这是一段非常慢的代码,并且是程序中的一个很大的瓶颈。

Is there a method which can compute the same value faster?有没有一种方法可以更快地计算相同的值?

cv::CountNonZero . cv::CountNonZero Usually the OpenCV implementation of a task is heavily optimized.通常,任务的 OpenCV 实现是经过大量优化的。

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.您将图像分成 N 部分并在不同的线程中运行您的代码,然后您将获得每个线程的结果,然后您可以添加这些结果以获得最终数量。

Actually binary.at<int>(i, j) is slow access!实际上binary.at<int>(i, j)访问速度很慢!

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):一行中的最后一个像素通常跟在下一行的第一个像素之后(C 代码):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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