實時 人臉表情識別 深度神經網絡


 

轉載:https://sefiks.com/2018/01/01/facial-expression-recognition-with-keras/

基於上次的內容,這節內容主要介紹如何利用攝像頭進行實時的人臉表情識別

(1)首先實時的檢測出人臉,然后把檢測出的人臉截取下來送到模型中去做判別。這里檢測人臉用到了opencv中自帶的人臉檢測器

import cv2
face_cascade = cv2.CascadeClassifier('C:/ProgramData/Anaconda3/envs/tensorflow/Library/etc/haarcascades/haarcascade_frontalface_default.xml')
img = cv2.imread('/data/friends.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #transform image to gray scale
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
#print(faces)
  cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.imshow('img',img)

(2)上邊是檢測靜態圖片的,檢測實時檢測人臉的方式是:

cap = cv2.VideoCapture(0)
while
cap.isOpened: ret,img = cap.read() #轉化為灰色圖片 gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #檢測人臉 faces = face_cascade.detectMultiScale(gray,1.3,5) #框出人臉 for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
   cv2.imshow("camera", img)

   if cv2.waitKey(30) & 0xFF == ord('q'):
      break
   cap.release()
   cv2.destroyAllWindows()

(3)檢測出人臉后,我們能夠得到人臉的上下左右坐標,然后根據坐標可截取到人臉。然后把截取到的人臉轉變為48*48的大小。

detected_face = img[int(y):int(y+h), int(x):int(x+w)] #crop detected face
detected_face = cv2.cvtColor(detected_face, cv2.COLOR_BGR2GRAY) #transform to gray scale
detected_face = cv2.resize(detected_face, (48, 48)) #resize to 48x48

(4)表情識別,首先加載訓練好的模型和權重

from keras.models import model_from_json
model = model_from_json(open("facial_expression_model_structure.json", "r").read())
model.load_weights('facial_expression_model_weights.h5') #load weights

(5) 然后進行識別

img_pixels = image.img_to_array(detected_face)
img_pixels = np.expand_dims(img_pixels, axis = 0)
 
img_pixels /= 255
 
predictions = model.predict(img_pixels)
 
#find max indexed array
max_index = np.argmax(predictions[0])
 
emotions = ('angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral')
emotion = emotions[max_index]
 
cv2.putText(img, emotion, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2)

實驗結果:

    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM