%%   jpegtest.m

%   Matlab script to test the performance of jpeg

Q = [ 100 99 98 ] ;                % quality factors to test

x = double(imread('peppers.tif')) ;     % read the image. It should be tif format
                                        %  though imread can be made to
                                        %  read other formats
[sx,sy] = size(x) 
N = sx * sy                         %number pixels in image

% compute variance of image
mean = sum(sum( x )) / N 
variance = sum(sum( (x-mean).^2 ) ) / N 

% plot original image
subplot(2,2,1)
imagesc(x), axis image, colormap gray
xlabel('original image')
       
% jpeg encode image 
for k =1:length(Q)
    imwrite(uint8(x),'codedimage.jpg','jpeg','Quality',Q(k),'Bitdepth',8)
             % the above saves the image in jpeg encoded form with
             % specified quality factor
    INFO = imfinfo('codedimage.jpg') ;           
    Size = INFO.FileSize ;            % number of bytes in the encoded image
    Rate = Size * 8 / N ;             % encoded rate in bits/pixel
    
    y = double(imread('codedimage.jpg','JPEG')) ;   % we reread the image to display it 
                                                    % and compute mse and snr
    D = sum(sum( (x-y).^2 ))/ N ;
	SNR = 10 * log10( variance /D ) ;
    PSNR = 10 * log10( 255^2 /D ) ;
	subplot(2,2,k+1)
	imagesc(y),  axis image, colormap gray
	xlabel(['Q=' num2str(Q(k)) ',  R=' num2str(Rate,2) ',  D=' num2str(D,3) ',  SNR=' num2str(SNR,3) ' dB,  PSNR=' num2str(PSNR,3) ' dB'])
end
