1 function [mu,mask]=kmeans(ima,k)
\r
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\r
4 % kmeans image segmentation
\r
7 % ima: grey color image
\r
8 % k: Number of classes
\r
10 % mu: vector of class means
\r
11 % mask: clasification image mask
\r
13 % Author: Jose Vicente Manjon Herrera
\r
14 % Email: jmanjon@fis.upv.es
\r
17 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\r
21 copy=ima; % make a copy
\r
22 ima=ima(:); % vectorize ima
\r
23 mi=min(ima); % deal with negative
\r
24 ima=ima-mi+1; % and zero values
\r
28 % create image histogram
\r
35 if(ima(i)>0) h(ima(i))=h(ima(i))+1;end;
\r
40 % initiate centroids
\r
49 % current classification
\r
57 %recalculation of means
\r
61 mu(i)=sum(a.*h(a))/sum(h(a));
\r
64 if(mu==oldmu) break;end;
\r
73 c=abs(copy(i,j)-mu);
\r
79 mu=mu+mi-1; % recover real range
\r