Finding locations of images clusters centroids using imsegkmeans

7 views (last 30 days)
I use imsegkmeans to cluster images and I need to know the centroid of each cluster. So I write this line:
[Labels,centers] = imsegkmeans(div_img,4);
My image is an RGB 250-250 pixels and I am clustering it into 4 clusters, so I got a 4-3 matrix which matches the explaination in the documentation.
centers =
4×3 uint8 matrix
25 25 29
15 9 13
64 58 54
34 13 14
My understading is that the first row [25,25,29] contains the centroid for the first cluster and it has 3 values for R, G and B channels. However, I don't understand how this is a location? I need indices for row and column for the centroid of each cluster

Answers (1)

Shubham Rawat
Shubham Rawat on 2 Feb 2021
Hi Hassan,
In the imsegkmeans function you will have centroid values of the colors not the positions.
I have created a custom code which will generate Centroid positions of each cluster with the help of Label matrix:
% input Image(RGB) and number of clusters k
% output clusteIndices k*2 size
function clusterIndices = clusterIndices(I,k)
% L is the Label matrix here
[L,~] = imsegkmeans(I,k);
% initialization
clusterIndices = zeros(k,2);
sumx = zeros(k,2);
sumy = zeros(k,2);
num = zeros(k,1);
for c = 1:k
for i = 1:size(L,1)
for j = 1:size(L,2)
if L(i,j) == c
sumx(c) = sumx(c)+i;
sumy(c) = sumy(c)+j;
num(c) = num(c)+1;
clusterIndices(c,1) = sumx(c)/num(c);
clusterIndices(c,2) = sumy(c)/num(c);
Hope this Helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!