% workshhet 8
% get signal
load clown
[m,n] = size(X);
X = X-mean(X(:));


% question 1
% compute and wavelet transform
[la,ha,ls,hs] = wfilters('db2')
[CA,CH,CV,CD] = dwt2(X,la,ha,'mode','per');
w1X = [CA,CV;CH,CD];

figure(1)
imshow(w1X,[]);
disp('Press a key')
pause

% compare energies
EA = energy(CA);
EV = energy(CV);
EH = energy(CH);
ED = energy(CD);
energy_percents = 100*[EA,EV;EH,ED]/(EA+EV+EH+ED)
disp('Press a key')
pause


% question 2
% approximation and details
Z1 = zeros(size(CA)); 
XA = idwt2(CA,Z1,Z1,Z1,ls,hs,'mode','per');
XH = idwt2(Z1,CH,Z1,Z1,ls,hs,'mode','per');
XV = idwt2(Z1,Z1,CV,Z1,ls,hs,'mode','per');
XD = idwt2(Z1,Z1,Z1,CD,ls,hs,'mode','per');

figure(2)
subplot(1,2,1);
imshow(CA,[]);
subplot(1,2,2);
imshow(XA,[]);
disp('Press a key')
pause




% question3
% decomposition

U = X-XA-XH-XV-XD;
energy_of_diff = energy(U)


% question 4
% dot products in terms of energies
Cdots = [m*n*energy(CA)/4, m*n*energy(CH)/4,m*n*energy(CV)/4,m*n*energy(CD)/4] 
Xdots = [m*n*energy(XA), m*n*energy(XH),m*n*energy(XV),m*n*energy(XD)] 

% question 6
XdotX = m*n*energy(X)
sumofXdots = sum(Xdots)
disp('Press a key')
pause


% question 7
% decomposition
X1a = XA;
X1d = XV+XH+XD;
% X1a = idwt2(CA,Z1,Z1,Z1,ls,hs,'mode','per');
% X1d = idwt2(Z1,CH,CV,CD,ls,hs,'mode','per');

figure(3)
subplot(1,3,1);
imshow(X,[]);
subplot(1,3,2);
imshow(X1a,[]);
subplot(1,3,3);
imshow(X1d,[]);
disp('Press a key')
pause



% two stage
[CAA,CAH,CAV,CAD] = dwt2(CA,la,ha,'mode','per');
w2X = [[CAA,CAV;CAH,CAD],CV; CH, CD];
figure(4)
imshow(w2X,[]);
disp('Press a key')
pause

% question 8
Z2 = zeros(size(CAA)); 
XCAA = idwt2(CAA,Z2,Z2,Z2,ls,hs,'mode','per');
X2a  = idwt2(XCAA,Z1,Z1,Z1,ls,hs,'mode','per');
XCAD = idwt2(Z2,CAH,CAV,CAD,ls,hs,'mode','per');
X2d  = idwt2(XCAD,Z1,Z1,Z1,ls,hs,'mode','per');

figure(5)
subplot(2,2,1)
imshow(X,[]);
subplot(2,2,2)
imshow(X2a,[]);
subplot(2,2,3)
imshow(X2d,[]);
subplot(2,2,4)
imshow(X1d,[]);
disp('Press a key')
pause

U = X-X1a-X1d;
energy_of_diff_lev1 = energy(U)
U = X-X2a-X2d-X1d;
energy_of_diff_lev2 = energy(U)






