Spaces:
Sleeping
Sleeping
import gradio as gr | |
import os | |
import cv2 | |
import numpy as np | |
import imutils | |
from keras.preprocessing.image import img_to_array | |
from keras.models import load_model | |
# Load the pre-trained models and define parameters | |
detection_model_path = 'haarcascade_files/haarcascade_frontalface_default.xml' | |
emotion_model_path = 'model4_0.83/model4_entire_model.h5' | |
face_detection = cv2.CascadeClassifier(detection_model_path) | |
emotion_classifier = load_model(emotion_model_path, compile=False) | |
EMOTIONS = ['neutral', 'happiness', 'surprise', 'sadness', 'anger', 'disgust', 'fear', 'contempt', 'unknown'] | |
# face_detector_mtcnn = MTCNN() | |
classifier = load_model(emotion_model_path) | |
def predict_emotion(image): | |
faces = face_detection(image) | |
for face in faces: | |
x,y,w,h = face['box'] | |
roi = image[y:y+h,x:x+w] | |
# Converting the region of interest to grayscale, and resize | |
roi_gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY) | |
roi_gray = cv2.resize(roi_gray,(48,48),interpolation=cv2.INTER_AREA) | |
img = roi_gray.astype('float')/255.0 | |
img = img_to_array(img) | |
img = np.expand_dims(img,axis=0) | |
prediction = classifier.predict(img)[0] | |
#top_indices = np.argsort(prediction)[-2:] | |
#top_emotion = top_indices[1] | |
#second_emotion = top_indices[0] | |
#label = emotions[top_emotion] | |
confidences = {emotions[i]: float(prediction[i]) for i in range(len(emotions))} | |
return confidences | |
demo = gr.Interface( | |
fn = predict_emotion, | |
inputs = gr.Image(type="numpy"), | |
outputs = gr.Label(num_top_classes=9), | |
#flagging_options=["blurry", "incorrect", "other"], | |
examples = [ | |
os.path.join(os.path.dirname(__file__), "images/Image_1.jpg"), | |
os.path.join(os.path.dirname(__file__), "images/Image_2.jpg"), | |
os.path.join(os.path.dirname(__file__), "images/Image_3.jpg"), | |
os.path.join(os.path.dirname(__file__), "images/Image_4.jpg"), | |
os.path.join(os.path.dirname(__file__), "images/Image_5.jpg"), | |
os.path.join(os.path.dirname(__file__), "images/Image_6.jpg"), | |
os.path.join(os.path.dirname(__file__), "images/Image_7.jpg"), | |
os.path.join(os.path.dirname(__file__), "images/Image_8.jpg"), | |
os.path.join(os.path.dirname(__file__), "images/Image_9.jpg"), | |
os.path.join(os.path.dirname(__file__), "images/Image_10.jpg"), | |
], | |
title = "Whatchu feeling?", | |
theme = "shivi/calm_seafoam" | |
) | |
if __name__ == "__main__": | |
demo.launch() |