Views
No views yet
pip install tensorflow numpy opencv-python1import tensorflow as tf
2import cv2
3import numpy as np
4
5# Load the model
6model = tf.keras.models.load_model('emotion_model.keras')
7
8# Define emotion labels
9emotion_labels = {0: 'Anger', 1: 'Fear', 2: 'Happy', 3: 'Sad', 4: 'Surprise', 5: 'Neutral'}1def predict_emotion(image_path):
2 # Load and preprocess image
3 img = cv2.imread(image_path)
4 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
5 face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
6 faces = face_cascade.detectMultiScale(gray, 1.3, 5)
7
8 for (x, y, w, h) in faces:
9 roi_gray = gray[y:y+h, x:x+w]
10 roi_gray = cv2.resize(roi_gray, (48, 48))
11 roi_gray = roi_gray.astype('float32') / 255.0
12 roi_gray = np.expand_dims(roi_gray, axis=0)
13 roi_gray = np.expand_dims(roi_gray, axis=-1)
14
15 prediction = model.predict(roi_gray)
16 label = emotion_labels[np.argmax(prediction)]
17 print(f"Predicted Emotion: {label}")
18
19predict_emotion('test_image.jpg')