%Program to segment an image using k-means clustering
%                                       jogen shah
%The program was run for image: image.jpg with  two different 
%sizes of clusters. One with 3 and 5
%3-clusters and 5-clusters are the results

%No. of clusters we want to segment the image in.
%NCLUS is variable for no. ocuster numbers is 3 here
NCLUS = 5

im = imread('image.jpg');       %Read image
figure; imshow(im);

[x, y, z] = size(im);           %Find the size of image

reim = reshape(im, x*y, z);     %Change to 2d...basically all the rows are 
                                %appended and made to a single column for 
                                %each RGB plane
im = double(im);                %Change original image to double
reim = double(reim);            %Change reshaped image to double

[distance,label,tse] = kmeans1(reim, NCLUS);
                                %Call kmeans1 algorithm to cluster the reshaped image
orig = reshape(label, x, y);    %Convert back to 3D

[x, y]=size(orig);              %find size

for i = 1:NCLUS                 %Initialise the 'mean' in each of the cluster
    for j = 1:z                 %in each of the 3 RGB planes = 0
        cmean(i,j) = 0;
    end
    cluster(i) = 0;             %Count for no. of pixels in a cluster
end

%calculate the mean value for the color of each region
for i = 1:x
    for j = 1:y
        index = orig(i,j);         %Read the cluster no. for each pixel
        for z = 1:3
	        cmean(index,z) = cmean(index,z)+im(i,j,z);
	    end                        %Update mean color of the cluster to which the pixel belongs
        cluster(index) = cluster(index) + 1;
    end                            %Increment count for no. of pixels in the cluster
end

for i = 1:NCLUS
    for j = 1:z
       cmean(i,j) = cmean(i,j)/cluster(i);
    end                            %Calculate mean by dividing the no. of pixels
end


for i = 1:x
    for j = 1:y
        index = orig(i, j);        
	    for z = 1:3                %Give the mean color to each pixel
	        result(i, j, z) = cmean(index,z);
    	end
    end
end

figure; imshow(uint8(result));      %Show output of clustering