Spaces:
Build error
Build error
Commit ·
1f8d1c4
1
Parent(s): 90f0272
app update
Browse files
app.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import tensorflow as tf
|
| 6 |
+
face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
| 7 |
+
# Load the Keras model
|
| 8 |
+
model = tf.keras.models.load_model("/home/anil/Documents/College Projects/EmotionClassifierHF/EmotionClassifier/affectnet_CNN_VGG_FIVEEMO_FINE_FINAL.h5")
|
| 9 |
+
|
| 10 |
+
# Mapping of emotion labels to their indices
|
| 11 |
+
emotion_label_dict = {
|
| 12 |
+
0: 'neutral',
|
| 13 |
+
1: 'happiness',
|
| 14 |
+
2: 'sadness',
|
| 15 |
+
3: 'surprise',
|
| 16 |
+
4: 'fear',
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
# Function to detect faces in an image
|
| 20 |
+
def detect_face(image):
|
| 21 |
+
img =image
|
| 22 |
+
face = face_detector.detectMultiScale(img, 1.1, 5, minSize=(40, 40))
|
| 23 |
+
|
| 24 |
+
if len(face) > 0:
|
| 25 |
+
x, y, w, h = face[0]
|
| 26 |
+
crop_img = img[y:y+h, x:x+w]
|
| 27 |
+
cropped = cv2.resize(crop_img, (224, 224))
|
| 28 |
+
img_rgb = cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB)
|
| 29 |
+
return img_rgb
|
| 30 |
+
else:
|
| 31 |
+
print("No face detected.")
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
# Function to classify emotion using the loaded model
|
| 35 |
+
def classify_emotion(image):
|
| 36 |
+
# Preprocess the image
|
| 37 |
+
image = np.expand_dims(image, axis=0)
|
| 38 |
+
image = image / 255.0
|
| 39 |
+
|
| 40 |
+
# Make prediction using the model
|
| 41 |
+
predictions = model.predict(image)
|
| 42 |
+
emotion_index = np.argmax(predictions)
|
| 43 |
+
emotion_name = emotion_label_dict[emotion_index]
|
| 44 |
+
|
| 45 |
+
return emotion_name
|
| 46 |
+
|
| 47 |
+
# Streamlit app
|
| 48 |
+
def main():
|
| 49 |
+
st.title("Emotion Prediction App")
|
| 50 |
+
|
| 51 |
+
uploaded_file = st.file_uploader("Upload Image", type=["jpg", "png", "jpeg"])
|
| 52 |
+
|
| 53 |
+
if uploaded_file is not None:
|
| 54 |
+
image = Image.open(uploaded_file)
|
| 55 |
+
st.image(image, caption='Uploaded Image', use_column_width=True)
|
| 56 |
+
|
| 57 |
+
image_array = np.array(image)
|
| 58 |
+
detected_face = detect_face(image_array)
|
| 59 |
+
|
| 60 |
+
if detected_face is not None:
|
| 61 |
+
predicted_emotion = classify_emotion(detected_face)
|
| 62 |
+
st.write('Predicted Emotion:', predicted_emotion)
|
| 63 |
+
|
| 64 |
+
if __name__ == '__main__':
|
| 65 |
+
main()
|