Displaying kmean result with specific colors to specific clusters

落爺英雄遲暮 提交于 2019-12-25 02:55:23

问题


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 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.



来源:https://stackoverflow.com/questions/29889707/displaying-kmean-result-with-specific-colors-to-specific-clusters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!