sql / new.py
Garvitj's picture
Upload new.py
0cffb96 verified
raw
history blame
2.07 kB
#
import cv2
import numpy as np
import tensorflow as tf
# Load the face detector with the correct file path
face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Load the emotion model
emotion_dict = {0: "Angry", 1: "Disgusted", 2: "Fearful", 3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"}
emotion_model = tf.keras.models.load_model("model_emotion.h5")
emotion_model.load_weights("model_weights_new.h5")
print("Loaded emotion model from disk")
# Define the predict_img function
def predict_img(frame):
# Resize the image
frame = cv2.resize(frame, (1280, 720))
num_faces = face_detector.detectMultiScale(frame, scaleFactor=1.3, minNeighbors=5)
# Draw bounding boxes and annotate the image
for (x, y, w, h) in num_faces:
cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (0, 255, 0), 4)
roi_gray_frame = frame[y:y + h, x:x + w]
# Preprocess the input image
resized_img = cv2.resize(roi_gray_frame, (48, 48))
gray_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2GRAY)
input_img = np.expand_dims(gray_img, axis=-1) # Add the channel dimension
input_img = np.expand_dims(input_img, axis=0) # Add the batch dimension
# Normalize the image
input_img = input_img / 255.0
# Predict the emotions
emotion_prediction = emotion_model.predict(input_img)
maxindex = int(np.argmax(emotion_prediction))
emotion_label = emotion_dict[maxindex]
# Annotate the image with emotion label
cv2.putText(frame, emotion_label, (x+5, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA)
return frame
# Capture video from webcam
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
annotated_frame = predict_img(frame)
cv2.imshow('Emotion Detection', annotated_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()