还记得我们之前写过一篇文章《手把手教你人脸识别自动开机》吗?其中,利用OpenCV进行简单的人脸识别,从而训练计算机识别特定的人,进而识别物体。今天,让我们做一些高级的事情,识别人脸的情绪。本文分为两部分:1.人脸检测:检测图像的人脸位置,并输出边界框坐标2.情绪检测:将人脸的情绪分为高兴、愤怒、悲伤、中性、惊讶,厌恶和恐惧。1、人脸检测可以使用上篇文章(《手把手教你人脸识别自动开机》)中提到的方法——使用openCV检测,或者使用face_recognition项目,实现人脸检测非常简单。这里我们尝试face_recognition项目,face_recognition安装:Face_recognition需要一个叫dlib的包,可能无法通过pip安装,所以这里推荐大家使用anaconda安装dlib:condainstall-cconda-forgedlib然后安装Face_recognition:pipinstallface_recognition使用face_recognition三行代码识别图片中的人脸:importface_recognitionimage=face_recognition.load_image_file("1.png")face_locations=face_recognition.face_locations(image)2.情感检测文字提示,电脑也可以吗?答案是肯定的,但它需要经过训练才能识别情绪。今天我们不太可能谈论收集数据和构建CNN模型等逻辑过程。我们直接使用priya-dwivedi训练的模型,他用Kaggle开源数据集(FaceEmotionRecognitionFER)训练了一个六层卷积神经网络模型。现在调用模型识别这张图片中孙哥的情绪:importface_recognitionimportnumpyasnpimportcv2fromkeras.modelsimportload_modelemotion_dict={'angry':0,'sad':5,'neutral':4,'Disgust':1,'surprise':6,'fear':2,'happy':3}image=face_recognition.load_image_file("1.png")#loadimageface_locations=face_recognition.face_locations(image)#找人脸处top,right,bottom,left=face_locations[0]#framethefaceface_image=image[top:bottom,left:right]face_image=cv2.resize(face_image,(48,48))face_image=cv2.cvtColor(face_image,cv2.COLOR_BGR2GRAY)face_image人脸图像=np.reshape(face_image,[1,face_image.shape[0],face_image.shape[1],1])#调整为可以进入模型输入的大小model=load_model("./model_v6_23.hdf5")#加载模型predicted_class=np.argmax(model.predict(face_image))#分类情感label_map=dict((v,k)fork,vinemotion_dict.items())predicted_label=label_map[predicted_class]#输出情感print(预测cted_label)根据情绪映射表得到的结果:$pythonemotion.pyhappy从下面终端的输出结果可以看出孙哥现在心情很开心,这个结果应该是正确的(毕竟孙哥还是和他说的一样)的)。虽然简单,但还是建议有兴趣的同学从头到尾尝试一下。过程中会遇到很多坑,百度谷歌慢慢解决。文章到此结束。如果喜欢今天的Python教程,请继续关注Python实战宝典。如果对您有帮助,请点击下方的赞/观看。如果您有任何问题,可以在下方留言区留言。我们会耐心解答!Python实战宝典(pythondict.com)不只是一个合集欢迎关注公众号:Python实战宝典原文来自Python实战宝典:Python面部表情识别
