#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 11 09:39:38 2021 Adapted from databookuw.com """ import matplotlib.pyplot as plt import numpy as np import scipy.io # Step 0: set some parameters, load the original Matlab data plt.rcParams['figure.figsize'] = [8, 8] plt.rcParams.update({'font.size': 18}) mat_contents = scipy.io.loadmat('allFaces2.mat') faces = mat_contents['faces'] m = int(mat_contents['m']) n = int(mat_contents['n']) Dog = mat_contents['Dog'] nfaces = np.ndarray.flatten(mat_contents['nfaces']) #%% # Step 1: Load the data trainingFaces = faces[:,:np.sum(nfaces[:36])] #%% # Step 2: Find the mean, visualize it. avgFace = np.mean(trainingFaces,axis=1) # size n*m by 1 Xm=trainingFaces-avgFace[:,np.newaxis]; plt.figure() plt.imshow(np.reshape(avgFace,(m,n)).T) plt.set_cmap('gray') plt.title('Mean Face') plt.axis('off') plt.show() #%% # Step 3: Compute the SVD U, S, VT = np.linalg.svd(Xm,full_matrices=0) #%% # Step 4: Plot the singular values. plt.figure() plt.plot(np.log(S)) #%% # Step 5: Let's look at some eigenfaces (first 4, pos and neg) fig,axs = plt.subplots(2,2) axs=axs.ravel() for i in range(4): axs[i].imshow(np.reshape(U[:,i],(m,n)).T) fig,axs = plt.subplots(2,2) axs=axs.ravel() for i in range(4): axs[i].imshow(np.reshape(-U[:,i],(m,n)).T) axs[i].set_title(str(i)) #%% ## Step 6: Project person 2 and 7 onto basis vecs 5 and 6 P1 = 2 # Person number 2 P2 = 7 # Person number 7 P1data = faces[:,np.sum(nfaces[:(P1-1)]):np.sum(nfaces[:P1])] P2data = faces[:,np.sum(nfaces[:(P2-1)]):np.sum(nfaces[:P2])] P1data = P1data - avgFace[:,np.newaxis] P2data = P2data - avgFace[:,np.newaxis] # Project onto PCA modes 5 and 6 PCACoordsP1 = U[:,4:6].T @ P1data PCACoordsP2 = U[:,4:6].T @ P2data plt.figure() plt.plot(PCACoordsP1[0,:],PCACoordsP1[1,:],'d',color='k',label='Person 2') plt.plot(PCACoordsP2[0,:],PCACoordsP2[1,:],'^',color='r',label='Person 7') plt.legend() plt.show() # %% ## Step 7: Show eigenface reconstruction of image that was omitted from test set plt.figure() testFace = faces[:,np.sum(nfaces[:36])] # First face of person 37 plt.imshow(np.reshape(testFace,(m,n)).T) plt.set_cmap('gray') plt.title('Original Image') plt.axis('off') plt.show() #%% Step 8: Reconstruct a dog from photos of people! # # Vector "Dog" needs to be reshaped for some reason... Dog=np.reshape(Dog,(32256,)) testFace = Dog - avgFace k_list = [50, 200, 500, 1000, 1600] plt.figure() fig,axs = plt.subplots(2,3) axs=axs.ravel() axs[0].imshow(np.reshape(Dog,(m,n)).T) axs[0].axis('off') for i in range(5): reconFace = avgFace + U[:,:k_list[i]] @ ( U[:,:k_list[i]].T @ testFace) axs[i+1].imshow(np.reshape(reconFace,(m,n)).T) axs[i+1].axis('off')