【问题标题】:Face recognition - Python人脸识别 - Python
【发布时间】:2023-03-06 10:46:01
【问题描述】:

我正在尝试使用 python 通过 主成分分析 (PCA) 进行人脸识别。

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

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 p>

【问题讨论】:

    标签: python arrays numpy face-recognition pca


    【解决方案1】:

    我不相信您修改了图像在w 中与images 相比的存储顺序,因此,来自np.argmin(d)idx 应该与images 的索引相同列表,所以

    images[idx]
    

    应该是你想要的图像。

    当然,

    images[idx].shape
    

    将给出(1800,),因为它仍然是扁平的。如果你想把它弄平,你可以这样做:

    images[idx].reshape(90,90)
    

    【讨论】:

    • 我认为这不是真的。因为images 包含 30 张图片(3 张面孔,每张 10 张图片)。而d由20个距离组成,所以idx的最大值=20,所以如果测试图像input_images包含第三张图像(输出应该在21-30之间)我永远不会得到正确的结果。
    • 我明白了,在我使用的虚构数据中,情况并非如此:-P
    猜你喜欢
    • 2018-06-14
    • 2019-08-10
    • 2019-01-21
    • 2017-02-26
    • 2017-02-03
    • 2019-05-10
    • 2016-07-17
    • 2013-12-24
    • 2020-10-07
    相关资源
    最近更新 更多