% This function is a segmentation function using k-mean
% It takes two parameters, one is the name of the image file, the other is how 
% many clusters it will be segmented into.

function segmentation(name,number)

a = imread(name);

[i, j, k] = size(a);
% Reshape the 3-dimension image matrix into a two dimension matrix.
b = reshape(a, i*j, 3);

cc = double(a);
c = double(b);

% Using k-mean functions to segment the picture
% Since it takes a while to compute the distance value in k-means1 function and it is 
% never used in this program, you can just comment out the last several lines in k-means1
% function without affecting the execution of my segmentation function.
[distance,label,tse] = kmeans1(c,number);

% Reshape the label matrix which is obtained from k-mean function into a 
% 3-dimension matrix again
d = reshape(label, i, j);

[i, j]=size(d);

% initialize
for r=1:number
    c_r(r,1) = 0;
    c_g(r,1) = 0;
    c_b(r,1) = 0;
    cluster(r,1) = 0;
end

% To compute the mean value of Red, Green and Blue value for each cluster
for r=1:i
    for t=1:j
        temp = d(r,t);
        c_r(temp,1) = c_r(temp,1)+cc(r,t,1);
        c_g(temp,1) = c_g(temp,1)+cc(r,t,2);
        c_b(temp,1) = c_b(temp,1)+cc(r,t,3);
        cluster(temp,1) = cluster(temp,1) + 1;
    end
end

for r=1:number
       c_r(r,1) = c_r(r,1)/cluster(r,1);
       c_g(r,1) = c_g(r,1)/cluster(r,1);
       c_b(r,1) = c_b(r,1)/cluster(r,1);
end

% Construct the result picture according to the label matrix and according RGB value
for r= 1:i
    for t = 1:j
        temp = d(r, t);
        result(r, t, 1) = c_r(temp,1);
        result(r, t, 2) = c_g(temp,1);
        result(r, t, 3) = c_b(temp,1);
    end
end

% Display the picture
figure; imshow(uint8(result));