# 错误 - 计算python中PCA的欧氏距离Error - Calculating Euclidean distance for PCA in python

``````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.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 = 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: Fing weights of input image
w_in = eigenvectors_in.T * np.asmatrix(shifted_in)
print w_in
print w_in.shape

#Step 10: Euclidean distance
d = np.sqrt(np.sum((w - w_in)**2))
idx = np.argmin(d)
match = images[idx]
``````

## 2 个回复2

### ===============>>#1 票数：3 已采纳

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