clear;
clf;
close all;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Image compression by K-Means
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MATLAB=1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
K=8; %%% K-means Components K=4, 8, 12, 16, 20
CYCLE=20; %%% Repeated Time
REDUCE=3; %%% Reduce Image
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A=imread('suzukake.jpg');
[TATE,YOKO,IRO]=size(A);
TT=floor(TATE/REDUCE);
YY=floor(YOKO/REDUCE);
EPSILON=0.0001; %%% If 0/0, choose average vector
n=TT*YY; %%% Training samples
fprintf('pixels reduced: (%g,%g)-->(%g,%g)\n',TATE,YOKO,TT,YY);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
B=zeros(TT,YY,IRO);
for i=1:1:TT
for j=1:1:YY
B(i,j,:)=double(A(REDUCE*i,REDUCE*j,:))/256;
end
end
x=zeros(IRO,TT*YY);
for i=1:1:TT
for j=1:1:YY
x(:,YY*(i-1)+j)=B(i,j,:);
end
end
%%%%%%%%%%%%%%%% K Means %%%%%%%%%%%
recordy=zeros(CYCLE,IRO,K);
ID1=ones(1,K);
ID2=ones(n,1);
%%%%%%%%%%%%%%%%%%%%%% Learning Machine and Record %%%%%%%%%%
y=mean(x,2)*ID1+0.3*randn(IRO,K);
recordy(1,:,:)=y;
%%%%%%%%%%%%%%%%%%%%%% Learning Begin %%%%%%%%%%%%%%%
for j=2:1:CYCLE
cc=zeros(n,K);
Err=0;
for i=1:1:n
yy=y-x(:,i)*ID1;
dist=sum(yy.*yy,1);
[minval, k]=min(dist);
Err=Err+dot(x(:,i)-y(:,k),x(:,i)-y(:,k));
cc(i,k)=1;
end
fprintf('Err[%2g]=%.2f\n',j-1,Err);
d=(cc+EPSILON*ID2*ID1)./(ID2*sum(cc)+EPSILON*n);
y=x*d;
recordy(j,:,:)=y;
end
%%%%%%%%%%%%%%%%%%%%%% Learning End %%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Draw Image %%%%%%%%%%%%%%%%%%%
subplot(2,2,1);
map = gray(256);
colormap(map);
if(MATLAB==1)
imshow(B);
else
image(B);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Region judge
for i=1:1:n
yy=y-x(:,i)*ID1;
dist=sum(yy.*yy,1);
[minval, k]=min(dist);
ii=floor((i-1)/YY)+1;
jj=mod((i-1),YY)+1;
B(ii,jj,:)=y(:,k);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
subplot(2,2,2);
map = gray(256);
colormap(map);
if(MATLAB==1)
imshow(B);
else
image(B);
end
figure(1);
%%%%%%%%%%%%%%%%%%%%%% Patition Numbers %%%%%%%%%%%%%%%%
fprintf('Partition Numbers: ')
for k=1:1:K
fprintf('%g ',sum(cc(:,k)));
end
fprintf('\n');
subplot(2,2,3);
bar(sum(cc,1));
title('Partition Numbers');
%%%%%%%%%%%%%%%%%%%%%% Draw graph %%%%%%%%%%%%%%%%%%%
subplot(2,2,3);
h1=plot3(x(1,:),x(2,:),x(3,:),'b.'); hold on;
title('RED, GREEN, BLUE');
subplot(2,2,4);
plot3(y(1,:),y(2,:),y(3,:),'rs'); hold on;
title('RED, GREEN, BLUE');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Rate=(TT*YY*log2(K)+K*log2(3))/(TT*YY*3*8);
fprintf('Error=%f, Compression Rate=%f\n',Err,Rate);