function design()
% create a codebook
% sig--------image signal
% re_sig--------reform image signal--fit to VQ
% siz_word---the size of codeword
% siz_book---the size of codebook
% m_sig------the number of image matrix row
% n_sig------the number of image matrix column
figure(1);
%调入和显示原始图像
sig=imread('11.bmp');
%求出图像象素的行数和列数
[m_sig,n_sig]=size(sig);
%设置码字大小
siz_word=4;
%设置码书大小
siz_book=512;
if m_sig~=n_sig
error('signal is not fitable for quantization.');
end
if mod(m_sig,siz_word)~=0
error('signal is also not fitable for quantization.');
end
imshow(sig);
%将图像分割和变形
num=m_sig/siz_word;%32
ss=siz_word*siz_word;%64
nn=num*num;%1024
re_sig=[];%64,1024
%图像分块处理
for i=1:m_sig
for j=1:m_sig
f1=floor(i./siz_word);
m1=mod(i,siz_word);
if m1==0
m1=siz_word;
f1=f1-1;
end
f2=floor(j./siz_word);
m2=mod(j,siz_word);
if m2==0
m2=siz_word;
f2=f2-1;
end
re_sig(num*f1+f2+1,siz_word*(m1-1)+m2)=sig(i,j);
end
end
% 码书初始化
codebook=[];
for i=1:siz_book
r=floor(rand*nn);
codebook=[codebook;re_sig(r,:)];
end
% LBG 算法
sea=100;
while sea<=0.0001
d1=0.0;
for i=1:siz_book
VectorNumber(i)=0; % the number of codeword of every class is 0
end
for i=1:nn
CodeNumber(i)=1;
min=VectorDistance(siz_word,re_sig(i,:),codebook(1,:));
for j=2:siz_book
d=0.0;
for l=2:siz_word
d=d+(re_sig(i,l)-codebook(j,l))^2;
if d>=min
break;
end
end
if d<min
min=d;
CodeNumber(i)=j;
end
end
VectorNumber(CodeNumber(i))=VectorNumber(CodeNumber(i))+1;
d1=d1+min;
end
sea=(d0-d1)/d1;
if sea<=0.0001
break;
end
d0=d1;
for j=1:siz_book
if VectorNumber[j]~=0
dd=zeros(1,siz_word);
for l=1:nn
if CodeNumber(l)==j
for k=1:siz_word
dd(k)=dd(k)+re_sig(l,k);
end
end
end
for k=1:siz_word
codebook(j,k)=dd(k)/VectorNumber(j);
end
else
msgbox('select a random vector');
l=floor(rand*nn);
codebook(j,:)=re_sig(l,:);
end
end
end
save codebook4_512 codebook;
%计算矢量距离的子函数
function z=VectorDistance(siz_word, Vector1, Vector2)
for i=1:siz_word
z=z+(Vector1(i)-Vector2(i))^2;
end