PCA人脸识别GUI的python代码
时间: 2023-10-29 11:07:11 浏览: 108
以下是使用PCA进行人脸识别的Python GUI代码:
```python
import tkinter as tk
from tkinter import filedialog
import cv2
import numpy as np
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("PCA Face Recognition")
# 创建选择文件按钮
self.file_button = tk.Button(self, text="选择图像文件", command=self.select_file)
self.file_button.pack(pady=10)
# 创建显示图像的画布
self.canvas = tk.Canvas(self, width=400, height=400)
self.canvas.pack(pady=10)
# 创建识别按钮
self.recognize_button = tk.Button(self, text="识别人脸", command=self.recognize_face)
self.recognize_button.pack(pady=10)
# 加载人脸图像数据
self.faces = np.load("faces.npy")
# 计算平均人脸和特征向量
self.mean_face = np.mean(self.faces, axis=0)
self.feature_vectors = self.faces - self.mean_face
# 计算协方差矩阵和特征值/特征向量
cov_matrix = np.cov(self.feature_vectors.T)
eig_vals, eig_vecs = np.linalg.eig(cov_matrix)
# 选择前k个特征向量
k = 10
self.eig_vecs_k = eig_vecs[:, :k]
def select_file(self):
# 打开文件选择对话框
file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.jpg;*.jpeg;*.png;*.bmp")])
# 显示选择的图像
img = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (400, 400))
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
img = cv2.transpose(img)
img = cv2.flip(img, 1)
self.img = img
self.display_image(img)
def display_image(self, img):
# 显示图像到画布
img_tk = self.get_image_tk(img)
self.canvas.create_image(0, 0, anchor="nw", image=img_tk)
def get_image_tk(self, img):
# 转换图像格式为tkinter可用的格式
height, width, channels = img.shape
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_pil = Image.fromarray(img_rgb)
img_tk = ImageTk.PhotoImage(img_pil)
return img_tk
def recognize_face(self):
# 将选择的图像转换成特征向量
img_gray = cv2.cvtColor(self.img, cv2.COLOR_RGB2GRAY)
img_gray_flatten = img_gray.flatten()
img_feature_vector = img_gray_flatten - self.mean_face
img_feature_vector = img_feature_vector.reshape(1, -1)
# 计算特征向量的投影
img_projected = np.dot(img_feature_vector, self.eig_vecs_k)
# 计算所有人脸图像的投影
faces_projected = np.dot(self.feature_vectors, self.eig_vecs_k)
# 计算与选择的图像最近的人脸图像
min_distance = np.inf
min_index = -1
for i in range(len(faces_projected)):
distance = np.linalg.norm(faces_projected[i] - img_projected)
if distance < min_distance:
min_distance = distance
min_index = i
# 显示识别结果
recognized_face = self.faces[min_index]
recognized_face = recognized_face.reshape((400, 400))
recognized_face = cv2.cvtColor(recognized_face, cv2.COLOR_GRAY2RGB)
recognized_face = cv2.transpose(recognized_face)
recognized_face = cv2.flip(recognized_face, 1)
self.display_image(recognized_face)
if __name__ == "__main__":
app = App()
app.mainloop()
```
该GUI程序使用PCA进行人脸识别,可以选择本地的人脸图像文件,然后对其进行识别并显示识别结果。在程序运行之前需要将人脸图像数据保存为`faces.npy`文件。
阅读全文