本次讲述的表情分类是识别的分析流程分为:
- 1、加载pre-model网络与权重;
- 2、利用opencv的函数进行简单的人脸检测;
- 3、抠出人脸的图并灰化;
- 4、表情分类器检测
.
一、表情数据集
主要来源于kaggle比赛,下载地址。
有七种表情类别: (0=Angry, 1=Disgust, 2=Fear, 3=Happy, 4=Sad, 5=Surprise, 6=Neutral).
数据是48x48 灰度图,格式比较奇葩。
第一列是情绪分类,第二列是图像的numpy,第三列是train or test。
.
二、opencv的人脸识别
参考《opencv+Recorder︱OpenCV 中使用 Haar 分类器进行面部检测》
理论略过,直接来看重点:
(1)加载人脸检测器,haarcascade_frontalface_default.xml;
(2)图片加载并灰化,cvtColor,可参考: opencv︱图像的色彩空間cvtColor(HSV、HSL、HSB 、BGR)
(2)人脸探测,detectMultiScale.
cascPath = '/.../haarcascade_frontalface_default.xml'
faceCascade = cv2.CascadeClassifier(cascPath)
jpg_file = '/home/ubuntu/keras/image/8c80abb4gw1f3b5hxd3aaj20jg0cx411.jpg'
img_gray = cv2.imread(jpg_file)
img_gray = cv2.cvtColor(img_gray, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
img_gray,
scaleFactor=1.1,
minNeighbors=1,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
其中minNeighbors设置小一些,容易检测出来。这个检测器还是有点粗糙。
.
三、表情分类与识别
本节源自github的mememoji。
网络结构:
opencv中的人脸检测的pre-model文件(haarcascade_frontalface_default.xml)和表情识别pre-model文件(model.h5)都在作者的github下载。
是利用Keras实现的。直接来看完整的代码:
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']
json_file = open('/.../model.json','r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
model.load_weights('/.../model.h5')
def predict_emotion(face_image_gray):
resized_img = cv2.resize(face_image_gray, (48,48), interpolation = cv2.INTER_AREA)
image = resized_img.reshape(1, 1, 48, 48)
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]
img_gray = cv2.imread('/.../real-time_emotion_analyzer-master/meme_faces/angry-angry.png')
img_gray = cv2.cvtColor(img_gray, cv2.COLOR_BGR2GRAY)
angry, fear, happy, sad, surprise, neutral = predict_emotion(img_gray)
cascPath = '/.../real-time_emotion_analyzer-master/haarcascade_frontalface_default.xml'
faceCascade = cv2.CascadeClassifier(cascPath)
jpg_file = '/.../001.jpg'
img_gray = cv2.imread(jpg_file)
img_gray = cv2.cvtColor(img_gray, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
img_gray,
scaleFactor=1.1,
minNeighbors=1,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
for (x, y, w, h) in faces:
face_image_gray = img_gray[y:y+h, x:x+w]
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
angry, fear, happy, sad, surprise, neutral = predict_emotion(face_image_gray)
from:https://blog.csdn.net/sinat_26917383/article/details/72885715