脸识别热门,表情识别更加。但是表情识别很难,因为人脸的微表情很多,本节介绍一种比较粗线条的表情分类与识别的办法。
1、加载pre-model网络与权重;
2、利用opencv的函数进行简单的人脸检测;
3、抠出人脸的图并灰化;
4、表情分类器检测
有七种表情类别: (0=Angry, 1=Disgust, 2=Fear, 3=Happy, 4=Sad, 5=Surprise, 6=Neutral).
数据是48x48 灰度图,格式比较奇葩。
第一列是情绪分类,第二列是图像的numpy,第三列是train or test。
参考《opencv+Recorder︱OpenCV 中使用 Haar 分类器进行面部检测》
理论略过,直接来看重点:
(1)加载人脸检测器,haarcascade_frontalface_default.xml;
(2)图片加载并灰化,cvtColor,可参考: opencv︱图像的色彩空間cvtColor(HSV、HSL、HSB 、BGR)
(2)人脸探测,detectMultiScale.
# (1)加载人脸检测器
cascPath = '/.../haarcascade_frontalface_default.xml'
faceCascade = cv2.CascadeClassifier(cascPath)
# (2)图片加载并灰化
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,# minNeighbors=5比较难检测
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
其中minNeighbors设置小一些,容易检测出来。这个检测器还是有点粗糙。
本节源自github的mememoji。
网络结构:
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']
# 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)
# cv2.imwrite(str(index)+'.png', resized_img)
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,# minNeighbors=5比较难检测
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)