# How to cluster a set of images?

I have a set of images (imgset) as

Clearly, the classification list should be

{1,1,1,2,2,2,1,1,1,2,2,2,3,3,3,4,4,4,3,3,3,4,4,4,5,5,5,6,6,6,5,5,5,6,6,6}


One approach that I have tried is binarizing the images (using Binarize) followed by computing the DiceDissimilarity between any two images. However, I don't find any fixed threshold value to group the images.

How efficiently can these images be classified?

• @AntonAntonov Title edited. Thanks. – Majis May 29 '18 at 17:36
• The "Spectral" method for FindClusters does a good job IF you specify the number of clusters which, I realize, is a big if... FindClusters[imgs, 6, Method -> "Spectral"]. – MarcoB May 29 '18 at 18:41
• @MarcoB I tried that first, but I thought although the results are kind of good, that approach does not allow much further tweaking. (Someone who knows image processing better than me might disagree...) – Anton Antonov May 29 '18 at 18:51

Here is the result with a somewhat too ad-hoc clustering:

May be with some tweaking the code below can produce more desired results. But please observe the obtained clusters. Although, they are not exactly as the ones mentioned in the question the found clusters "make lots of sense."

## Get the images

imgLinks =
Flatten[StringCases[
Import["https://mathematica.stackexchange.com/q/174223/34008",
"Hyperlinks"], __ ~~ "imgur" ~~ __]]

imgs = Import /@ Take[imgLinks,36]


## First try

ColumnForm[FindClusters[imgs, 6, Method -> "Spectral"]]


## Clustering code

In order to get better results with further tweaking I would use a vector representation. FeatureExtract (coupled with transformations like GaussianFilter etc.) can be used, but I got better results by just taking the image data.

vecsImgs = Flatten /@ Map[ImageData, imgs];
Tally[Dimensions /@ vecsImgs]

(* {{{5625}, 36}} *)

cls =
FindClusters[vecsImgs -> Range[Length[vecsImgs]], 6,
DistanceFunction -> CosineDistance]

(* {{1, 2, 3, 7, 8, 9, 25, 27}, {4, 5, 6, 10, 11, 12}, {13, 14,
15, 19, 20, 21, 26}, {16, 17, 18, 22, 23, 24}, {28, 29, 30, 34, 35,
36}, {31, 32, 33}} *)

ColumnForm[imgs[[#]] & /@ cls]