分类:
2008-05-06 20:10:44
function [res,code]=huffman(image) % 输入参数图像必须是 灰度图 % 程序用 Huffman树 结构实现 data=double(image); [w,h]=size(data); hist=imhist(image); hist=hist.*1.0./(w*h); %%%%%%%%%%%%%%%%%%%% %% Huffman Tree %%%%%%%%%%%%%%%%%%%% num=length(hist); %newhist=[1/6,1/4,5/12,1/6]; %num=4; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% 初始化 for i=1:2*num-1 ht(i).lch=0; ht(i).rch=0; ht(i).pare=0; ht(i).weight=0; end for i=1:num ht(i).weight=hist(i); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% 建树 n=length(hist); for i=num+1:2*num-1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% 直接选择最小的两个比排序后选前两个更快 min=100; for j=1:i-1 if ht(j).weight min=ht(j).weight; end end min=100; for j=1:i-1 if ht(j).weight min=ht(j).weight; end end ht(s1).pare=i; ht(s2).pare=i; ht(i).lch=s1; ht(i).rch=s2; ht(i).weight=ht(s1).weight+ht(s2).weight; end %for i=1:2*num-1 %if ht(i).pare==0 % i %end %ht(i).pare %end %ht(end).weight %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% 编码 for i=1:num res{i}=blanks(260); cd=blanks(260); start=num; c=i; p=ht(c).pare; while(p>0) if(ht(p).lch==c) cd(start)='0'; else cd(start)='1'; end c=p; p=ht(c).pare; start=start-1; end %%% 反转字符串数组,去掉最后面的空串 cd=deblank(cd); res{i}=seqreverse(cd); res{i}=deblank(res{i}); res{i}=seqreverse(res{i}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% 下面为图像编码 %% 时间较长,与原图像大小有关 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %p=0; code=['Code Begin :'] for i=1:w for j=1:h %p=p+1 code=strcat(code,res{data(i,j)}); end end code=strcat(code,': The End!'); end |