%         Program to implement k-means clustering algorithm   
%         Novemeber, 2003
%         Karthika Akkinepally

I=imread('test.jpg'); % read Input image
I=im2double(I);
[r,c,d]=size(I); % store the dimensions of the image

I1=reshape(I,r*c,d); % vectorize the image

nclus=3; % no. of clusters

[distance,label,tse]=kmeans1(I1,nclus); % calling kmeans function
I2=reshape(label,r,c);
% variables to store sum and no. of elements in each cluster
sum1=zeros(3,3);
c1=zeros(3,1);

for i=1:r
    for j=1:c
        for k=1:nclus
            if(I2(i,j)==k)
               c1(k,1)=c1(k,1)+1;
                sum1(I2(i,j),k)=sum1(I2(i,j),k)+I1(i*j,k);
            end;
        end;
    end;
end;
% calculating the mean of each cluster
for k=1:nclus
    mean1(k,:)=sum1(k,:)/c1(k,1);
end;

final_image=zeros(r,c,d);
% output image
for i=1:r
    for j=1:c
        temp=I2(i,j);
        for k=1:d
            final_image(i,j,:)=mean1(temp,:);
        end;
    end;
end;

figure, imshow(final_image);