close all;
clear all;

%load input image
im_original = imread('im1.bmp');

% show original image
figure;imshow(im_original);

im_processed = im_original;
im_original = double(im_original);


% get input image dimensions
sz = size(im_original);

% change image size to [], 3
im = reshape(im_original, [], 3);

% change to double
im = double(im);

%define cluster group
cluster_group = 4;

% calculate k-mean 
[distance,label,tse] = kmeans1(im, cluster_group);

label
% switch back to original image size
im_kmean = reshape(label, sz(1), sz(2));


cluster_mean = [0,0,0;0,0,0;0,0,0;0,0,0];
cluster_num = [0,0,0,0];

%get total values for each cluster group 
for i = 1:sz(1)
    for j = 1:sz(2)
        cluster_group_num = im_kmean(i,j);
        for k = 1:3
	        cluster_mean(cluster_group_num,k) = cluster_mean(cluster_group_num,k)+im_original(i,j,k);
	    end
        cluster_num(cluster_group_num) = cluster_num(cluster_group_num) + 1;
    end
end

% calculate mean values for each cluster group
for i = 1:cluster_group
    for k = 1:3
       cluster_mean(i,k) = cluster_mean(i,k)/cluster_num(i);
    end
end

% remap the cluster mean value to original image
for i = 1:sz(1)
    for j = 1:sz(2)
        cluster_group_num = im_kmean(i, j);
	    for k = 1:3
	        im_processed(i, j, k) = cluster_mean(cluster_group_num,k);
    	end
    end
end

% show processed image
figure; imshow(im_processed);
