這篇文章主要介紹了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()