

clear;
delete('j*.j*');
%inFile = 'cameraman.tif';
inFile='mandi2.tif';
folder = fileparts(which(inFile));
A = imread(fullfile(folder,inFile));
[Height,Width,Depth] = size(A);
if Depth > 1
    A = rgb2gray(A);
end

dwt_levels=8;
show_files_at_size_kB=20;

N1=5;
N2=5;

V1=round(linspace(1,80,N1));
V2=logspace(1,3,N2);

ijpg=1;
for Q_JPEG=V1,
    fprintf('JPEG coding...\n');
    
    fname=sprintf('jpeg_%d.jpg',Q_JPEG);
    
    tic;
    imwrite(A,fname,'Quality',Q_JPEG);
    t_jpeg_coding(ijpg)=toc;
    fprintf('JPEG decoding...\n');
    tic;
    A_jpg=imread(fname);
    t_jpeg_decoding(ijpg)=toc;
    
    fprintf('Quality assesment\n');
    [mssim, ssim_map] = ssim(A, A_jpg);
    ssim_jpg(ijpg)=mssim;
    
    [psnr,mse]=PSNR(A,A_jpg,255);
    psnr_jpg(ijpg)=psnr;
    
    f=dir(fname);
    size_jpg(ijpg)=f.bytes;
    
    ijpg=ijpg+1;
end



ijpg2000=1;
for CR_JPEG2000=V2
    fprintf('JPEG2000 coding...\n');
    
    fname=sprintf('jpeg_2000_%d_%f.jp2',dwt_levels,CR_JPEG2000);
    
    tic;
    imwrite(A,fname,...
        'ReductionLevels',dwt_levels, 'CompressionRatio',CR_JPEG2000);
    t_jpeg2000_coding(ijpg2000)=toc;
    tic
    A_jpg2000=imread(fname);
    t_jpeg2000_decoding(ijpg2000)=toc;
    
    fprintf('Quality assesment\n');
    [mssim, ssim_map] = ssim(A, A_jpg2000);
    ssim_jpg2000(ijpg2000)=mssim;
    
    [psnr,mse]=PSNR(A,A_jpg2000,255);
    psnr_jpg2000(ijpg2000)=psnr;
    
    f=dir(fname);
    size_jpg2000(ijpg2000)=f.bytes;
    
    
    ijpg2000=ijpg2000+1;
end

figure;
plot(size_jpg/1024,ssim_jpg,'r');
hold on;
plot(size_jpg2000/1024,ssim_jpg2000,'b');
legend('JPEG','JPEG2000');
xlabel('Filesize [kB]');
ylabel('SSIM');
title('SSIM - JPEG vs JPEG2000');



figure;
plot(size_jpg/1024,psnr_jpg,'r');
hold on;
plot(size_jpg2000/1024,psnr_jpg2000,'b');
legend('JPEG','JPEG2000');
xlabel('Filesize [kB]');
ylabel('PSNR [dB]');
title('PSNR - JPEG vs JPEG2000');


figure;
plot(size_jpg/1024,t_jpeg_coding,'r');
hold on;
plot(size_jpg2000/1024,t_jpeg2000_coding,'b');
legend('JPEG','JPEG2000');
xlabel('Filesize [kB]');
ylabel('Coding time [sec]');
title('Coding time - JPEG vs JPEG2000');


figure;
plot(size_jpg/1024,t_jpeg_decoding,'r');
hold on;
plot(size_jpg2000/1024,t_jpeg2000_decoding,'b');
legend('JPEG','JPEG2000');
xlabel('Filesize [kB]');
ylabel('Decoding time [sec]');
title('Decoding time - JPEG vs JPEG2000');

fjpg=dir('j*.jpg');
[i_jpg]=find_file_at_size_kB(show_files_at_size_kB,fjpg);
fjpg2000=dir('j*.jp2');
[i_jpg2000]=find_file_at_size_kB(show_files_at_size_kB,fjpg2000);
Ajpg=imread(fjpg(i_jpg).name);
Ajpg2000=imread(fjpg2000(i_jpg2000).name);
figure;
imshow(Ajpg);title(sprintf('JPEG at approx. filesize: %d kB',show_files_at_size_kB));
figure;
imshow(Ajpg2000);title(sprintf('JPEG2000 at approx. filesize: %d kB',show_files_at_size_kB));





