function g = svd_compress(imname,r) f_in = double(imread(imname)); %load image f = f_in(:,:,1); [mr,mc] = size(f); m = mr*mc; g = zeros(mr,mc); %compute SVD [U,S,V] = svd(f); %load U; load S; load V; %shortcut, can load from memory if using same image with different r sv = diag(S); %singular values svlen = length(find(sv>0)); s = round(r*svlen); %number of singular values to keep %compress Uc = U(:,1:s); svc = sv(1:s); Vc = V(:,1:s); numval = s + mr*s + mc*s; %total number of values that we must store %approximate image using only the stored elements g = Uc*(svc(:,ones(1,mc)).*Vc'); %full grayscale map for L intensity values L = 256; cmap = zeros(L,3); cmap(:,1) = [0:(1/(L-1)):1]'; cmap(:,2) = [0:(1/(L-1)):1]'; cmap(:,3) = [0:(1/(L-1)):1]'; %compression factor cf = numval/m; %ratio of number of stored elements to number of pixels in original image %plot stuff figure(18) subplot(1,2,1); colormap(cmap); image(f); axis off; title('original image'); subplot(1,2,2); colormap(cmap); image(g); axis off; title([num2str(100*s/svlen) '% singular values, ' num2str(100*cf) '% storage']);