%% Palette image
I = double(imread('minion.jpg'));
M = size(I, 1);
N = size(I, 2);
R = I(:, :, 1);
G = I(:, :, 2);
B = I(:, :, 3);
data = [3, M*N];
for i = 1 : M*N
data(1,i) = R(i);
data(2,i) = G(i);
data(3,i) = B(i);
end
rng(658)
rnd = randi([1, M*N], [1, 100]);
centroid = data(:, rnd);
%classification
D = zeros(100, M*N);
for iter = 1 : 10
for i = 1 : 100
for j = 1 : M*N
D(i, j) = sum( (centroid(:, i) - data(:, j)).^2 );
end
end
[~, Grp] = min(D);
for i = 1 : 100
centroid(:, i) = mean( data(:, Grp==i), 2 );
end
end
%Encoding
MAT = ones(1, 100);
for i = 1 : M*N
[~, X(i)] = min( sum( data(:, i)*MAT - centroid ).^2 );
end
%% Decoding
I2 = zeros(size(data));
for i = 1 : M*N
I2(:, i) = data(:, X(i));
end
Rp = I2(1, :);
Gp = I2(2, :);
Bp = I2(3, :);
R2 = reshape(Rp, [], 630);
G2 = reshape(Gp, [], 630);
B2 = reshape(Bp, [], 630);
I3(:, :, 1) = R2;
I3(:, :, 2) = G2;
I3(:, :, 3) = B2;
imshow(uint8(I))
figure;
imshow(uint8(I3))