num_clusters = 3;

a = imread('test_image.jpg');

num_rows = size(a,1);

num_cols = size(a,2);

num_dims = size(a,3);

a = im2double(a);

reshaped_image = reshape(a, num_rows*num_cols, num_dims);

[distance, label, tse] = kmeans1(reshaped_image, num_clusters);

mean_intensity = zeros(1, 3);

inter = zeros(1, 3);

for i = 1:num_clusters

    j = find(label==i);
    
    for k = 1:size(j, 1)
        inter(k,:) = reshaped_image(j(k), :);
    end
    
    color_table(i, 1) = mean(inter(:, 1));
    
    color_table(i, 2) = mean(inter(:, 2));
    
    color_table(i, 3) = mean(inter(:, 3));    
    
end

clustered_image = zeros(num_rows, num_cols, num_dims);

pixel_number = 1;

for j = 1:num_cols
    
    for i = 1:num_rows
        
        for k = 1:num_clusters
            
            clustered_image(i, j, :) = color_table(label(pixel_number), :);
            
        end
        
        pixel_number = pixel_number+1;
        
    end
    
end

imshow(clustered_image);
