I'm testing to see if I can count/draw circles around dots I drew on a piece of paper, this research is for my thesis as I want to count the amount of pinholes in a composite laminate. I tried several methods that were already given in several forums.

The code I use is:

img = Import["https://i.imgur.com/Wu7pSBY.jpg"];
i = GaussianFilter[FillingTransform[img], 15];
b = Binarize[i];
d = DistanceTransform[b, Padding -> 0];
m = MaxDetect[ImageAdjust[d, 0.2]];
w = WatershedComponents[GradientFilter[b, 3], m, Method -> "Rainfall"];
s = SelectComponents[w, "Count", 20 < # < 10000 &];
ms = ComponentMeasurements[
   s, {"Centroid", "EquivalentDiskRadius", "Label"}];
 Graphics[{Blue, Circle @@ # & /@ (ms[[All, 2, 1 ;; 2]]), 
   MapThread[Text, {ms[[All, 2, 3]], ms[[All, 2, 1]]}]}]]

I have zero to none idea what this all does, but the results are this (click for full size):


The only thing I want it to do is draw circles around the dots and count them. Can anyone help out?

  • 3
    $\begingroup$ All you need is Binarize, ColorNegatve and ComponentMeasurements to find the centroids. Please read up on these. Using code you don't understand is not a good idea. $\endgroup$
    – Szabolcs
    Mar 16, 2021 at 13:40
  • 2
    $\begingroup$ Possible duplicate of Count Elements in Image and Count flowers in an image (which is a duplicate of the first one) $\endgroup$
    – Sumit
    Mar 16, 2021 at 14:06
  • 2
    $\begingroup$ Try studying each line of the code by remove the semi-colons one at a time on each. Just look at the first two, remove semi-colon on the GaussianFilter. See what the output is. Then study the help: Type GaussianFilter, place cursor on it, press the "i" icon and study the help. Do that slowly with each command, learn what's happening then have what I think is a good chance of not only understanding what's happening but improving it. :) $\endgroup$
    – Dominic
    Mar 16, 2021 at 14:13
  • $\begingroup$ Thank you all so much for the respons, I'll experiment with the lines and will study the help. $\endgroup$ Mar 16, 2021 at 14:40
  • 1
    $\begingroup$ See also How to count number of small dots in a picture $\endgroup$
    – Chris K
    Mar 16, 2021 at 16:00

1 Answer 1


I think I have a solid way now to count them, my code is:

img = Import["https://i.imgur.com/Wu7pSBY.jpg"];
b = DeleteSmallComponents[ColorNegate[Binarize[img]], 50];
c = ComponentMeasurements[
   b, {"Centroid", "EquivalentDiskRadius", "Label"}];
Show[b, Graphics[{Red, Circle @@ # & /@ (c[[All, 2, 1 ;; 2]]), 
   MapThread[Text, {c[[All, 2, 3]], c[[All, 2, 1]]}]}]]
c // Length

This resulted in this:


Thanks for the help everyone!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.