图像K-means在matlab中聚类

时间:2014-05-31 18:31:32

标签: matlab image-processing cluster-analysis

我有一个用于K-means聚类的代码,用于MATLAB中的图像分割。如何用(mu和掩码值)显示图像?

function [mu,mask]=kmeans(ima,k)
% check image 
ima=imread('Robat.jpg');
ima=double(ima); 
copy=ima;         % make a copy 
ima=ima(:);       % vectorize ima (colunm)
mi=min(ima);      % deal with negative  
ima=ima-mi+1;     % and zero values  (sefr va manfi ro az beyn mibare)
k=6;

s=length(ima); 

% create image histogram 

m=max(ima)+1; 
h=zeros(1,m); 
hc=zeros(1,m); 

for i=1:s 
  if(ima(i)>0) h(ima(i))=h(ima(i))+1;end; 
end 
ind=find(h); 
hl=length(ind); 

% initiate centroids 

mu=(1:k)*m/(k+1); 

% start process 

while(true) 

  oldmu=mu; 
  % current classification   

  for i=1:hl 
      c=abs(ind(i)-mu); 
      cc=find(c==min(c)); 
      hc(ind(i))=cc(1); 
  end 

  %recalculation of means   

  for i=1:k,  
      a=find(hc==i); 
      mu(i)=sum(a.*h(a))/sum(h(a)); 
  end 

  if(mu==oldmu) break;end; 

end 

% calculate mask 
s=size(copy); 
mask=zeros(s); 
for i=1:s(1), 
for j=1:s(2), 
  c=abs(copy(i,j)-mu); 
  a=find(c==min(c));   
  mask(i,j)=a(1); 
end 
end 

mu=mu+mi-1;   % recover real range

我的图片是彩色图片,我想将此细分代码应用于它!

0 个答案:

没有答案