clear all;
imgdir=dir('*.jpg');

for i=1:length(imgdir)
name=imgdir(i).name;

%specifying the number of clusters
n_clus=4;

%for n_clus=2:6
swcl=sprintf('%2d', n_clus);
name='car.jpg';
g=imread(name);
%mask=roipoly(g);
[M,N,K]=size(g);
figure, imshow(g);

%represent the image in 3d color space
I=double(reshape(g,M * N,3));

%normalazing the given data
[meanv,stdv,datanew]=normalize(I,[],[]);

%using k-means clusering with mahanalobis distance 
[distance,label,center]=kmeans2(datanew,n_clus);
segimg=zeros(M*N,3);

for i=1:n_clus
index=find(label==i);
    meanc=mean(I(index,:));
    segimg(index,1)=meanc(1);
    segimg(index,2)=meanc(2);
    segimg(index,3)=meanc(3);
end;
newimg=reshape(segimg,M,N,3);
newimg=newimg/256;

%show segmented image
figure,imshow(newimg);
title(['segmented with ' swcl ' clusters']);
end
%end;