
%cluster numbers is 3 here
NUM = 3
%load image
A = imread('test.jpg');
[m, n, k] = size(A);
%change to 2d
B = reshape(A, m*n, 3);

C = double(A);
D = double(B);

[distance,label,tse] = kmeans1(D, NUM);

E = reshape(label, m, n);

[m, n]=size(E);

for i = 1:NUM
    for k = 1:3
        cmean(i,k) = 0;
    end
    cluster(i) = 0;
end

%calculate the mean value for the color of each region
for i = 1:m
    for j = 1:n
        index = E(i,j);
        for k = 1:3
	        cmean(index,k) = cmean(index,k)+C(i,j,k);
	    end
        cluster(index) = cluster(index) + 1;
    end
end

for i = 1:NUM
    for k = 1:3
       cmean(i,k) = cmean(i,k)/cluster(i);
    end
end


for i = 1:m
    for j = 1:n
        index = E(i, j);
	    for k = 1:3
	        result(i, j, k) = cmean(index,k);
    	end
    end
end


figure; imshow(uint8(result));