ADD file via upload

This commit is contained in:
p74035216 2023-11-22 23:33:06 +08:00
parent 2116671ef6
commit 713d417ce2
1 changed files with 59 additions and 0 deletions

59
预测表情(main).py Normal file
View File

@ -0,0 +1,59 @@
import numpy as np
import cv2
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D
from keras.optimizers import Adam
from keras.layers import MaxPooling2D
from keras.models import Sequential
# 照片路径
train_dir = 'D:\\my\\college\\31\\machinelearning\\archive\\train'
val_dir = 'D:\\my\\college\\31\\machinelearning\\archive\\test'
# 把灰度值从0-255映射到0-1
train_datagen = ImageDataGenerator(rescale=1./255)
val_datagen = ImageDataGenerator(rescale=1./255)
# 图像增强
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(48,48),
batch_size=64,
color_mode="grayscale",
class_mode='categorical')
validation_generator = val_datagen.flow_from_directory(
val_dir,
target_size=(48,48),
batch_size=64,
color_mode="grayscale",
class_mode='categorical')
emotion_model = Sequential()
emotion_model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48,48,1)))
emotion_model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
emotion_model.add(Dropout(0.25))
emotion_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
emotion_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
emotion_model.add(Dropout(0.25))
emotion_model.add(Flatten())
emotion_model.add(Dense(1024, activation='relu'))
emotion_model.add(Dropout(0.5))
emotion_model.add(Dense(7, activation='softmax'))
emotion_model.load_weights('emotion_model.h5')
frame = cv2.imread('angry1.jpg')
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cropped_frame = np.expand_dims(np.expand_dims(cv2.resize(gray_frame, (48, 48)), -1), 0)
emotion_prediction = emotion_model.predict(cropped_frame)
maxindex = int(np.argmax(emotion_prediction))
emotion_dict = {0: "Angry", 1: "Disgusted", 2: "Fearful", 3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"}
print(emotion_dict[maxindex])