Nightwind
Nightwind

Reputation: 1

How to detect these white spots?

I have an image where I need to count the white spots. I tried this code, but it works badly:

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

I attach the original image, and the result:

Original image

Result

Upvotes: 0

Views: 339

Answers (1)

HansHirse
HansHirse

Reputation: 18895

After binarization, you can simply feed your image to Cv2.ConnectedComponents. For more information, see the corresponding OpenCV function cv::connectedComponents.

That'd be the minimal code to get the number of the white spots:

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

The console output is:

Number of white spots: 551

Since I'm more fluent in (the) Python (API of OpenCV), especially for visualization purposes, here's the corresponding code for that, too:

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()

Console output is the same, and here's the visualization:

Visualization

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

Upvotes: 1

Related Questions