%程序L7_2.m: 应用小波变换与向量量化做图像压缩%
%利用LGB训练一层小波变换后四个频带的码本%
function Wavelet_Vector_Comprssion()
%X=imread('j:\数字图像处理-活用Matlab程序\CH7\lena.bmp','bmp');
%[LL1,LH1,HL1,HH1]=dwtper2(X,'bior3.3');
%load lena
X=imread('E:\matlab1\LENA64.bmp','bmp');
figure(100);imshow(uint8(X));title('original image');
%利用正交小波函数对X进行多尺度分解
%[C,S]=wavedec2(double(X),N,Wavelet_Name)是使用指定的小波基‘Wavelet_Name’对图像X进行N层分解
Wavelet_Name='db1';
Wavelet_Scale=1;
[C,S]=wavedec2(double(X),Wavelet_Scale,Wavelet_Name);
%appcoef2用来提取二维信号小波分解的近似分量
LL1=appcoef2(C,S,Wavelet_Name,Wavelet_Scale);
%detcoef2用来提取二维信号小波分解的细节分量
%D=detcoef2(O,C,S,N),O指定细节分量的类型,
%当O=‘h’时,重构水平细节分量,当O=‘v’时,重构垂直细节分量,当O=‘d’时,重构细节细节分量
LH1=detcoef2('v',C,S,1);
HL1=detcoef2('h',C,S,1);
HH1=detcoef2('d',C,S,1);
%训练LL1频带码本,将码本大小设为128,维度为4 %
th=0.05;
nc=128;nd=4;
[cbLL1]=LBG(LL1,nc,nd,th); %LBG.m在L3.3节中
%训练LH1频带码本,将码本大小设为64,维度为4 %
nc=64;nd=4;
[cbLH1]=LBG(LH1,nc,nd,th);
%训练HL1频带码本,将码本大小设为64,维度为4 %
nc=64;nd=4;
[cbHL1]=LBG(HL1,nc,nd,th);
%训练HH1频带码本,将码本大小设为64,维度为16 %
nc=64;nd=16;
[cbHH1]=LBG(HH1,nc,nd,th);
%利用一层小波变换加上向量量化进行Lena图像压缩%
%输入一幅Lena图像%
X=imread('E:\matlab\LENA64.bmp','bmp');
%load lena
[M,N]=size(X);
%使用Matlab中Wavelet工具箱的周期性小波变换函数dwtper2.m%
%并使用双正交小波bior3.3进行一层小波变换%
%[LL1,LH1,HL1,HH1]=dwtper2(X,'bior3.3');
[C,S]=wavedec2(double(X),Wavelet_Scale,Wavelet_Name);
LL1=appcoef2(C,S,Wavelet_Name,Wavelet_Scale);
LH1=detcoef2('v',C,S,1);
HL1=detcoef2('h',C,S,1);
HH1=detcoef2('d',C,S,1);
wt_X(1:M/2,1:N/2)=LL1;
wt_X(1:M/2,N/2+1:N)=LH1;
wt_X(M/2+1:M,1:N/2)=HL1;
wt_X(M/2+1:M,N/2+1:N)=HH1;
%分别针对不同的频带进行向量量化,其中VQ.m置于L3.4节中%
[R_LL1,bitLL1]=VQ(LL1,cbLL1);
[R_LH1,bitLH1]=VQ(LH1,cbLH1);
[R_HL1,bitHL1]=VQ(HL1,cbHL1);
[R_HH1,bitHH1]=VQ(HH1,cbHH1);
wt_Y(1:M/2,1:N/2)=R_LL1;
wt_Y(1:M/2,N/2+1:N)=R_LH1;
wt_Y(M/2+1:M,1:N/2)=R_HL1;
wt_Y(M/2+1:M,N/2+1:N)=R_HH1;
%计算图像经过向量量化后的压缩率CR及失真PSNR%
totalbit=bitLL1+bitLH1+bitHL1+bitHH1; %花费的总位数
%Y=idwtper2(R_LL1,R_LH1,R_HL1,R_HH1,'bior3.3'); %反小波变换
C1= [R_LL1 R_HL1 R_LH1 R_HH1];
S1=S;
Y=waverec2(C1,S1,Wavelet_Name);
size(Y)%size(Y)=[512 512]
X=double(X);
Y=double(Y);
MSE=(sum(sum((X-Y).^2)))/(M*N)
PSNR=20*log10(255/sqrt(MSE))
CR=M*N*8/totalbit
figure(200);imshow(uint8(Y));title('compressed image');