%
% script tryWavelets.m  
%
% commandline : 
% -------------
%    tryWavelets
% 
% purpose : 
% --------
% for simple experiements 
% by cps-250 students 
% with the use of wavelets 
% for analysis, filtering 
% and reconstruction 
% 


%  Nikos Pitsianis 
%  Xiaobai Sun 
%  Duke CS 
%  
% 

clear all
close all 



%% load and show image 

X = imread('peppers.png'); 

X = sum(X,3);            % make the image monchromic  
X = double(X);           % convert into double 
[m,n] = size(X); 

Xfro = norm( X, 'fro' ); 


figure(1); 
imagesc(X); 
axis equal; axis off; colormap gray
title('The original Image in grey scale')




%%  2D discrete wavelet analysis/decomposition 

disp( 'Successive analysis and approximation ...' ) 

wt      = 'db1';           % selected wavelet type 
nlevels = 3 ;              % the number of successive approximations  

Wframe2D = zeros( size(X) ); 

figure(2);  

Y = X; 

figure(2); 

for j = 1:nlevels

  disp( 'press a key' ) 
  pause 
  disp( sprintf( 'Level %d approximation', j ) ); 
  
  [Y,CH{j},CV{j},CD{j}] = dwt2(Y, wt);
  Yfro = norm( Y, 'fro');
  
  Wframe2D(1:m,1:n)  = [Y, CH{j}; CV{j}, CD{j}] ; 

  clf ; 
  imagesc( Wframe2D ); 
  axis equal; 
  axis off ; 
  colormap gray 

  Tstring = sprintf('Level %d : coefficients of %s wavelets ',j,wt); 
  Tstring = [Tstring, sprintf('%5.4g vs %5.4g in F-norm ',Yfro, Xfro) ];  
  title( Tstring ); 
  
  m = m/2; 
  n = n/2; 
end


%% filtering in between 

 Tstring = sprintf(' \n Do some filtering on the truncated coefficients !! \n'); 
 disp( Tstring ) 

%%  synthesis/reconstruction  

disp( 'Successive reconstructions : lossless or lossy' ) 

figure(3); 

for j = nlevels:-1:1

  disp( 'press a key  ') 
  pause 
  axis equal; 
  axis off; 
  colormap gray

  
  imagesc( [Y,CH{j}; CV{j},CD{j}] ); 
  axis equal; 
  axis off; 
  colormap gray
  title( sprintf( 'Before : approximation and complements at level %d', j ) ); 

  
  disp( 'press a key' ) 
  pause 
  Y = idwt2( Y,CH{j},CV{j},CD{j}, wt);

  imagesc(Y); 
  axis equal; 
  axis off; 
  colormap gray
  title(sprintf('After : reconstruction at Level %d',j ))
  
end

