【问题标题】:How to detect these white spots?如何检测这些白点?
【发布时间】:2021-07-29 04:49:17
【问题描述】:

我有一张图像,我需要计算其中的白点。我试过这段代码,但效果很差:

CircleSegment[] circles;
Mat dst = new Mat();
Mat train = new Mat(path, ImreadModes.Grayscale);

Cv2.GaussianBlur(train, dst, new OpenCvSharp.Size(1, 1), 4, 550);
circles = Cv2.HoughCircles(dst, HoughMethods.Gradient, 5, 50, 1, 60, 1, 60);

for (int i = 0; i < circles.Length; i++)
{
    count++;
    Cv2.Circle(dst, (OpenCvSharp.Point)circles[i].Center, (int)circles[i].Radius, new Scalar(125), 2);
}

using (new Window("Circles", dst))
{
    Cv2.WaitKey();
}
MessageBox.Show(count.ToString(), "Result", MessageBoxButtons.OK);

我附上原图,结果:

【问题讨论】:

  • 我认为问题是你的圆圈不是完美的圆圈,你可能需要使用其他工具
  • 尝试使用计数检测器

标签: c# opencv


【解决方案1】:

二值化后,您可以简单地将图像提供给Cv2.ConnectedComponents。更多信息请参见对应的OpenCV函数cv::connectedComponents

这是获取白点数量的最少代码:

using OpenCvSharp;

namespace OpenCVSharpTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using var img = new Mat("z4BL7.png", ImreadModes.Grayscale);
            Cv2.Threshold(img, img, 0, 255, ThresholdTypes.Otsu);

            using var labels = new Mat();
            int ncc = Cv2.ConnectedComponents(img, labels);
            System.Console.WriteLine("Number of white spots: " + ncc.ToString());
        }
    }
}

控制台输出为:

Number of white spots: 551

由于我更精通 Python(OpenCV 的 API),尤其是用于可视化目的,因此这里也有相应的代码:

import cv2

img = cv2.imread('z4BL7.png', cv2.IMREAD_GRAYSCALE)
img = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)[1]

ncc, labels = cv2.connectedComponents(img)
print('Number of white spots:', ncc)

# Just for visualization
import matplotlib.pyplot as plt
plt.imshow(labels)
plt.show()

控制台输出是一样的,下面是可视化:

-----------------------------------------------------
System information
-----------------------------------------------------
Platform:                   Windows-10-10.0.16299-SP0

Visual Studio Prof. 2019:   16.4.4
OpenCvSharp4.Windows:       4.5.2.20210404

Python:                     3.9.1
PyCharm:                    2021.1.1
Matplotlib:                 3.4.1
OpenCV:                     4.5.1
-----------------------------------------------------

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 1970-01-01
    • 2012-04-05
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 2022-06-14
    • 1970-01-01
    相关资源
    最近更新 更多