clear all;
close all;
clc;

%%%%% people -- color figure
A = imread('LS_SVD_ImageCompress_02.png');
A = rgb2gray(A);
A = A(50:562,1:512); % cut the image
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A = mat2gray(A);
imshow(A); pause

% [m,n] = size(A);
% r = rank(A); 
[U,D,V] = svd(A);  % A = U*D*V', U:m-by-m, D:m-by-n; V:n-by-n

% plot(diag(D),'+');

% compressed image 
KK = [1,50,100,150]; 
for idx = 1:length(KK)
    k = KK(idx);
    A1 = U(:,1:k)*D(1:k,1:k)*V(:,1:k)';
    subplot(2,2,idx); imshow(A1);
    tit = ['k=',int2str(k),sprintf(', relerr=%2.e',norm(A1-A,1)/norm(A,1))];
    title(tit);
    pause
end

%%%%% print the images
% figure;
% imshow(A,'Border','tight'); figname = ['svdIC02'];
% title('original image','FontSize',25);
% % set(gcf,'PaperPositionMode','auto');
% pos=get(gcf,'Position'); % 获取窗口尺寸信息
% % pos(4)=pos(4)*1.2; % 改变窗口宽度（倍数根据长宽比自己确定）
% set(gcf,'Position',[100,100,pos(3),pos(4)*1.2]); 
% print('-dpng', figname);
% for idx = 1:length(KK)
%     k = KK(idx);
%     A1 = U(:,1:k)*D(1:k,1:k)*V(:,1:k)';
%     figname = ['svdIC02_',sprintf('%d',k)];
%     imshow(A1,'Border','tight'); % imwrite(A1,figname);
%     tit = ['k=',int2str(k),sprintf(', relerr=%2.e',norm(A1-A,1)/norm(A,1))];
%     title(tit,'FontSize',25);
%     % print the image
%     set(gcf,'PaperPositionMode','auto')
%     set(gcf,'Position',[100,100,pos(3),pos(4)*1.2]); 
%     print('-dpng', figname);    
% end

