设置人脸检测模型:detection_model = ‘models/shape_predictor_68_face_landmarks.dat’
设置表情分类模型:classification_model = ‘models/model.hdf5’
设置表情分类标签:classification_labels = [‘anger’, ‘contempt’, ‘disgust’, ‘fear’, ‘happiness’, ‘neutral’, ‘sadness’, ‘surprise’]
rekognition(image):人脸表情检测函数
参数类型:被检测图像image
创建人脸识别对象:face_rekognition = FaceRekognition(detection_model)
创建表情识别对对象:emotion_rekognition = EmotionRekognition(classification_model, classification_labels)
识别图中人脸,遍历人脸进行表情识别与标识:face_details = [{‘BoundingBox’: face[‘BoundingBox’],‘Emotions’: emotion_rekognition.predict(face[‘FaceImage’])} for face in face_rekognition.predict(image)]
返回识别结果:return face_details
如果当前模块被主函数调用
if name == ‘main’:如果当前模块是否是被直接执行的
读取待检测图像路径:image_path = ‘images/test.jpg’
从该路径中读取图像:image_array = read_image(image_path)
进行人脸检测和表情检测:result = rekognition(image_array)
遍历所有识别结果:for item in result:
读取识别的表情:text = list(item[‘Emotions’].keys())[0]
在图像上绘制边界框:draw_bounding_box(box, image_array, (0, 0, 255))
在图像上绘制表情文本:draw_text(box, image_array, text, (0, 0, 255), 0, -20, 1, 2)
在图像上绘制人脸和表情信息:print(item)
显示处理后的图像:show_image(image_array)