# How can I extract the outline of bubbles in my image?

I have an image:

I tried to extract the outline of the bubbles, but I met with some problems. Firstly I tried the method used in Mathematica documentation for Analyze Segmented Cells In An Image, but it didn't work well, I got an irregular figure:

Then I tried the function EdgeDetect. Things got a little bit better, but it's still not what I want. Could you please help me with my problem?

• One question is.., what do you want out of it? The number of bubbles?
– Öskå
Commented Jul 18, 2014 at 17:46
• I want the outline of each bubble.
– Ryan
Commented Jul 18, 2014 at 17:49
• I've got something like this not perfect, but better :)
– Öskå
Commented Jul 18, 2014 at 18:30
• @Öskå I think it's much better than my picture! Could you please share your method with us?
– Ryan
Commented Jul 19, 2014 at 2:26
• Rahul's answer is even better ;o) Quite the same method though :)
– Öskå
Commented Jul 19, 2014 at 9:06

image = Import["https://i.sstatic.net/UNXEV.jpg"];
n = TotalVariationFilter[image, 0.05]
s = DeleteSmallComponents[ColorNegate[DeleteSmallComponents[b, 20^2]], 20^2]
m = MaxDetect[d, 10]
(w = WatershedComponents[ColorNegate[d], m]) // Colorize
c = ComponentMeasurements[w, {"Centroid", "EquivalentDiskRadius"}, #2 < 50 &];
Show[image, Graphics[{Thick, Red, Circle @@@ c[[All, 2]]}], ImageSize -> 1280]


(Click for bigger.)

Run the code to see the intermediate steps.

Thanks to nikie for the second half of this answer.

LocalAdaptiveBinarize is new in version 10, but all it does is "creates a binary image by replacing values above the mean of the range-$r$ neighborhood with $1$ and others with $0$." So you can replace it with something like, say,

b = Binarize[ImageSubtract[n, MeanFilter[n, 50]], 0]


which gives similar results, though not identical for some reason. Possibly there's a more elegant way to do it.

• Do you think that the same method could work with Polygons? I asked this question hoping to get the same kind of answer :)
– Öskå
Commented Jul 19, 2014 at 9:07
• Thank you for your answer! I think // ImageAdjust // Colorize are of no use during the processing, since d and w aren't changed by these 2 commands. So you just put them here to show the effect of ImageAdjust and Colorize? What's more, for users using Mathematica below 10: Note that function LocalAdaptiveBinarize appears only in Mathematica 10, which means that maybe you cannot use LocalAdaptiveBinarize. For concrete solution, Rahul has showed above.
– Ryan
Commented Jul 20, 2014 at 7:42
• I put the // ImageAdjust and // Colorize there to visualize what the intermediate steps are doing, because you can't tell anything from looking at d and w directly. I've updated my answer with a replacement for LocalAdaptiveBinarize.
– user484
Commented Jul 20, 2014 at 8:56