%% Eigenface Example using Yale Database %%Step 1: Load the data and create the training subset using 36 people. % The total number of columns needed is: sum(nfaces(1:36)) load allFaces2.mat trainingFaces=faces(:,1:sum(nfaces(1:36))); %% Step 2: Find the mean, mean-subtract the data. Visualize the mean % as a photo! avgFace=mean(trainingFaces,2); Xm=trainingFaces-avgFace; figure(1) imagesc(reshape(avgFace,n,m)); colormap(gray); axis off; axis square %% Step 3: Compute the SVD. [U,S,V]=svd(Xm,'econ'); %% Step 4: Look at the singular values; usually a log plot for high dimensions. plot(log(diag(S))); % At approx 2262, we see a big drop- this is the rank. %% Step 5: Let's look at some eigenfaces! Here are the first four: figure(2) for j=1:4 subplot(2,2,j) imagesc(reshape(U(:,j),n,m)); colormap(gray); axis off; axis square; end %% Step 6: Project the poses from persons 2 and 7 into the plane spanned by % basis vectors 5 and 6. Don't worry about the formulas used to determine % the columns. They're included here in case you want to change 2 and 7 % to other people. P1=2; P2=7; Bas1=5; Bas2=6; P1cols=sum(nfaces(1:P1-1))+1:sum(nfaces(1:P1)); P2cols=sum(nfaces(1:P2-1))+1:sum(nfaces(1:P2)); Data=faces(:,[P1cols,P2cols]) - avgFace; Coords=U(:,[Bas1,Bas2])'*Data; % This is two dimensional data figure(3) plot(Coords(1,1:nfaces(P1)),Coords(2,1:nfaces(P1)),'ro'); hold on plot(Coords(1,nfaces(P1)+1:end),Coords(2,nfaces(P1)+1:end),'k^'); hold off %% Step 6A: Optional subplot with the two faces and positive/negative % 5th basis vector. subplot(2,2,1) imagesc(reshape(faces(:,65),n,m)); colormap(gray); axis off; axis square; subplot(2,2,2) imagesc(reshape(U(:,5),n,m)); colormap(gray); axis off; axis square; subplot(2,2,3) imagesc(reshape(faces(:,381),n,m)); colormap(gray); axis off; axis square; subplot(2,2,4) imagesc(reshape(-U(:,5),n,m)); colormap(gray); axis off; axis square; %% Step 7: Look at partial reconstructions of person 37 using rank 50, 150, 500, 1000 Data=faces(:,sum(nfaces(1:36))+1); Data=Data-avgFace; kdim=[50,150,500,1000]; figure(4) for j=1:4 subplot(2,2,j) Recon=U(:,1:kdim(j))*(U(:,1:kdim(j))'*Data); imagesc(reshape(Recon+avgFace,n,m)); colormap(gray); axis off; axis square end %% Step 8: Repeat, for the photo of a dog! Data=Dog; Data=Data-avgFace; kdim=[50,100,400,600,1600]; figure(5) subplot(2,3,1) imagesc(reshape(Dog,n,m)); colormap(gray); axis off; axis equal for j=1:5 subplot(2,3,j+1) Recon=U(:,1:kdim(j))*(U(:,1:kdim(j))'*Data); imagesc(reshape(Recon+avgFace,n,m)); colormap(gray); axis off; axis equal end