資源描述:
《Huffman編碼(哈夫曼編碼)的Matlab實(shí)現(xiàn).doc》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
1、clearallfprintf('Readingdata...')data=imread('cameraman.tif');data=uint8(data);%讀入數(shù)據(jù),并將數(shù)據(jù)限制為uint8fprintf('Done!')%編碼壓縮fprintf('compressingdata...');[zipped,info]=norm2huff(data);fprintf('Done!')%解壓縮fprintf('compressingdata...');unzipped=huff2norm(zipped,info);fprintf(
2、'Done!')%測(cè)試是否無(wú)失真isOK=isequal(data(:),unzipped(:))%顯示壓縮效果whosdatazippedunzippedfunction[zipped,info]=norm2huff(vector)if~isa(vector,'uint8'),error('inputargumentmustbeauint8vector')endvector=vector(:)';%將輸入向量轉(zhuǎn)換為行向量f=frequency(vector);%計(jì)算個(gè)元素出現(xiàn)的概率simbols=find(f~=0);f=f(sim
3、bols);%將元素按出現(xiàn)的概率排列[f,sortindex]=sot(f);simbols=simbols(sortindex);%產(chǎn)生碼字generatethecodewordasthe52bitsofadoublelen=length(simbols);simbols_index=num2cell(1:len);codeword_tmp=cell(len,1);whilelength(f)>1,index1=simbols_index{1};index2=simbols_index{2};codeword_tmp(index1)=a
4、ddnode(codeword_tmp(index1),uint8(0));codeword_tmp(index2)=addnode(codeword_tmp(index2),uint8(1));f=[sum(f(1:2))f(3:end)];simbols_index=[{[index1index2]}simbols_index(3:end)];%將數(shù)據(jù)重新排列,是兩個(gè)節(jié)點(diǎn)的頻率盡量與前一個(gè)節(jié)點(diǎn)的頻率想當(dāng)resortdatainordertohavetwonodeswithlowerfrequencyasfirstto[f,sortin
5、dex]=sort(f);simbols_index=simbols_index(sortindex);end%對(duì)應(yīng)相應(yīng)的元素與碼字codeword=cell(256:1);codeword(simbols)=codeword_tmp;%計(jì)算總的字符串長(zhǎng)度len=0;forindex=1:length(vector),len=len+length(codeword{double(vector(index))+1});end%產(chǎn)生01序列string=repmat(uint8(0),1,len);pointer=1;forindex=1:l
6、ength(vector),code=codeword{double(vector(index))+1};len=length(code);string(pointer+(0:len-1))=code;pointer=pointer+len;end%如果需要,加零len=length(string);pad=8-mod(len,8);ifpad>0,string=[stringuint8(zeros(1,pad))];end%保存實(shí)際有用的碼字codeword=codeword(simbols);codelen=zeros(size(co
7、deword));weights=2.^(0:23);maxcodelen=0;forindex1:length(codeword),len=length(codeword{index});iflen>maxcodelen,maxcodelen=len;endiflen>0,code=sum(weights(codeword{index}==1));code=bitset(code,len+1);codeword{index}=code;codelen(index)=len;endendcodeword=[codeword{:}]%計(jì)算壓
8、縮后的向量cols=length(string)/8;string=reshape(string,8,cols);weights=2.^(0:7);zipped=uint8(weights*d