哈夫曼编码的matlab实现,Huffman编码(哈夫曼编码)的Matlab实现

clear all

fprintf('Reading data...')

data=imread('cameraman.tif');

data=uint8(data);%读入数据,并将数据限制为uint8

fprintf('Done!\n')

%编码压缩

fprintf('compressing data...');

[zipped,info]=norm2huff(data);

fprintf('Done!\n')

%解压缩

fprintf('compressing data...');

unzipped=huff2norm(zipped,info);

fprintf('Done!\n')

%测试是否无失真

isOK=isequal(data(:),unzipped(:))

%显示压缩效果

whos data zipped unzipped

function [zipped,info]=norm2huff(vector)

if~isa(vector,'uint8'),

error('input argument must be a uint8 vector')

end

vector=vector(:)';

%将输入向量转换为行向量

f=frequency(vector);

%计算个元素出现的概率

simbols=find(f~=0);

f=f(simbols);%将元素按出现的概率排列

[f,sortindex]=sot(f);

simbols=simbols(sortindex);

%产生码字 generate the codeword as the 52 bits of a double

len=length(simbols);

simbols_index=num2cell(1:len);

codeword_tmp=cell(len,1);

while length(f)>1,

index1=simbols_index{1};

index2=simbols_index{2};

codeword_tmp(index1)=addnode(codeword_tmp(index1),uint8(0)); codeword_tmp(index2)=addnode(codeword_tmp(index2),uint8(1)); f=[sum(f(1:2)) f(3:end)];

simbols_index=[{[index1 index2]} simbols_index(3:end)];

%将数据重新排列,是两个节点的频率尽量与前一个节点的频率想当

resort data in order to have two nodes with lower frequency as first to

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值