I was doing some fractal dimension calculation using http://community.wolfram.com/groups/-/m/t/1025046 box counting method and I thought to myself if it would be possible to make a constrain that the boxes (or circles) have to touch at least two edges. that would be a great tool to estimate the size of the features in e.g. fibrous network from SEM images. enter image description here


and plotting e.g. there are 40 circles of size 30px, 10 of size 29px etc. any ideas how to implement that?


1 Answer 1


This is relatively easy using a distance transform:

img = Import["https://i.sstatic.net/Juolc.png"]
binary = Binarize[img, .9];
dist = DistanceTransform[ColorNegate[binary]];

Now, dist, contains for each pixel the euclidean distance to the closest white pixel. The points you're looking for are (I think) the local maxima in this image:

maxPos = ComponentMeasurements[MaxDetect[dist], "Centroid"][[All, 2]];    
radii = PixelValue[dist, maxPos]

Which yields these circles:

Show[binary, Graphics[{Red, MapThread[Circle, {maxPos, radii}]}]]

enter image description here

and the radii:

Histogram[radii, {1}]

enter image description here

These are the circles that are locally maximal. So they're usually touching 3 or more white points. If you want all circles that touch two white points, you should look at SkeletonTransform.

For example, for a square, the method above wold yield only on circle, at the center of the square. SkeletonTransform would yield all points along the diagonals of the square - as circles centered on the diagonals touch the square in two places.

enter image description here

  • $\begingroup$ this is great! One question: is it possible to color code the circles on the image using e.g. rainbow colors with a legend? $\endgroup$
    – dziakku
    Commented Oct 12, 2017 at 11:55
  • $\begingroup$ @dziakku: Sure, you can get gradients (e.g. rainbow colors) using ColorData and create a legend using BarLegend $\endgroup$ Commented Oct 12, 2017 at 16:13
  • $\begingroup$ One additional comment - the code is great in it's simplicity - one good add-on is a GaussianFilter for binazing the image to reduce the noise $\endgroup$
    – dziakku
    Commented Oct 18, 2017 at 9:04

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.