1.导包
import tkinter as tk
from tkinter import filedialog
import cv2
from PIL import Image, ImageTk
from keras.models import load_model
import numpy as np
2.创建主窗口
# 主窗口
root = tk.Tk()
root.title("表情识别系统")
root. Geometry("600x450")
3.加载预训练的模型
model = load_model("D:/sdxx/DATASET/trained_model.h5")
4.定义好人脸表情的标签
# 定义情绪标签
emotion_labels = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']
4.1 人脸表情识别函数
# 人脸表情识别函数
def recognize_emotion(img):
# 对图像进行预处理
img = img.resize((150, 150))
img = np.expand_dims(np.array(img), axis=0)
img = img / 255.0 # 归一化
# 使用模型进行预测
prediction = model.predict(img)[0]
# 获取最高概率的情绪
max_index = np.argmax(prediction)
emotion = emotion_labels[max_index]
probability = prediction[max_index]
# 返回情绪和概率
return emotion, probability
# 更新情绪标签
def update_emotion_labels(emotion, probability):
emotion_label.config(text=f"情绪: {emotion} - 概率: {probability:.2f}")
# 创建情绪显示标签
emotion_label = tk.Label(root, text="情绪: - 概率: ")
emotion_label.pack(side="right", padx=10, pady=10)
# 创建图像显示区域
image_label = tk.Label(root)
image_label.pack(pady=10)
4.2选择文件并识别
def select_file():
file_path = filedialog.askopenfilename()
if file_path:
image = Image.open(file_path)
emotion, probability = recognize_emotion(image)
# 更新情绪显示
update_emotion_labels(emotion, probability)
# 显示选择的图片