Python错误 - ValueError:需要多于1个值才能解压缩

时间:2013-04-11 23:46:31

标签: python numpy matplotlib face-recognition pca

我正在尝试使用python(matplotlib)通过主成分分析(PCA)进行人脸识别。我试图按照此图像中的描述进行操作:

enter image description here

这是我的代码:

import os
from PIL import Image
import numpy as np
import glob
from matplotlib.mlab import PCA

#Step1: put database images into a 3D array
filenames = glob.glob('C:\\Users\\Karim\\Downloads\\att_faces\\New folder/*.pgm')
filenames.sort()
img = [Image.open(fn).convert('L') for fn in filenames]
images = np.dstack([np.array(im) for im in img])

# Step2: create 2D flattened version of 3D input array
d1,d2,d3 = images.shape
b = np.zeros([d1,d2*d3])
for i in range(len(images)):
  b[i] = images[i].flatten()

#Step 3: database PCA
results = PCA(b.T)
x = results.Wt

#Step 4: input image
input_image = Image.open('C:\\Users\\Karim\\Downloads\\att_faces\\1.pgm').convert('L')
input_image = np.array(input_image)
input_image = input_image.flatten()

#Step 5: input PCA
in_results = PCA(input_image.T)
y = in_results.Wt

#Step 6: get shortest distance

但我从in_results = PCA(input_image.T)说出错: Traceback (most recent call last): File "C:\Users\Karim\Desktop\Bachelor 2\New folder\new2.py", line 29, in <module> in_results = PCA(input_image.T) File "C:\Python27\lib\site-packages\matplotlib\mlab.py", line 846, in __init__ n, m = a.shape ValueError: need more than 1 value to unpack

任何人都可以提供帮助??

1 个答案:

答案 0 :(得分:3)

问题是PCA构造函数需要一个2D数组,并假设你要传递一个。您可以从追溯中看到:

in __init__ 
n, m = a.shape 
ValueError: need more than 1 value to unpack

显然,如果a是0D或1D数组,a.shape将不会有两个成员,因此这将失败。您可以尝试自己打印input_image.T.shape以查看它是什么。

但是你的代码至少有一个问题,可能有两个。

首先,即使您在某个时刻有2D数组,也可以这样做:

input_image = input_image.flatten()

之后,当然,你有一个1D阵列。

其次,我认为你没有2D阵列。这样:

input_image = np.array(input_image)

...应根据numpyPIL文档所说的内容,创建一个包含一个对象的“标量”(0D)数组。在各种不同的设置上进行测试,我似乎有时会得到一个0D数组,有些是2D数组,所以也许你没有遇到这个问题 - 但如果你不是这样,你可能会在你运行不同的时候得到它机。

你可能想要这个:

input_image = np.asarray(input_image)

这将为您提供2D数组,或引发异常。 (好吧,除非你不小心打开一个多通道图像,当然它会给你一个3D数组。)