Let’s code to identify your emotions.
Coding识别你的喜怒哀乐。
---《python情绪识别》.BY Andy
Emotions.png
一、原图
二、情绪识别结果
三、代码实现
'''
@filename:faceEmotions_image.py
'''
import dlib #人脸识别的库dlib
import numpy as np #数据处理的库numpy
import cv2 #图像处理的库OpenCv
from skimage import io #>pip install scikit-image,scipy
class face_emotion():
def __init__(self):
# 使用特征提取器get_frontal_face_detector
self.detector = dlib.get_frontal_face_detector()
# dlib的68点模型,使用作者训练好的特征预测器
self.predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
def learning_face(self):
# 眉毛直线拟合数据缓冲
line_brow_x = []
line_brow_y = []
im_rd = cv2.imread("p4.jpg")
img_gray = cv2.cvtColor(im_rd, cv2.COLOR_RGB2GRAY)
faces = self.detector(img_gray, 0) # 检测到的人脸数
# 待会要显示在屏幕上的字体
font = cv2.FONT_HERSHEY_SIMPLEX
if(len(faces)!=0):
# 对每个人脸都标出68个特征点
for k, d in enumerate(faces):
cv2.rectangle(im_rd, (d.left(), d.top()),
(d.right(), d.bottom()), (0, 0, 255))
cv2.rectangle(im_rd, (d.left()-10, d.top()-10),
(d.right()+10, d.bottom()+10), (0, 255, 0))
# 用红色矩形框出人脸
cv2.rectangle(im_rd, (d.left(), d.top()), (d.right(), d.bottom()), (0, 0, 255))
# 计算人脸热别框边长
self.face_width = d.right() - d.left()
# 使用预测器得到68点数据的坐标
shape = self.predictor(im_rd, d)
# 圆圈显示每个特征点
for i in range(68):
cv2.circle(im_rd, (shape.part(i).x, shape.part(i).y), 2, (0, 255, 0), -1, 8)
#cv2.putText(im_rd, str(i), (shape.part(i).x, shape.part(i).y),
# cv2.FONT_HERSHEY_SIMPLEX, 0.3,(255, 255, 255))
# 分析任意n点的位置关系来作为表情识别的依据
mouth_width = (shape.part(54).x - shape.part(48).x) / self.face_width # 嘴巴咧开程度
mouth_higth = (shape.part(66).y - shape.part(62).y) / self.face_width # 嘴巴张开程度
#