-
Notifications
You must be signed in to change notification settings - Fork 0
/
real-time detection.py
70 lines (54 loc) · 2.34 KB
/
real-time detection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import os
import cv2
import numpy as np
import tensorflow as tf
from keras.models import model_from_json
from keras.preprocessing import image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
model = model_from_json(open("fer.json", "r").read())
model.load_weights('fer.h5')
face_haar_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap=cv2.VideoCapture(0) #select the default video capture
#If the camera was not opened sucessfully
if not cap.isOpened():
print("Cannot open camera")
exit()
#Continously read the frames
while True:
#read frame by frame and get return whether there is a stream or not
ret, frame=cap.read()
#If no frames recieved, then break from the loop
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
#Change the frame to greyscale
gray_image= cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#We pass the image, scaleFactor and minneighbour
faces_detected = face_haar_cascade.detectMultiScale(gray_image,1.32,5)
#Draw Triangles around the faces detected
for (x,y,w,h) in faces_detected:
cv2.rectangle(frame,(x,y), (x+w,y+h), (255,0,0), thickness=7)
roi_gray=gray_image[y:y+w,x:x+h]
roi_gray=cv2.resize(roi_gray,(48,48))
#Processes the image and adjust it to pass it to the model
image_pixels = tf.keras.preprocessing.image.img_to_array(roi_gray)
plt.imshow(image_pixels)
plt.show()
image_pixels = np.expand_dims(image_pixels, axis = 0)
image_pixels /= 255
#Get the prediction of the model
predictions = model.predict(image_pixels)
print(predictions)
max_index = np.argmax(predictions[0])
emotion_detection = ('angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral')
emotion_prediction = emotion_detection[max_index]
print(emotion_prediction)
#Write on the frame the emotion detected
cv2.putText(frame,emotion_prediction,(int(x), int(y)),cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),3)
resize_image = cv2.resize(frame, (1000, 700))
cv2.imshow('Emotion',resize_image)
if cv2.waitKey(10) == ord('b'):
break
cap.release()
cv2.destroyAllWindows