kmeans
returns the centroids / representative colours that exist in your image stored in CENTERS
and IDX
gives you the membership of each pixel. Each row of CENTERS
is a centroid and with that, IDX
tells you which row from CENTERS
you would need to reference that a pixel in your image got assigned to after the clustering.
If you want to find the "most popular colour", I'm assuming you mean the most frequently occurring. In that case, apply a mode
operation to your cluster membership vector, then use this to index into CENTERS
to get the most popular cluster:
idx_popular = mode(IDX);
popular_colour = CENTERS(idx_popular,:);
Minor Note
As kmeans
is a randomized algorithm, it is highly probable that your cluster centroids will be different at each iteration - whether they're different all together or the same but in a different order is subject to the algorithm.
I would suggest you run the kmeans
algorithm a few times to ensure that you do get the most popular colour with high probability. That can be done by specifying the Replicates
flag when running kmeans
:
num_repeats = 5; %// For example
[IDX,CENTERS] = kmeans(mat, N, 'Replicates', num_repeats);