首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >人脸识别- Python

人脸识别- Python
EN

Stack Overflow用户
提问于 2013-04-16 22:49:00
回答 1查看 1.5K关注 0票数 4

我试图利用python进行主成分分析(PCA)人脸识别。

现在我可以得到训练图像images和输入图像input_image之间的最小欧几里德距离。这是我的代码:

代码语言:javascript
运行
复制
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\\me\\Downloads\\/*.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.asmatrix(shifted_images) * np.asmatrix(shifted_images.T)

#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) 
# check eigenvectors.T/eigenvectors 

#Step 7: Input image
input_image = Image.open('C:\\Users\\me\\Test\\5.pgm').convert('L').resize((90, 90))
input_image = np.asarray(input_image).flatten()

#Step 8: get the normalized image, covariance, 
# eigenvalues and eigenvectors for input image
shifted_in = input_image - mean_image
c = np.cov(input_image)
cmat = c.reshape(1,1)
eigenvalues_in, eigenvectors_in = linalg.eig(cmat)

#Step 9: Find weights of input image
w_in = eigenvectors_in.T * np.asmatrix(shifted_in) 
# check eigenvectors/eigenvectors_in

#Step 10: Euclidean distance
d = np.sqrt(np.sum(np.asarray(w - w_in)**2, axis=1))
idx = np.argmin(d)
print idx

我现在的问题是,我想返回图像(或者它在数组images**)中的索引,它的最小欧氏距离**),而不是它在d数组中的索引。

EN

回答 1

Stack Overflow用户

发布于 2013-04-17 02:21:18

我不认为您修改了将图像存储在w中的顺序,而不是images中,因此,idx from np.argmin(d)应该是images列表的相同索引,因此

代码语言:javascript
运行
复制
images[idx]

应该是你想要的形象。

当然了,

代码语言:javascript
运行
复制
images[idx].shape

会给出(1800,),因为它仍然是扁平的。如果你想解开它,你可以:

代码语言:javascript
运行
复制
images[idx].reshape(90,90)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16048535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档