Image compression using Huffman coding

조회 수: 2 (최근 30일)
Juila
Juila 2019년 10월 4일
Hi, I need a matlab code for png image compression using Huffman coding, i use this coding but i can't get cmpression, can anynone check my code plase and tell me what is wrong with my coding, also i need to save this to binary file for comparison thank you in advance
clear all;
clc;
% input image
image = imread('img1.png');
[m,n] = size(image);
J = imresize(image,[256 256]);
[x,y] = size(J);
figure();
imshow(J);
title('original RGB image')
drawnow();
Image = rgb2gray(J);
figure();
imshow(Image);
title('original image as grayscale');
drawnow();
[N, M] = size(Image);
Count = zeros(256,1);
for i = 1:N
for j = 1:M
Count(Image(i,j)+1) = Count(Image(i,j)+1)+1;
end
end
prob = Count/(M*N);
prob_1=prob(:)';
symbols = 0:255;
[dict,avglen] = huffmandict(symbols,prob);
comp = huffmanenco(Image(:),dict);
l_encoded=length(comp);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
head1 = [l_encoded [N, M] prob_1 ];
l_head = length( head1 );
header = [l_head head1];
%%%%%%%%%%% File writing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
image=input('comp.bin): ', 's');
fid=fopen(image,'w');
fwrite(fid, header, 'double'); %%%% writing the header in double format
fwrite(fid,comp,'ubit1'); %%%% writing the encoded bits in binary format after the header
fclose(fid);
decomp = cast( reshape(huffmandeco(comp,dict), N, M), class(Image));
figure();
imshow(decomp);
title('reconstructed image');
drawnow();
figure();
dimg = imsubtract(Image, decomp);
imshow(dimg, []);
title('difference between original and reconstructed (expect no difference)');
drawnow();

답변 (0개)

카테고리

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