Pythonを使用して主成分分析(PCA)による顔認識を実装しようとしています。このチュートリアルの手順に従っています: http://onionesquereality.wordpress.com/2009/02/11/face-recognition-using-eigenfaces-and-distance-classifiers-a-tutorial/
これが私のコードです:
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
ステップ 7にも追加しようとし.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
誰でも助けてくれますか??