先看运行结果
首先导入我们需要的包
import tkinter as tk
from tkinter import filedialog
import cv2
from PIL import Image, ImageTk
from tkinter import messagebox
import subprocess
实例化窗口,命名,大小
win = tk.Tk()
win.title("人脸识别")
win.geometry("1500x800")
定义图片标签
我们用两个标签来显示图片
# 定义存放图片的标签
image_label_original = tk.Label(win)
image_label_original.pack(side=tk.LEFT,padx=10,pady=80)
image_label_detected = tk.Label(win)
image_label_detected.pack(side=tk.LEFT,padx=10,pady=80)
定义按钮
# 创建选择图片和识别人脸的按钮
tk.Button(win, text="选择图片", command=select_image,font=my_font,
fg='red').place(x=333,y=12)
tk.Button(win, text="识别人脸", command=detect_faces,font=my_font,
fg='red').place(x=666,y=12)
定义选择图片的函数
# 定义标量,用来储存用户选择图片的路径
selected_image_path = None
def select_image():
# 调用全局变量
global selected_image_path
# 打开文件选择对话框
selected_image_path = filedialog.askopenfilename()
# 使用OpenCV加载图片
img = cv2.imread(selected_image_path)
# 使用OpenCV的cvtColor函数将图像从BGR颜色空间转换为RGB颜色空间
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 使用PIL(Pillow)的Image类将numpy数组转换为PIL图像对象
img_pil = Image.fromarray(img_rgb)
# 将PIL图像对象转换为Tkinter可以显示的格式
img_tk = ImageTk.PhotoImage(image=img_pil)
# 显示原始图片
image_label_original.config(image=img_tk)
image_label_original.image = img_tk
定义检测人脸函数
def detect_faces():
global selected_image_path
# 判断路径是否有效
if selected_image_path:
# 使用OpenCV加载图片
img = cv2.imread(selected_image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 加载人脸识别模型
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# 判断是否检测到人脸
if len(faces) > 0:
# 在人脸周围画矩形框
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
# 转换为PIL格式并显示
img_rgb_detected = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_pil_detected = Image.fromarray(img_rgb_detected)
img_tk_detected = ImageTk.PhotoImage(image=img_pil_detected)
image_label_detected.config(image=img_tk_detected)
image_label_detected.image = img_tk_detected # keep a reference
else:
# 提示未检测到人脸
messagebox.showinfo("提示", "未检测到人脸")
else:
messagebox.showinfo("提示", "请先选择一张图片")
用按钮调用函数即可实现人脸识别
退出窗口和返回系统跟主界面函数一样
最后别忘了刷新窗口