%实验目的: 学习JPEG压缩编码
%实验内容:
%一.实现基本JPEG的压缩和编码分三个步骤:
%1.首先通过DCT变换去除数据冗余;
%2.使用量化表对DCT系数进行量化;
%3.对量化后的系数进行Huffman编码。
%具体源程序由主程序及两个子程序(DCT量化、Huffman编码)组成:
%1.主程序
I=imread('1.jpg');
yiq=rgb2ntsc(I);
my=[16 11 10 16 24 40 51 61;12 12 14 19 26 58 60 55;
14 13 16 24 40 57 69 56;14 17 22 29 51 87 80 62;
18 22 37 56 68 109 103 77;24 35 55 64 81 104 113 92;
49 64 78 87 103 121 120 101;72 92 95 98 112 100 103 99];
miq=[17 18 24 47 99 99 99 99;18 21 26 66 99 99 99 99;
24 26 56 99 99 99 99 99;47 66 99 99 99 99 99 99;
99 99 99 99 99 99 99 99;99 99 99 99 99 99 99 99;
99 99 99 99 99 99 99 99;99 99 99 99 99 99 99 99];
I1=yiq(:,:,1);
I2=yiq(:,:,2);
[m n]=size(I1);
t1=8;ti1=1;
while(t1<m)
t1=t1+8;ti1=ti1+1;
end
t2=8;ti2=1;
while(t2<n)
t2=t2+8;ti2=ti2+1;
end
times=0;
for k=0:ti1-2
for j=0:ti2-2
dct8x8(I1(k*8+1:k*8+8,j*8+1:j*8+8),my,times*64+1);
dct8x8(I2(k*8+1:k*8+8,j*8+1:j*8+8),miq,times*64+1);
times=times+1;
end
block(I2(k*8+1:k*8+8,j*8+1:t2),[8 8], 'dctmtx(8)');
end
for j=0:ti2-2
dct8x8(I1(k*8+1:t1,j*8+1:j*8+8),times*64+1);
times=times+1;
end
dct8x8(I1(k*8+1:t1,j*8+1:t2),times*64+1);
%2.function 定义DCT量化子程序
dct8x8(I,m,s)
T=inline('dctmtx(8)');
y=blkproc(I,[8 8],T);
y=round(y./m);
p=1;te=1;
while(p<=64)
for q=1:te
y1(s+p)=y(te-q+1,q);p=p+1;
end
for q=te:-1:1
y1(s+p)=y(te-q+1,q);p=p+1;
end
end
f=haffman(y1);
c(s:s+64,1)=f(:,1);c(s:s+64,2)=f(:,2);c(s:s+64,3)=f(:,3)
%3.function 定义Huffman编码子程序
c=haffman(I)
[m,n]=size(I);
p1=1;s=m*n;
for k=1:m
for h=1:n
f=0;
for b=1:p1-1
if(c(b,1)==I(k,h)) f=1;break;end
end
if(f==0) c(p1,1)=I(k,h);p1=p1+1;end
end
end
for g=1:p1-1
p(g)=0;c(g,2)=0;
for k=1:m
for h=1:n
if(c(g,1)==I(k,h)) p(g)=p(g)+1;end
end
end
p(g)=p(g)/s;
end
pn=0;po=1;
while(1)
if(pn>=1.0) break;
else
[pm p2]=min(p(1:p1-1));p(p2)=1.1;
[pm2,p3]=min(p(1:p1-1));p(p3)=1.1;
pn=pm+pm2;p(p1)=pn;
tree(po,1)=p2;tree(po,2)=p3;
po=po+1;p1=p1+1;
end
end
for k=1:po-1
tt=k;m1=1;
if(or(tree(k,1)<9,tree(k,2)<9))
if(tree(k,1)<9)
c(tree(k,1),2)=c(tree(k,1),2)+m1;
m2=1;
while(tt<po-1)
m1=m1*2;
for h=tt:po-1
if(tree(h,1)==tt+g)
c(tree(k,1),2)=c(tree(k,1),2)+m1;
m2=m2+1;tt=h;break;
elseif(tree(h,2)==tt+g)
m2=m2+1;tt=h;break;
end
end
end
c(tree(k,1),3)=m2;
end
tt=k;m1=1;
if(tree(k,2)<9)
m2=1;
while(tt<po-1)
m1=m1*2;
for h=tt:po-1
if(tree(h,1)==tt+g)
c(tree(k,2),2)=c(tree(k,2),2)+m1;
m2=m2+1;tt=h;break;
elseif(tree(l,2)==tt+g)
m2=m2+1,tt=h;break;
end
end
end
c(tree(k,2),3)=m2;
end
end
end
- 1
- 2
- 3
前往页