0
votes

I applied k-mean clustering on a preprocessed image using the following matlab code

%B - input image
C=rgb2gray(B);
[idx centroids]=kmeans(double(C(:)),4);
imseg = zeros(size(C,1),size(C,2));
for i=1:max(idx)
     imseg(idx==i)=i;
end
i=mat2gray(imseg);
% i - output image

Every time I display the output, color assigned to the output images changes. How can I give a specific color to cluster1, cluster2, cluster3 and cluster4.

1
you can do it in the line you display the output, unfortunately you havent added it to the code so we cant help...Ander Biguri

1 Answers

3
votes

You can use a colormap. Let R1, B1 and G1 be the RGB values you want to dispaly the first cluster in (values in range [0..1]), and R2 be the red channel value for the second cluster and so on... Then your color map is:

cmp = [R1 G1 B1;
       ...
       R4 G4 B4];

Now,

[idx centroids] = kmeans(double(C(:)),4);
imseg = reshape( idx, size(C) ); %// reshape
figure; imagesc( imseg );colormap( cmp ); %// that's it!

PS,
It is best not to use i as a variable name in Matlab.