本模型可以检测7种表情,分别是:生气、厌恶、害怕、开心、难过、惊奇、中立

另外还可以检测性别

文章来自我的CSDN博客:https://blog.csdn.net/m0_43505377/article/details/95765279

一、环境

建议安装 Anconda

Anconda 官网:Home - Anaconda

系统环境建议:

windows、ubuntu

环境建议:

python 3.6

tensorflow-gpu 1.13

keras-gpu 2.24

所需包建议(版本影响不大):

statistics

pandas== 0.19.1

numpy== 1.12.1

h5py== 2 .7.0

opencv-python==3.2.0

注意:如果运行中缺少了一谢基本包可直接pip安装即可

如:pip install scipy 

后面可加上: -i https://pypi.tuna.tsinghua.edu.cn/simple 加快下载速度

如:pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple

在anconda 中一键安装也是可以的哦!

二、代码文件:

我就不卖官子啦!直接放源代码文件咯(有环境可以直接运行的那种)!

代码文件中我放了大量的注释,对python有一点基础的很快就可以简单理解!链接:

链接: https://pan.baidu.com/s/1p34bPoQ-21oReiA_ZnXQTQ 提取码: 67rh

三、代码文件解析

解压后有3个文件

第一个文件是存放模型的文件夹(可以自行切换模型)

第二个是基础模块文件夹

第三个是主文件,环境安装完成后可直接运行检测模型

主文件(emotion_sex_recognition.py)

from statistics import modeimport cv2
from keras.models import load_model
import numpy as npfrom utils_base.datasets import get_labels
from utils_base.inference import detect_faces
from utils_base.inference import draw_text
from utils_base.inference import draw_bounding_box
from utils_base.inference import apply_offsets
from utils_base.inference import load_detection_model
from utils_base.preprocessor import preprocess_inputimport threading
from urllib import parse,request#这是数据传输模块,没有需要的时候不需要使用
def swop(emotion,name,sex,age,gl):values={"id":name,"number":emotion}data=parse.urlencode(values)try:url = 'http://127.0.0.1.ngrok.xiaomiqiu.cn/saw_2'req = request.Request(url, data.encode(encoding='utf-8'))print("服务器接入成功,数据成功传输!")except:print("服务器接入失败,数据将临时保存")# 加载数据和图像的参数
detection_model_path = 'models/detection_models/haarcascade_frontalface_default.xml'
emotion_model_path = 'models/emotion_models/fer2013_mini_XCEPTION.110-0.65.hdf5'
gender_model_path = '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')#连接网络摄像头识别
video_capture = cv2.VideoCapture(0)while True:bgr_image = video_capture.read()[1]#图像模式的转换gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)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_prediction = emotion_classifier.predict(gray_face)#寻找可能性最大的表情emotion_probability = np.max(emotion_prediction)emotion_label_arg = np.argmax(emotion_prediction)print("表情种类:",emotion_label_arg)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)print("性别:",gender_label_arg)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 emotion_text == 'angry':color = emotion_probability * np.asarray((255, 0, 0))elif emotion_text == 'sad':color = emotion_probability * np.asarray((0, 0, 255))elif emotion_text == 'happy':color = emotion_probability * np.asarray((255, 255, 0))elif emotion_text == 'surprise':color = emotion_probability * np.asarray((0, 255, 255))else:color = emotion_probability * np.asarray((0, 255, 0))color = color.astype(int)color = color.tolist()#图像上绘制边框。draw_bounding_box(face_coordinates, rgb_image, color)gender_mode=gender_mode+"  "+"<No entry>"#打印在图片上draw_text(face_coordinates, rgb_image, gender_mode,color, 0, -20, 1, 1)#显示识别相似度百分比emotion_probability=int(emotion_probability*100)emotion_mode=emotion_mode+" "+str(emotion_probability)+"%"#显示视频帧率fps = "fps:"+str(video_capture.get(cv2.CAP_PROP_FPS))cv2.putText(rgb_image, fps, (5, 25), cv2.FONT_HERSHEY_DUPLEX, 0.9, (0, 255, 0), 0)draw_text(face_coordinates, rgb_image, emotion_mode,color, 0, -45, 1, 1)#输出部分数据demo=fps+"--"+emotion_mode+"--"+gender_modeprint(demo)#开启多线程传输数据,默认屏蔽#  thread1=threading.Thread(target=swop,args=(emotion_label_arg,j, gender_label_arg, 18, emotion_probability))#  thread1.start()bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)bgr_image = cv2.resize(bgr_image, dsize=(1280, 720))cv2.imshow('window_frame', bgr_image)if cv2.waitKey(1) & 0xFF == ord('q'):break
video_capture.release()
cv2.destroyAllWindows()

基础模块文件(inference.py)

import cv2
import matplotlib.pyplot as plt
import numpy as np
from keras.preprocessing import image#装载模型
def load_detection_model(model_path):detection_model = cv2.CascadeClassifier(model_path)return detection_model#查找脸部
def detect_faces(detection_model, gray_image_array):return detection_model.detectMultiScale(gray_image_array, 1.2, 4)#3个参数,第一个参数是查找的图像#第2个是脸部最小的大小#第3个是检测到几次才确定是人脸,与准确率直接挂钩#画出脸部矩形
def draw_bounding_box(face_coordinates, image_array, color):x, y, w, h = face_coordinatescv2.rectangle(image_array, (x, y), (x + w, y + h), color, 2)#确定脸的矩形位置
def apply_offsets(face_coordinates, offsets):x, y, width, height = face_coordinatesx_off, y_off = offsetsreturn (x - x_off, x + width + x_off, y - y_off, y + height + y_off)#文字打印在图片上
def draw_text(coordinates, image_array, text, color, x_offset=0, y_offset=0,font_scale=2, thickness=2):x, y = coordinates[:2]cv2.putText(image_array, text, (x + x_offset, y + y_offset),cv2.FONT_HERSHEY_SIMPLEX,font_scale, color, thickness, cv2.LINE_AA)
#颜色
def get_colors(num_classes):colors = plt.cm.hsv(np.linspace(0, 1, num_classes)).tolist()colors = np.asarray(colors) * 255return colors

序号对于名称文件(datasets.py)

#表情序号对应的表情
def get_labels(dataset_name):if dataset_name == 'fer2013':return {0: 'angry', 1: 'disgust', 2: 'fear', 3: 'happy',4: 'sad', 5: 'surprise', 6: 'neutral'}elif dataset_name == 'imdb':return {0: 'woman', 1: 'man'}elif dataset_name == 'KDEF':return {0: 'AN', 1: 'DI', 2: 'AF', 3: 'HA', 4: 'SA', 5: 'SU', 6: 'NE'}else:raise Exception('Invalid dataset name')

标准化(preprocessor.py)

import numpy as np
from scipy.misc import imread, imresizedef preprocess_input(x, v2=True):x = x.astype('float32')x = x / 255.0if v2:x = x - 0.5x = x * 2.0return x
#标准化

我是站在巨人的肩膀上的:

python利用tensorflow识别图形_表情识别与性别识别 实时识别模型附源代码 基于python的tensorflow与keras...相关推荐

  1. python打代码运行图形_利用aardio给python编写图形界面

    前阵子在用python写一些小程序,写完后就开始思考怎么给python程序配一个图形界面,毕竟控制台实在太丑陋了. 于是百度了下python的图形界面库,眼花缭乱的一整页,拣了几件有"特色& ...

  2. python绘制二维图形_使用python绘制二维图形示例

    我就废话不多说了,直接上代码吧! import matplotlib.pyplot as plt #也可以使用 import pylab as pl import matplotlib.font_ma ...

  3. python免费开源工具推荐_年薪200万的程序员,推荐这10大Python免费开源工具!

    原标题:年薪200万的程序员,推荐这10大Python免费开源工具! 毫无疑问,Python是最流行的语言之一,其成功的原因之一是它为科学计算提供了广泛的报道. 在这里,我们仔细研究用于机器学习和数据 ...

  4. python免费开源工具推荐_年薪200万的程序员,推荐的10大Python开源免费工具!

    原标题:年薪200万的程序员,推荐的10大Python开源免费工具! 毫无疑问,Python是最流行的语言之一,其成功的原因之一是它为科学计算提供了广泛的报道. 在这里,我们仔细研究用于机器学习和数据 ...

  5. python命令窗口在哪里_详解如何在cmd命令窗口中搭建简单的python开发环境

    详解如何在cmd命令窗口中搭建简单的python开发环境 1.快捷键win+r输入cmd回车调出cmd界面,在命令行输入python回车,显示python命令无法识别 2.登陆python官网http ...

  6. 计算机识别检测,从猫狗不分到实时识别准确率超过99%,计算机图像识别是如何做到的?...

    原标题:从猫狗不分到实时识别准确率超过99%,计算机图像识别是如何做到的? [导读] 十年前,研究人员认为让计算机来区分猫和狗几乎是不可能的.如今,计算机视觉识别的准确率已超过99%.Joseph R ...

  7. python绘图内容怎么保存_将绘图保存到图像文件,而不是使用Matplotlib显示 - python...

    我正在编写一个快速脚本来动态生成绘图.我使用下面的代码(来自Matplotlib文档)作为起点: from pylab import figure, axes, pie, title, show # ...

  8. Python wxpython篇 | Python生态库之图形用户界面开发库 “wxPython “ 的安装及使用(附. 使用pyinstaller 库打包Python随机点名小程序程序.exe文件)

    全文目录 wxPython 图形用户界面 PyCharm 中安装 wxPython库 PyCharm中将程序打包成 .exe 可执行文件 wxPython 的使用 第一个wxPython 程序 自定义 ...

  9. python海量数据分析师_数据分析师真的月入过万吗?(基于Python的招聘数据分析全流程实操)...

    0 前言 作为一名数据分析小白,经过一轮融汇贯穿学习后,也迫不及待想做一份数据分析报告,于是选取了现阶段最感兴趣的数据分析相关岗位招聘信息进行一波数据分析. 1 理解问题确定分析的目的和方向 因为目前 ...

  10. 决策树留一法python代码_机器学习模型2 决策树-基于Python sklearn的实现

    1.模型原理 (一)原理 1.原理:引入信息熵(不确定程度)的概念,通过计算各属性下的信息增益程度(信息增益越大,则意味着使用该属性来进行划分所获得的"纯度提升"越大),增益程度最 ...

最新文章

  1. 服务器不显示磁盘柜,磁盘柜与服务器的关系
  2. Linux学习:第二章-Linux安装
  3. python迷宫求解代码_Python中的迷宫求解
  4. JavaScript 中的 require / exports、import / export、浅谈JavaScript、ES5、ES6
  5. Div+CSS布局入门教程(二) 写入整体层结构与CSS
  6. 为什么大厂都在用 GO 语言?读透 GO 语言的切片
  7. 两款优质的Mac读写ntfs软件推荐
  8. Java——包装器类
  9. access2016访问mysql_关于VB连接access2016数据库
  10. 《鸟哥的Linux私房菜》简评
  11. python基础教程ppt下载_python基础分享ppt
  12. 超市扫码机器服务器系统搭建,超市用的扫码机是怎么个原理?
  13. 启动solidworks时显示VBE6EXT.OLB不能被加载
  14. nginx proxy_temp 文件夹权限问题
  15. 计算英文句子中有多少单词?
  16. Project-Euler-045思维
  17. Matlab读取二进制数据文件
  18. 22-3-批量对excel文件重命名
  19. 如何减少http请求
  20. 需求分析中适应性怎么写_需求文档,怎么写才不会被打?

热门文章

  1. 记录一次es写入操作
  2. java面试题 垃圾回收机制 GC BAT面试题系列 基础篇(十四)
  3. springmvc并发调用controller方法时对局部变量的影响
  4. 利用Samba搭建Backup Server配置文件
  5. 【随机数】深入理解random和srandom
  6. Date 当前程序日期格式 参数设置 DecimalSeparator
  7. C++对二进制文件的操作实例
  8. 自定义Button按钮
  9. 解决精简版的XP下,无法使用运程桌面
  10. 含有REF CURSOR 的过程只能有一个out参数?