This is a code for Image Compression using Huffman Coding. Could someone tell me why am I not able to calculate the entropy? And how could I go about writing creating a file which contains the compressed image ?

25 views (last 30 days)
%clearing all variableas and screen
clear all;
close all;
clc;
%Reading image
a=imread('chair.png');
figure,imshow(a)
%converting an image to grayscale
[I, colormap] = rgb2ind(a, 256);
%size of the image
[m,n]=size(I);
Totalcount=m*n;
%variables using to find the probability
cnt=1;
sigma=0;
%computing the cumulative probability.
for i=0:255
k=I==i;
count(cnt)=sum(k(:));
%pro array is having the probabilities
pro(cnt)=count(cnt)/Totalcount;
sigma=sigma+pro(cnt);
cumpro(cnt)=sigma;
cnt=cnt+1;
end
%Symbols for an image
symbols = [0:255];
%Huffman code Dictionary
[dict, avglen] = huffmandict(symbols,pro);
entropy = - sum (pro .* log10(pro)/log10(2))
disp(['Entropy: ' num2str(entropy)]);
disp(['Average Length: ' num2str(avglen)])
%function which converts array to vector
vec_size = 1;
for p = 1:m
for q = 1:n
newvec(vec_size) = I(p,q);
vec_size = vec_size+1;
end
end
%Huffman Encodig
hcode = huffmanenco(newvec,dict);
%Huffman Decoding
dhsig1 = huffmandeco(hcode,dict);
%convertign dhsig1 double to dhsig uint8
dhsig = uint8(dhsig1);
%vector to array conversion
dec_row=sqrt(length(dhsig));
dec_col=dec_row;
%variables using to convert vector 2 array
arr_row = 1;
arr_col = 1;
vec_si = 1;
for x = 1:m
for y = 1:n
back(x,y)=dhsig(vec_si);
arr_col = arr_col+1;
vec_si = vec_si + 1;
end
arr_row = arr_row+1;
end
%converting image from grayscale to rgb
RGB = ind2rgb(back, colormap);
imwrite(RGB,'decoded.png');
%end of the huffman coding

Answers (1)

Haleem Ebdul
Haleem Ebdul on 19 Dec 2021
Instead of writing image to disk, i use figure to display image, then save as jpg. boom it give what i want, the image size is half of original
% imwrite(RGB,'decoded.png');
figure,imshow(RGB)

Categories

Find more on Denoising and Compression in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!