huffencode.m
上传用户:xmsdbyfz
上传日期:2022-06-22
资源大小:2k
文件大小:2k
源码类别:

压缩解压

开发平台:

Matlab

  1. %huffencode函数对输入矩阵vector进行Huffman编码,返回编码后的向量(压缩后数据)及相关信息
  2. function [zipped,info]=huffencode(vector)
  3. if~isa(vector,'uint8')
  4.     eror('input argument must be a uint8 vector');
  5. end
  6. [m,n]=size(vector);
  7. vector=vector(:)';
  8. f=frequency(vector);
  9. symbols=find(f~=0);
  10. f=f(symbols);
  11. [f,sortindex]=sort(f);
  12. symbols=symbols(sortindex);
  13. len=length(symbols);
  14. symbols_index=num2cell(1: len);
  15. codeword_tmp=cell(len,1);
  16. while length(f)>1
  17.     index1=symbols_index{1};
  18.     index2=symbols_index{2};
  19.     codeword_tem(index1)=addnode(codeword_tem(index1),uint8(0));
  20.     codeword_tem(index2)=addnode(codeword_tem(index2),uint8(1));
  21.     f=[sum(f(1: 2))f(3: end)];
  22.     symbols_index=[{[index1,index2]} symbols_index(3: end)];
  23.     [f,sortindex]=sort(f);
  24.     symbols_index=symbols_index(sortindex);
  25. end
  26. codeword=cell(256,1);
  27. codeword(symbols)=codeword_tmp;
  28. len=0;
  29. for index=1:length(vector)
  30.     len=len+length(codeword{double(vector(index))+1});
  31. end
  32. string=repmat(uint8(0),1,len);
  33. pointer=1;
  34. for index=1:length(vector)
  35.     code=codeword{double(vector(index))+1};
  36.     len=length(code);
  37.     string(pointer+(0:len-1))=code;
  38.     pointer=pointer+len;
  39. end
  40. len=length(string);
  41. pad=8-mod(len,8);
  42. if pad>0
  43.     string=[string uint8(zeros(1,pad))];
  44. end
  45. codeword=codeword(symbols);
  46. codelen=zeros(size(codeword));
  47. weights=2.^(0:23);
  48. maxcodelen=0;
  49. for index=1:length(codeword)
  50.     len=length(codeword{index});
  51.     if len>maxcodelen
  52.         maxcodelen=len;
  53.     end
  54.     if len>0
  55.         code=sum(weights(codeword{index}==1));
  56.         code=bitset(code,len+1);
  57.         codeword{index}=code;
  58.         codelen(index)=len;
  59.     end
  60. end
  61. codeword=[codeword{:}];
  62. cols=length(string)/8;
  63. string=reshape(string,8,cols);
  64. weights=2.^(0:7);
  65. zipped=uint8(weights*double(string));
  66. huffcodes=sparse(1,1);
  67. for index=1:nnz(codeword)
  68.     huffcodes(codeword(index),1)=symbols(index);
  69. end
  70. info.pad=pad;
  71. info.huffcodes=huffcodes;
  72. info.ratio=cols./length(vector);
  73. info.length=length(vector);
  74. info.maxcodelen=maxcodelen;
  75. info.rows=m;
  76. info.cols=n;