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

压缩解压

开发平台:

Matlab

  1. function [zipped,info]=huffencode(vector)
  2. % if~isa(vector,'uint')
  3. %     error('input argument must be a uint8 vector');
  4. % end
  5. [m,n]=size(vector);
  6. vector=vector(:)';
  7. f=frequency(vector);
  8. symbols=find(f~=0);
  9. f=f(symbols);
  10. [f,sortindex]=sort(f);
  11. symbols=symbols(sortindex);
  12. len=length(symbols);
  13. symbols_index=num2cell(1:len);
  14. codeword_tmp=cell(len,1);
  15. while length(f)>1
  16.     index1=symbols_index{1};
  17.     index2=symbols_index{2};
  18.     codeword_tmp(index1)=addnode(codeword_tmp(index1),uint8(0));
  19.     codeword_tmp(index2)=addnode(codeword_tmp(index2),uint8(1));
  20.     f=[sum(f(1:2)) f(3:end)];
  21.     symbols_index=[{[index1,index2]} symbols_index(3:end)];
  22.     [f,sortindex]=sort(f);
  23.     symbols_index=symbols_index(sortindex);
  24. end
  25. codeword=cell(256,1);
  26. codeword(symbols)=codeword_tmp;
  27. len=0;
  28. for index=1:length(vector)
  29.     code=codeword{double(vector(index))+1};
  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;