# How to count and mark all counted objects in this image

I need some help on image processing in Mathematica (I have unsuccesfully tried with OpenCV).

I have an image:

and I need to count all objects in this image and mark them.

The perfect result would look like this:

Is this possible? How?

Thank you all for your help. Alternative question: Is there a solution how to get rid of all the connections between objects without changing the rest of the image:

• OpenCV ? Are you sure this question is about Wolfram Mathematica ? – Sektor Nov 26 '14 at 20:12
• I failed to solve this by using OpenCV - I do not know if this possible using Wolfram Mathematica! – Lauris Nov 26 '14 at 20:31
• I have not done anything (produced code) yet using Wolfram Mathematica. It was said to me that our University have Wolfram Mathematica so I just wanted to know if this possible and then start to dig in code. – Lauris Nov 26 '14 at 20:50
• Wow! Binarize[img, 0] for a nice surprise! It was there all along! – Aisamu Nov 26 '14 at 22:19
• Yes, this definitely looks like the distance transform of a binary image. Why not provide the original binary image in the first place? – user484 Nov 27 '14 at 8:54

You can play with the binarization value to tweak the results:

img = Import["http://i.stack.imgur.com/LWNaK.png"];
MorphologicalComponents[Binarize[img, 0.4]] // Colorize


You can then calculate the positions, means, sizes, etc of the components using ComponentMeasurements as in this answer.

As for your second question, about removing the links between objects, the straightforward approach here is Erosion. For instance

Erosion[img, 5]


nicely removes the bulk of the links. Again, you will want to play with the erosion parameter (in this case 5) for best effect.

• Thank you for the answer! What would be your guess of percentage of objects which I will be able to count and mark by this approach? – Lauris Nov 26 '14 at 20:53
• There are two kinds of errors that might happen: you might miss a component that does exist or you might find an extra one (that doesn't really exist). You can balance these two possible kinds of errors, but never eliminate them completely. – bill s Nov 26 '14 at 20:55
• That is clear! I am planning to analyse medical data. Allowed error is plus/minus 3%. Currently I have error of 15% or more :( – Lauris Nov 27 '14 at 8:35

Here's a set of functions, drawn mostly from here and a portion of this screencast. It is not a perfect answer at this point; the major problem being the small tendrils that link features together. It is possible that some type of filter with a DiskMatrix mask will lead you to a better result, but for the moment, I suspect there's a lot to wade through here.

seimg = Import["http://i.stack.imgur.com/LWNaK.png"];
i = GaussianFilter[FillingTransform[seimg], 15];
b = Binarize[i];
d = DistanceTransform[b, Padding -> 0];