Skip to content

Instantly share code, notes, and snippets.

@nelsondspy
Last active December 1, 2018 21:32
Show Gist options
  • Save nelsondspy/76540d7d98415fa9f6be27c387fdafec to your computer and use it in GitHub Desktop.
Save nelsondspy/76540d7d98415fa9f6be27c387fdafec to your computer and use it in GitHub Desktop.
clear all; clc;
% Carga de imagen y parametros generales
IMAGEN='robot.png'
A = double(imread(IMAGEN));
max_iterations = 5;
k = 5;
%%%----Calculo de kmean
f_dim = size(A, 1);
c_dim = size(A, 2);
% Initialize means to randomly-selected colors in the original photo.
means = zeros(k, 3);
rand_x = ceil(f_dim *rand(k, 1));
rand_y = ceil(c_dim *rand(k, 1));
for i = 1:k
means(i,:) = A(rand_x(i), rand_y(i), :);
end
% array that will store the nearest neighbor for every
% pixel in the image
nearest_mean = zeros(max(f_dim,c_dim));
% Run k-means
for itr = 1:max_iterations
% Stores the means to be calculated in this iteration
new_means = zeros(size(means));
% num_assigned(n) stores the number of pixels clustered
% around the nth mean
num_assigned = zeros(k, 1);
% For every pixel in the image, calculate the nearest mean. Then
% Update the means.
for i = 1:f_dim
for j = 1:c_dim
% Calculate the nearest mean for the pixels in the image
r = A(i,j,1); g = A(i,j,2); b = A(i,j,3);
diff = ones(k,1)*[r, g, b] - means;
distance = sum(diff.^2, 2);
[val ind] = min(distance);
nearest_mean(i,j) = ind;
% Add this pixel to the rgb values of its nearest mean
new_means(ind, 1) = new_means(ind, 1) + r;
new_means(ind, 2) = new_means(ind, 2) + g;
new_means(ind, 3) = new_means(ind, 3) + b;
num_assigned(ind) = num_assigned(ind) + 1;
end
end
% Calculate new means
for i = 1:k
% Only update the mean if there are pixels assigned to it
if (num_assigned(i) > 0)
new_means(i,:) = new_means(i,:) ./ num_assigned(i);
end
end
% Convergence test. Display by how much the means values are changing
d = sum(sqrt(sum((new_means - means).^2, 2)))
if d < 1e-5
break
end
means = new_means;
end
disp(itr)
means = round(means);
%%-----Selecciona y Aplica los colores mas cercanos a los centroides
for i = 1:f_dim
for j = 1:c_dim
r = A(i,j,1); g = A(i,j,2); b = A(i,j,3);
diff = ones(k,1)*[r, g, b] - means;
distance = sum(diff.^2, 2);
[val ind] = min(distance);
A(i,j,:) = means(ind,:);
end
end
imshow(uint8(round(A)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment