echo on
%This program demonstrates how singular value
%decomposition can be used to compress an image.
%It requires the companion program
%displaycomponents.m which should be in the
%same directory.  The image trees comes with
%matlab itself as a demo.

load trees %load the image

a = ind2gray(X,map);%convert the image to gray

[m,n] = size(a);%size of the image

a = a(1:2:m,1:2:n);%reduce image to make svd faster

[u,s,v] = svd(a);

sv = diag(s);%singular values of a

plot(sv)

pause

%The next part generates a slider which allows
%you to control the number of singular values
%that you use in reconstructing the picture.

components = uicontrol('Style','Slider',...
	'Min',1,'Max',40,'Value',20,...
	'Position',[20,20,400,20],...
	'Callback','displaycomponents');

%this is a matlab function which generates and
%draws the image with the slider-controlled
%number of components:

displaycomponents


___________________________________


%Save this script as displaycomponents.m
echo off;

ncomp = get(components,'Value');
ncomp = round(ncomp)

i = 1:ncomp;%select first ncomp values

us = u(:,i);
vs = v(:,i);
ss = diag(sv(i));

%This produces an estimate of a by using only
%the first ncomp singular values.
as = us*ss*vs';


subplot(1,2,1);
imshow(a,64);

subplot(1,2,2);
imshow(as,64);