% The input image data will be classified as 4 seperated clusters;
% Then all pixels in every cluster will be assigned a new value, Which is an average value
% of all pixels in a cluster ;

clear

data1 = imread('flowers.tif');
i = size(data1, 1);
j = size(data1, 2);
k = size(data1, 3);
data1 = reshape(data1,i*j, k);
data2 = double(data1);
[label,tse] = kmeans1(data2,4); % label() records the clusters to which every image pixel belongs

% The mean in every cluster is calculated, and is assigned to all pixels in that clutser.

for rgb = 1:3  % The datum in three R,G,B subspace are all processed seperately.
    
    count1 = [0 0 0 0]; % store the pixel numbers in every cluster, totaly four clusters.
    sum1 = [0 0 0 0]; % store the summation of all pixels in every cluster;
    mean1 = [0 0 0 0]; % store the average value of all pixels in every cluster;
    for k1=1:size(label)
        for k2=1:4
            if (label(k1) == k2)
                count1(k2) = count1(k2) +1; %count the pixel numbers in every cluster, totaly four clusters.
                sum1(k2) = sum1(k2) + data2(k1,rgb); % caculate the sum of all pixels in every cluster.
            end
        end
    end

    for k2=1:4
        mean1(k2) = sum1(k2)/count1(k2); % caculate the average value of all pixels in every cluster.
    
        fprintf(1,'%2d: ',count1(k2));
    end

    for k1=1:size(label) 
        for k2=1:4
            if (label(k1) == k2)
                data2(k1,rgb) = mean1(k2); % all pixels in every cluster are assigned a new value which is the mean of that cluster
            end
        end
    end
    
end

data2 = uint8(data2);
data2 = reshape(data2,i,j,3);

figure;
imshow(data2);



    
    
    
    
            
    
    

