我想通过使用Python的主成分分析(PCA)实现人脸识别。我下面这个教程中的步骤:http://onionesquereality.wordpress.com/2009/02/11/face-recognition-using-eigenfaces-and-distance-classifiers-a-tutorial/使用Python的主成分分析(PCA)
这里是我的代码:
import os
from PIL import Image
import numpy as np
import glob
import numpy.linalg as linalg
#Step1: put database images into a 2D array
filenames = glob.glob('C:\\Users\\Karim\\Downloads\\att_faces\\New folder/*.pgm')
filenames.sort()
img = [Image.open(fn).convert('L').resize((90, 90)) for fn in filenames]
images = np.asarray([np.array(im).flatten() for im in img])
#Step 2: find the mean image and the mean-shifted input images
mean_image = images.mean(axis=0)
shifted_images = images - mean_image
#Step 3: Covariance
c = np.cov(shifted_images)
#Step 4: Sorted eigenvalues and eigenvectors
eigenvalues,eigenvectors = linalg.eig(c)
idx = np.argsort(-eigenvalues)
eigenvalues = eigenvalues[idx]
eigenvectors = eigenvectors[:, idx]
#Step 5: Only keep the top 'num_eigenfaces' eigenvectors
num_components = 20
eigenvalues = eigenvalues[0:num_components].copy()
eigenvectors = eigenvectors[:, 0:num_components].copy()
#Step 6: Finding weights
w = eigenvectors.T * np.asmatrix(shifted_images)
#Step 7: Input image
input_image = Image.open('C:\\Users\\Karim\\Downloads\\att_faces\\1.pgm').convert('L').resize((90, 90))
input_image = np.asarray(input_image)
#Step 8: get the normalized image, covariance, eigenvalues and eigenvectors for input image
shifted_in = input_image - mean_image
cov = np.cov(shifted_in)
eigenvalues_in, eigenvectors_in = linalg.eig(cov)
我得到一个错误: Traceback (most recent call last): File "C:/Users/Karim/Desktop/Bachelor 2/New folder/new3.py", line 47, in <module> shifted_in = input_image - mean_image ValueError: operands could not be broadcast together with shapes (90,90) (8100)
我试图从步骤1中删除.flatten()
但这产生的另一计算特征值和特征向量时出错: Traceback (most recent call last): File "C:/Users/Karim/Desktop/Bachelor 2/New folder/new3.py", line 25, in <module> eigenvalues,eigenvectors = linalg.eig(c) File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 1016, in eig _assertRank2(a) File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 155, in _assertRank2 'two-dimensional' % len(a.shape)) LinAlgError: 4-dimensional array given. Array must be two-dimensional
我也尝试在步骤7b中添加.flatten()
当计算输入图像的特征值和特征向量时,它也会产生另一个错误: Traceback (most recent call last): File "C:/Users/Karim/Desktop/Bachelor 2/New folder/new3.py", line 49, in <module> eigenvalues_in, eigenvectors_in = linalg.eig(cov) File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 1016, in eig _assertRank2(a) File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 155, in _assertRank2 'two-dimensional' % len(a.shape)) LinAlgError: 0-dimensional array given. Array must be two-dimensional
任何人都可以帮忙?
你说得对T的协方差他输入图像。感谢这个有用的评论,但是很荣幸,我没有得到你的意思,推测它是一个2D矩阵 – user2229953
@ user2229953我已经用一个例子对其进行了阐述。 – askewchan