CV之FR:基于Keras框架利用训练好的hdf5模型直接进行人脸识别推理(cv2自带两步检测法)实现对《跑男第六季第五期》之如花视频片段(或调用摄像头)进行实时性别、脸部表情识别

28 篇文章 9 订阅

CV之FR:基于Keras框架利用训练好的hdf5模型直接进行人脸识别推理(cv2自带两步检测法)实现对《跑男第六季第五期》之如花视频片段(或调用摄像头)进行实时性别、脸部表情识别

目录

基于Keras框架利用训练好的hdf5模型直接进行人脸识别推理(cv2自带两步检测法)实现对《跑男第六季第五期》之如花视频片段(或调用摄像头)进行实时性别、脸部表情识别

输出结果

设计思路

核心代码


基于Keras框架利用训练好的hdf5模型直接进行人脸识别推理(cv2自带两步检测法)实现对《跑男第六季第五期》之如花视频片段(或调用摄像头)进行实时性别、脸部表情识别

输出结果

设计思路

核心代码

from statistics import mode

import cv2
from keras.models import load_model
import numpy as np


detection_model_path = '../trained_models/detection_models/haarcascade_frontalface_default.xml'

emotion_model_path = '../trained_models/emotion_models/fer2013_mini_XCEPTION.102-0.66.hdf5'
gender_model_path = '../trained_models/gender_models/simple_CNN.81-0.96.hdf5'
emotion_labels = get_labels('fer2013')
gender_labels = get_labels('imdb')
font = cv2.FONT_HERSHEY_SIMPLEX

frame_window = 10  
gender_offsets = (30, 60) 
emotion_offsets = (20, 40)

face_detection = load_detection_model(detection_model_path)
emotion_classifier = load_model(emotion_model_path, compile=False)
gender_classifier = load_model(gender_model_path, compile=False)

emotion_target_size = emotion_classifier.input_shape[1:3]
gender_target_size = gender_classifier.input_shape[1:3]

gender_window = []
emotion_window = []

cv2.namedWindow('window_frame_by_Jason_Niu')
# video_capture = cv2.VideoCapture(0)
video_capture = cv2.VideoCapture("F:\File_Python\Python_example\YOLOv3_use_TF\RunMan5.mp4") 
while True:

    bgr_image = video_capture.read()[1]
    gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY) #分别将读取的图像进行灰化、RGB化处理
    rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
    faces = detect_faces(face_detection, gray_image)  
    for face_coordinates in faces:
     
        x1, x2, y1, y2 = apply_offsets(face_coordinates, gender_offsets) 
        rgb_face = rgb_image[y1:y2, x1:x2]  

        x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)
        gray_face = gray_image[y1:y2, x1:x2]
        try:
            rgb_face = cv2.resize(rgb_face, (gender_target_size))
            gray_face = cv2.resize(gray_face, (emotion_target_size))
        except:
            continue
        gray_face = preprocess_input(gray_face, False)  
        gray_face = np.expand_dims(gray_face, 0)  
        gray_face = np.expand_dims(gray_face, -1)

        emotion_label_arg = np.argmax(emotion_classifier.predict(gray_face)) 
        emotion_text = emotion_labels[emotion_label_arg] 
        emotion_window.append(emotion_text)     

        rgb_face = np.expand_dims(rgb_face, 0)
        rgb_face = preprocess_input(rgb_face, False)
        gender_prediction = gender_classifier.predict(rgb_face) 
        gender_label_arg = np.argmax(gender_prediction)
        gender_text = gender_labels[gender_label_arg]
        gender_window.append(gender_text)

        if len(gender_window) > frame_window: 
            emotion_window.pop(0)         
            gender_window.pop(0)
        try:
            emotion_mode = mode(emotion_window)
            gender_mode = mode(gender_window)
        except:
            continue

        if gender_text == gender_labels[0]:
            color = (0, 0, 255)
        else:
            color = (255, 0, 0)

        draw_bounding_box(face_coordinates, rgb_image, color) 
        draw_text(face_coordinates, rgb_image, gender_mode,   
                  color, 0, -20, 1, 4)
        draw_text(face_coordinates, rgb_image, emotion_mode,
                  color, 0, -45, 1, 4)
        

    bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)  
    cv2.namedWindow("window_frame_by_Jason_Niu",0);
    cv2.resizeWindow("window_frame_by_Jason_Niu", 640, 380);
    cv2.imshow('window_frame_by_Jason_Niu', bgr_image)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一段基于Keras框架的代码,使用LSTM模型对CSV文件的第一列进行预测,并打印出训练过程中使用的权重矩阵: ```python import pandas as pd import numpy as np from keras.models import Sequential from keras.layers import Dense, LSTM from keras.callbacks import ModelCheckpoint # 读取CSV文件 dataframe = pd.read_csv('data.csv', usecols=[0], engine='python') dataset = dataframe.values dataset = dataset.astype('float32') # 数据归一化 max_value = np.max(dataset) min_value = np.min(dataset) scalar = max_value - min_value dataset = list(map(lambda x: x / scalar, dataset)) # 构造训练数据 def create_dataset(dataset, look_back=1): dataX, dataY = [], [] for i in range(len(dataset)-look_back): a = dataset[i:(i+look_back)] dataX.append(a) dataY.append(dataset[i + look_back]) return np.array(dataX), np.array(dataY) look_back = 10 trainX, trainY = create_dataset(dataset, look_back) # 将训练数据重构为LSTM的输入格式 trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1)) # 构建LSTM模型 model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(trainX.shape[1], 1))) model.add(LSTM(units=50)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') # 设置回调函数保存权重 filepath="weights.best.hdf5" checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min') callbacks_list = [checkpoint] # 训练模型 model.fit(trainX, trainY, epochs=100, batch_size=64, callbacks=callbacks_list) # 打印权重矩阵 for layer in model.layers: weights = layer.get_weights() print(weights) ``` 需要注意的是,此代码中使用了LSTM模型对时间序列数据进行预测,其中`look_back`参数用于指定前多少个时间步作为输入预测下一个时间步的值。`ModelCheckpoint`回调函数用于在训练过程中保存最好的权重矩阵,以便在预测时使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个处女座的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值