简体   繁体   中英

How to calculate eigenfaces in python?

I'm trying to calculate eigenfaces for a set of images using python.

First I turn each image into a vector using:

list(map(lambda x:x.flatten(), x))

Then I calculate covariance matrix (after removing mean from all data):

# x is a numpy array

x = x - mean_image
cov_matrix = np.cov(x.T)

Then I calculate eigenvalues and eigenevtors:

eigen_values, eigen_vecotrs = np.linalg.eig(cov_matrix)

The results are vectors with complex numbers, so I only keep the real part to be able to show them:

eigen_vectors = np.real(eigen_vectors)

After trying to show eigenfaces ( eigenvectors ), the result is not even close to how an eigenface looks like:

图片

I have managed to get a list of eigenfaces using np.linalg.svd() however I'm curious why my code does not work and how can I change it so it work as expected.

To fix the np.linalg.eig returning complex results I reduced the size of images, so it doesn't return complex numbers anymore however still my eigenvectors doesn't look like an eigenface:

在此处输入图片说明

proj_data = np.dot(x.transpose(),eigen_vector).T 
img = proj_data[i].reshape(height,width)

This will give you the expected result.

After calculating the eigenvectors you should transpose it. Or you will get mixed image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM