Views
No views yet
(48, 48, 1)[0.0, 1.0].1import cv2
2import numpy as np
3import tensorflow as tf
4from tensorflow.keras.models import load_model
5
6# 1. Load the model
7model = load_model('emotion_model_finetuned_final.keras')
8
9# 2. Define Emotion Labels
10EMOTION_LABELS = {0: 'Angry', 1: 'Fear', 2: 'Happy', 3: 'Sad', 4: 'Surprise', 5: 'Neutral'}
11
12# 3. Preprocess your image
13# Image must be a 48x48 grayscale numpy array
14def predict_emotion(image_path):
15 # Read as grayscale
16 img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
17 # Resize to 48x48
18 img = cv2.resize(img, (48, 48))
19 # Normalize pixel values
20 img = img.astype('float32') / 255.0
21 # Expand dimensions to match model input shape (1, 48, 48, 1)
22 img = np.expand_dims(img, axis=0)
23 img = np.expand_dims(img, axis=-1)
24
25 # Predict
26 predictions = model.predict(img)
27 max_index = np.argmax(predictions[0])
28 confidence = np.max(predictions[0])
29
30 emotion = EMOTION_LABELS[max_index]
31 print(f"Predicted Emotion: {emotion} (Confidence: {confidence*100:.2f}%)")
32 return emotion
33
34# Run prediction
35# predict_emotion('path_to_your_face_image.jpg')