Could someone help me with the errors I'm facing in this code ? The code is for Image Compression using Huffman Coding

6 次查看(过去 30 天)
clc;
clear all;
close all;
base = 2; % For base (b) Huffman Coding
%% READING THE TEXT FILE
img = imread('chair.png');
img1 = double(img(:));
[M, N] = size(img1);
%% HUFFMAN CODING
[sym_prob,sym] = hist(img1,unique(img1));
sym_prob = sym_prob/sum(sym_prob);
entropy = - sum(sym_prob .*(log10(sym_prob)/log10(base)));
disp(['The entropy of the file is: ' num2str(entropy)]);
% Creating the dictionary corresponding to each used symbol
[dict,avglen]=huffmandict(sym,sym_prob, base);
disp(['The average length of the Huffman code is: ' num2str(avglen)]);
disp(['The efficiency of the Huffman code is: ' num2str(entropy/avglen*100) '%']);
disp(['The redundancy of the Huffman code is: ' num2str((1 - (entropy/avglen))*100) '%']);
fprintf('\n')
enco = huffmanenco(img1, dict); % Encoding the data
%% STORING & DISPLAYING THE COMPRESSED DATA
huff_im=bin2dec(enco');
huff_im=reshape(huff_im,M,N);
huff_im=uint8(huff_im);
imwrite(huff_im, 'compressed_img.png')
imshow(huff_im)

回答(1 个)

Raag
Raag 2025-3-7
Hi Vincent,
The main issue is that Huffman encoding creates a variable-length bit stream, which cannott be directly converted into a fixed-size image using functions like ‘bin2dec’ and reshaping. The encoded data is not structured like your original image data, so forcing it into that shape leads to errors.
When you encode the image with ‘huffmanenco’, each pixel is replaced by a binary code that can vary in length. Trying to convert these variable-length codes into a standard numeric format using ‘bin2dec’ and then reshaping them to the original image dimensions will not work. Instead, the proper approach is to save the encoded data along with the Huffman dictionary and later decode the data using ‘huffmandeco’.
Here is a concise example:
% Read the image and convert it to a vector
img = imread('chair.png');
img_vector = double(img(:));
% Calculate symbol probabilities for the pixel values
uniqueSymbols = unique(img_vector);
[sym_counts, sym] = hist(img_vector, uniqueSymbols);
sym_prob = sym_counts / sum(sym_counts);
% Create the Huffman dictionary
[dict, avglen] = huffmandict(sym, sym_prob, 2);
disp(['Average Length: ' num2str(avglen)]);
% Encode the image data using Huffman encoding
enco = huffmanenco(img_vector, dict);
% To decode, use the Huffman decoder and reshape to the original image dimensions
decoded_img = huffmandeco(enco, dict);
decoded_img = reshape(decoded_img, size(img));
% Display the decoded image
imshow(uint8(decoded_img));
For a better understanding of the above solution, refer to the following MATLAB documentations:

类别

Help CenterFile Exchange 中查找有关 Denoising and Compression 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by