霍夫曼图像压缩编码源程序

  • 格式:docx
  • 大小:14.10 KB
  • 文档页数:4

下载文档原格式

  / 12
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

clear

X=imread('lena512.bmp');

data=uint8(X);

[zipped,info]=huffencode(data); %调用Huffman编码程序进行压缩

unzipped=huffdecode(zipped,info,data);

%调用Huffman编码程序进行解码

%显示原始图像和经编码后的图像,显示压缩比,并计算均方根误差得erms=0,表示是Huffman是无失真编码

subplot(121);imshow(data);

subplot(122);imshow(unzipped);

%erms=compare(data(:),unzipped(:))

cr=info.ratio

whos data unzipped zipped

function [zipped, info] = huffencode(vector)

% 输入和输出都是uint8 格式

% info 返回解码需要的结构信息

% info.pad 是添加的比特数

% info.huffcodes 是Huffman 码字

% info.rows 是原始图像行数

% info.cols 是原始图像列数

% info.length 是原始图像数据长度

% info.maxcodelen 是最大码长

if ~isa(vector, 'uint8')

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

end

[m, n] = size(vector);

vector = vector(:)';

f = frequency(vector); %计算各符号出现的概率

symbols = find(f~=0);

f = f(symbols);

[f, sortindex] = sort(f); %将符号按照出现的概率大小排列

symbols = symbols(sortindex);

len = length(symbols);

symbols_index = num2cell(1:len);

codeword_tmp = cell(len, 1);

% 生成Huffman 树,得到码字编码表

while length(f)>1

index1 = symbols_index{1};

index2 = symbols_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)];

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

[f, sortindex] = sort(f);

symbols_index = symbols_index(sortindex);

end

codeword = cell(256, 1);

codeword(symbols) = codeword_tmp;

len = 0;

for index = 1:length(vector) %得到整个图像所有比特数len = len + length(codeword{double(vector(index))+1}); end

string = repmat(uint8(0), 1, len);

pointer = 1;

for index = 1:length(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);

if pad > 0

string = [string uint8(zeros(1, pad))];

end

codeword = codeword(symbols);

codelen = zeros(size(codeword));

weights = 2.^(0:23);

maxcodelen = 0;

for index = 1:length(codeword)

len = length(codeword{index});

if len > maxcodelen;

maxcodelen = len;

end

if len > 0

code = sum(weights(codeword{index} == 1));

code = bitset(code, len + 1);

codeword{index} = code;

codelen(index) = len;

end

end

codeword = [codeword{:}];

%计算压缩的向量

cols = length(string)/8;