%%%%%%%%%%%%%
%%2d
%%%%%%%%%%%%%

%% low-rank image

N = 800;

f = zeros(N);
f(.2*N:.8*N,.2*N:.4*N) = 1;
f(.6*N:.8*N,.4*N:.8*N) = 2;
figure(11);imagesc(f,[-6,6]);axis image;colorbar;
title('Original low-rank image');

[U,S,V] = svd(f);
size(S);
figure(12);stem(diag(S));
title('Singular values of original image');


n = randn(N);
y = f+n;
figure(13);imagesc(y,[-6,6]);axis image;colorbar;
title('Noisy image');

[U2,S2,V2] = svd(y);
figure(14);stem(diag(S2));
title('Noisy singular values')

S_hat = S2.*(abs(S2)>N/4);
f_oracle = U*S_hat*V';
f_hat = U2*S_hat*V2';

figure(15);imagesc(f_oracle,[-6,6]);axis image;colorbar
title('Denoised image with oracle knowledge of low-rank structure')

figure(16);imagesc(f_hat,[-6,6]);axis image;colorbar
title('Denoised image via svd');


%% cameraman
f = double(imread('cameraman.bmp'));
f = f/max(f(:));
y = f+ randn(size(f))/10;
h = fspecial('gaussian',[5 5],2);
f_hat = conv2(y,h,'same');

figure(17);imagesc([f y f_hat],[0,1]);axis image;colormap gray; colorbar;axis off
title('Original image --|-- Noisy image --|-- Smoothed noisy image');

%% phantom

N = 256;
f = phantom(N);
y = f + randn(N)/10;
h = fspecial('gaussian',[5 5],2);
f_hat_1 = conv2(y,h,'same');

f_hat_2 = low_rank_denoise(y,5);

k = 8;
f_hat_3a = blockproc(y,[k,k],@(x) low_rank_denoise(x.data-mean(x.data(:)),.6)+mean(x.data(:)));
f_hat_3b = circshift(blockproc(circshift(y,[k/2,0]),[k,k],@(x) low_rank_denoise(x.data-mean(x.data(:)),.6)+mean(x.data(:))),[-k/2,0]);
f_hat_3c = circshift(blockproc(circshift(y,[0,k/2]),[k,k],@(x) low_rank_denoise(x.data-mean(x.data(:)),.6)+mean(x.data(:))),[0,-k/2]);
f_hat_3d = circshift(blockproc(circshift(y,[k/2,k/2]),[k,k],@(x) low_rank_denoise(x.data-mean(x.data(:)),.6)+mean(x.data(:))),[-k/2,-k/2]);

f_hat_4 = (f_hat_3a+f_hat_3b+f_hat_3c+f_hat_3d)/4;



figure(18);imagesc([f y f_hat_1; f_hat_2 f_hat_3a f_hat_4],[0,1]);axis image;colormap gray;
axis off
h = text(10,10,'Original image','Color',[1 1 1],'FontSize',16);
h = text(10+N,10,'Noisy image','Color',[1 1 1],'FontSize',16);
h = text(10+2*N,10,'Smoothed image','Color',[1 1 1],'FontSize',16);
h = text(10,10+N,'SVD denoised image','Color',[1 1 1],'FontSize',16);
h = text(10+N,10+N,'Blockwise SVD denoised image','Color',[1 1 1],'FontSize',16);
h = text(10+2*N,10+N,'Cycle spun blockwise SVD denoised image','Color',[1 1 1],'FontSize',16);




