我正在尝试使用MATLAB中的Huffman编码压缩灰度图像,并尝试了以下代码。我已经使用了一个大小为512x512的灰度图像,格式为
tif
。我的问题是,压缩后的图像大小(压缩码字的长度)比未压缩的图像还要大。压缩比小于1。clc;
clear all;
A1 = imread('fig1.tif');
[M N]=size(A1);
A = A1(:);
count = [0:1:255]; % Distinct data symbols appearing in sig
total=sum(count);
for i=1:1:size((count)');
p(i)=count(i)/total;
end
[dict,avglen]=huffmandict(count,p) % build the Huffman dictionary
comp= huffmanenco(A,dict); %encode your original image with the dictionary you just built
compression_ratio= (512*512*8)/length(comp) %computing the compression ratio
%% DECODING
Im = huffmandeco(comp,dict); % Decode the code
I11=uint8(Im);
decomp=reshape(I11,M,N);
imshow(decomp);
p(i)=count(i)/total; end代码永远不会结束。 当我像答案提供的那样运行时,我会收到一个错误:Error using huffmandict (line 171) Source symbols repeatError in Huffman (line 10) [dict,avglen]=huffmandict(count,p)唯一的区别是:我获取了一张RGB图像并将其转换为灰度图像。你能帮我吗? - faith
count
计算不正确。我在我的答案中特别指出了这一点,并建议OP使用imhist
代替。如果您没有imhist
,因为它是图像处理工具箱的一部分,请使用accumarray
:p = accumarray(double(A(:)) + 1, 1, [256 1]) / numel(A);
。A
是输入图像。 - rayryengimhist
。然而,我遇到了“源符号重复”的错误。 - faithcount
变量出了问题。有重复项。请仔细检查是否正确生成了从0到255的向量,步长为1。 - rayryengcount
变量生成为count=imhist(A1)
而不是count=[0:1:255]
。那么我应该在哪里使用向量[0:255]
? - faithcount
应该保持不变。是p
不正确,我已经在我的帖子中进行了更正。请查看编辑。祝你好运。 - rayryeng