import cv2
import torch
import numpy as np
from statistics import mode
import image_standardization as isd
from model_CNN import MyCNN
from model_CNN import CNN
detection_model_path = 'trained_model/haarcascade_frontalface_default.xml'
model_path = 'trained_model/model_CNN.pkl'
face_detection = cv2.CascadeClassifier(detection_model_path)
detection_model = torch.load(model_path, map_location=torch.device('cpu'))
frame_window = 10
emotion_labels = {0: 'angry', 1: 'disgust', 2: 'fear', 3: 'happy', 4: 'sad', 5: 'surprise', 6: 'neutral'}
emotion_window = []
video_capture = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.startWindowThread()
cv2.namedWindow('window_frame')
while True:
# 读取一帧
_, frame = video_capture.read()
frame = frame[:, ::-1, :] # 水平翻转,符合自拍习惯
frame = frame.copy()
# 获得灰度图,并且在内存中创建一个图像对象
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 获取当前帧中的全部人脸
faces = face_detection.detectMultiScale(gray, 1.3, 5)
# 对于所有发现的人脸
for (x, y, w, h) in faces:
# 在脸周围画一个矩形框,(255,0,0)是颜色,2是线宽
cv2.rectangle(frame, (x, y), (x + w, y + h), (84, 255, 159), 2)
# 获取人脸图像
face = gray[y:y + h, x:x + w]
face = cv2.resize(face, (48, 48))
# 扩充维度,转换成为(1,1,48,48)
face = np.expand_dims(face, 0)
face = np.expand_dims(face, 0)
# 人脸数据归一化,将像素值从0-255映射到0-1之间
face = isd.preprocess_input(face)
new_face = torch.from_numpy(face)
new_new_face = new_face.float().requires_grad_(False)
# 调用我们训练好的表情识别模型,预测分类
# np.argmax()是numpy中获取array的某一个维度中数值最大的那个元素的索引
# emotion_arg得到的是一个数字,按照表情顺序排好的数字
emtion_all_proprobability = detection_model.forward(new_new_face).detach().numpy()
emotion_arg = np.argmax(emtion_all_proprobability)
# 获取数字对应的表情
emotion = emotion_labels[emotion_arg]
emotion_window.append(emotion)
if len(emotion_window) >= frame_window:
emotion_window.pop(0)
try:
# 获得出现次数最多的分类
emotion_mode = mode(emotion_window)
except:
continue
# 在矩形框上部,输出分类文字
cv2.putText(frame, emotion_mode, (x, y - 30), font, .7, (0, 0, 255), 1, cv2.LINE_AA)
try:
# 将图片从内存中显示到屏幕上
cv2.imshow('window_frame', frame)
except:
continue
# 按q退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()这段代码出现了上述错误我应该如何修改