这篇文章主要介绍了python 实现表情识别的示例代码,帮助大家更好的理解和学习python,感兴趣的朋友可以了解下
表情识别
表情识别支持7种表情类型,生气、厌恶、恐惧、开心、难过、惊喜、平静等。
实现思路
使用OpenCV识别图片中的脸,在使用keras进行表情识别。
效果预览
实现代码
1 #coding=utf-8 2 #表情识别 3 4 import cv2 5 from keras.models import load_model 6 import numpy as np 7 import chineseText 8 import datetime 9 10 startTime = datetime.datetime.now() 11 emotion_classifier = load_model( 12 'classifier/emotion_models/simple_CNN.530-0.65.hdf5') 13 endTime = datetime.datetime.now() 14 print(endTime - startTime) 15 16 emotion_labels = { 17 0: '生气', 18 1: '厌恶', 19 2: '恐惧', 20 3: '开心', 21 4: '难过', 22 5: '惊喜', 23 6: '平静' 24 } 25 26 img = cv2.imread("img/emotion/emotion.png") 27 face_classifier = cv2.CascadeClassifier( 28 "C:\Python36\Lib\site-packages\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml" 29 ) 30 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 31 faces = face_classifier.detectMultiScale( 32 gray, scaleFactor=1.2, minNeighbors=3, minSize=(40, 40)) 33 color = (255, 0, 0) 34 35 for (x, y, w, h) in faces: 36 gray_face = gray[(y):(y + h), (x):(x + w)] 37 gray_face = cv2.resize(gray_face, (48, 48)) 38 gray_face = gray_face / 255.0 39 gray_face = np.expand_dims(gray_face, 0) 40 gray_face = np.expand_dims(gray_face, -1) 41 emotion_label_arg = np.argmax(emotion_classifier.predict(gray_face)) 42 emotion = emotion_labels[emotion_label_arg] 43 cv2.rectangle(img, (x + 10, y + 10), (x + h - 10, y + w - 10), 44 (255, 255, 255), 2) 45 img = chineseText.cv2ImgAddText(img, emotion, x + h * 0.3, y, color, 20) 46 47 cv2.imshow("Image", img) 48 cv2.waitKey(0) 49 cv2.destroyAllWindows()