# How to segment an image based on MeanEuclideanDistance?

Consider an image (img) as

Now I have partitioned the image using the following command

parts = ImagePartition[img, 32];


Then I compute the ImageDistance among all the image parts using DistanceFunction as MeanEuclideanDistance.

partsFlatten=Flatten@parts;
meanEuclideanDistance =
Table[{ImageDistance[partsFlatten[[i]], partsFlatten[[j]],
DistanceFunction -> "MeanEuclideanDistance"]}, {i, 1, 49, 1}, {j,
1, 49, 1}]


Now I wish to group the original parts based on meanEuclideanDistance and reconstruct the original image displaying different groups (using different colors preferably).

How can this be achieved?

[Note: In my opinion, a filter can be designed for this specific purpose which will accept the image and the kernel size (32 here), finds a dynamic threshold for the meanEuclideanDistance to group the parts and display the segments.

]

Edit 1: This is what I have come out so far.

Manipulate[im = img;
{w, h} = ImageDimensions[img];
imgparts = ImagePartition[im, {Round[w/np], Round[h/np]}];
{nr, nc} = Dimensions@imgparts;
imgpartsflattened = Flatten@imgparts;
med = Table[{ImageDistance[imgpartsflattened[[i]],
imgpartsflattened[[j]],
DistanceFunction -> "MeanEuclideanDistance"]}, {i, 1, nr, 1}, {j,
1, nc, 1}];
ListPlot[Flatten@med], {np, 1, 100, 1}]


And the corresponding plot for np=8 is as follows

I guess you are looking for a clustering algorithm to group the image patches based on their mutual distance.

Upfront, is beneficial to crop the image size to a multiple of 32, or whatever your preferred patch size should be.

cimg = ImageCrop[img, 32 Quotient[ImageDimensions[img], 32]]


Then, one can perform the actual clustering via ClusteringComponents which be default assumes the Euclidean distance function (essentially the same as "MeanEuclideanDistance" with respect to clustering). The remaining code below handles the rendering of the segmentation.

ImageCompose[
cimg,
{ImageResize[
Colorize@ClusteringComponents[
ImagePartition[cimg, 32, 16],
2
],
ImageDimensions[cimg],
Resampling -> "Constant"],
0.5}
]


To obtain more than 2 segments, simply increase the number of clusters.