人脸面部表情识别 keras实现(二)

人脸面部情绪识别(二)

人脸面部情绪识别 age&gender(三)

根据人脸预测年龄性别和情绪代码实现 (c++ + caffe)(四)

import cv2
import sys
import json
import time
import numpy as np

from keras.models import model_from_json


emotion_labels = ['angry', 'fear', 'happy', 'sad', 'surprise', 'neutral']

cascPath = sys.argv[1]

faceCascade = cv2.CascadeClassifier(cascPath)

# load json and create model arch
json_file = open('model.json','r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)

# load weights into new model
model.load_weights('model.h5')

def predict_emotion(face_image_gray): # a single cropped face
    resized_img = cv2.resize(face_image_gray, (48,48), interpolation = cv2.INTER_AREA)

    image = resized_img.reshape(1, 1, 48, 48)
    im = cv2.resize(resized_img,(90,100))
    cv2.imwrite('face.bmp', im)
    list_of_list = model.predict(image, batch_size=1, verbose=1)
    angry, fear, happy, sad, surprise, neutral = [prob for lst in list_of_list for prob in lst]
    return [angry, fear, happy, sad, surprise, neutral]

video_capture = cv2.VideoCapture(0)
while True:
    # Capture frame-by-frame
    ret, frame = video_capture.read()
    img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY,1)


    faces = faceCascade.detectMultiScale(
        img_gray,
        scaleFactor=1.1,
        minNeighbors=1,
        minSize=(30, 30),
        flags=cv2.CASCADE_SCALE_IMAGE

    )
    emotions = []
    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        face_image_gray = img_gray[y:y+h, x:x+w]
        angry, fear, happy, sad, surprise, neutral = predict_emotion(face_image_gray)
        emotions = [angry, fear, happy, sad, surprise, neutral]
        m = emotions.index(max(emotions))
        biaoqing = ""
        for index, val in enumerate(emotion_labels):
            if (m == index):
                biaoqing = val
                print(biaoqing)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        #cv2.putText(frame, biaoqing, (x, y),
        #           cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0),
        #           thickness=2, lineType=2)
        with open('emotion.txt', 'a') as f:
            f.write('{},{},{},{},{},{},{},{}\n'.format(time.time(),angry, fear, happy, sad, surprise, neutral,biaoqing))
    # Display the resulting frame
    cv2.imshow('Video', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

几个主要的东西

  1. 运行命令行 python real-time.py haarcascade_frontalface_default.xml
    加载haarcascade_frontalface_default.xml是haar分类器,用于检测人脸,别人训练好的

  2. 加载model.h5模型,这是用caffe训练的,用于表情预测

  3. model.json经过查看里面内容,就是别人将model通过keras保存为json格式,现在重新将json加载
  4. emotion.txt里面是结果,哪个值越大就是哪个。这仅仅是预测,但效果还是比(一)好很多哪个值越大就是哪个
  5. 整个源代码,包括模型从这里下载
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个使用基于卷积神经网络的深度学习方法实现人脸面部表情识别的项目源码(Python): ```python import os import numpy as np import pandas as pd import keras from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout # 数据集路径 base_dir = '/path/to/dataset' # 训练集、验证集、测试集路径 train_dir = os.path.join(base_dir, 'train') validation_dir = os.path.join(base_dir, 'validation') test_dir = os.path.join(base_dir, 'test') # 图像大小 img_size = 48 # 数据增强 train_datagen = ImageDataGenerator(rescale=1./255, rotation_range=30, width_shift_range=0.2, height_shift_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') validation_datagen = ImageDataGenerator(rescale=1./255) # 生成训练集、验证集、测试集数据 train_generator = train_datagen.flow_from_directory(train_dir, target_size=(img_size, img_size), batch_size=32, color_mode='grayscale', class_mode='categorical') validation_generator = validation_datagen.flow_from_directory(validation_dir, target_size=(img_size, img_size), batch_size=32, color_mode='grayscale', class_mode='categorical') test_generator = validation_datagen.flow_from_directory(test_dir, target_size=(img_size, img_size), batch_size=32, color_mode='grayscale', class_mode='categorical') # 构建模型 model = Sequential() model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(img_size, img_size, 1))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(128, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2))) model.add(Conv2D(128, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(7, activation='softmax')) # 编译模型 model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 训练模型 history = model.fit(train_generator, steps_per_epoch=train_generator.n // train_generator.batch_size, epochs=50, validation_data=validation_generator, validation_steps=validation_generator.n // validation_generator.batch_size) # 评估模型 test_loss, test_acc = model.evaluate(test_generator, verbose=2) # 保存模型 model.save('emotion_detection_model.h5') # 可视化训练过程 acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'bo', label='Training accuracy') plt.plot(epochs, val_acc, 'b', label='Validation accuracy') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() ``` 这个项目使用了Keras框架,通过构建一个基于卷积神经网络的模型来实现人脸面部表情识别。在代码中,我们使用了ImageDataGenerator对数据进行增强,从而提高模型的泛化能力。另外,我们还使用了训练集、验证集、测试集的方式来评估模型的性能。最终,我们将训练好的模型保存为'h5'格式的文件,并使用matplotlib可视化了训练过程中的准确率和损失函数的变化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值