用python编写一个有录入人脸和人脸识别的用户界面
时间: 2024-05-03 08:18:55 浏览: 183
首先,需要安装以下库:OpenCV、face_recognition、tkinter、Pillow。
然后,可以按照以下步骤编写代码:
1. 导入所需库
```python
import cv2
import face_recognition
import tkinter as tk
from PIL import Image, ImageTk
```
2. 创建用户界面
```python
# 创建主窗口
root = tk.Tk()
root.title("人脸识别")
# 创建画布
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
# 创建按钮
btn_capture = tk.Button(root, text="录入人脸")
btn_capture.pack(side=tk.LEFT)
btn_recognize = tk.Button(root, text="人脸识别")
btn_recognize.pack(side=tk.RIGHT)
# 进入消息循环
root.mainloop()
```
3. 编写录入人脸的函数
```python
def capture_face():
# 打开摄像头
cap = cv2.VideoCapture(0)
# 循环读取摄像头数据,直到按下 Esc 键
while True:
ret, frame = cap.read()
# 显示当前帧
cv2.imshow("capture", frame)
# 按下 Esc 键退出
if cv2.waitKey(1) == 27:
break
# 释放摄像头
cap.release()
cv2.destroyAllWindows()
# 保存人脸图像
cv2.imwrite("face.jpg", frame)
# 提示保存成功
tk.messagebox.showinfo("提示", "人脸录入成功!")
```
4. 编写人脸识别的函数
```python
def recognize_face():
# 加载已录入的人脸图像
known_image = face_recognition.load_image_file("face.jpg")
known_encoding = face_recognition.face_encodings(known_image)[0]
# 打开摄像头
cap = cv2.VideoCapture(0)
# 循环读取摄像头数据,直到按下 Esc 键
while True:
ret, frame = cap.read()
# 查找当前帧中的人脸
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)
# 遍历每一张人脸,进行识别
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# 与已录入的人脸进行比对
matches = face_recognition.compare_faces([known_encoding], face_encoding)
# 如果匹配成功,标记为已识别
if matches[0]:
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, "已识别", (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 显示当前帧
cv2.imshow("recognize", frame)
# 按下 Esc 键退出
if cv2.waitKey(1) == 27:
break
# 释放摄像头
cap.release()
cv2.destroyAllWindows()
```
5. 将函数与按钮绑定
```python
btn_capture.config(command=capture_face)
btn_recognize.config(command=recognize_face)
```
完整代码如下:
阅读全文