| import gradio as gr |
|
|
| import os |
| import cv2 |
| import numpy as np |
| from keras.preprocessing import image |
| import warnings |
| warnings.filterwarnings("ignore") |
| from keras_preprocessing.image import ImageDataGenerator |
| from keras.utils import img_to_array, load_img |
| from keras.models import load_model |
| import matplotlib.pyplot as plt |
| import numpy as np |
| from PIL import Image |
| import tensorflow as tf |
|
|
| |
| model = load_model(r'best_model.h5') |
|
|
| face_haar_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') |
|
|
| def analyze_emotion(frame): |
| gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) |
| faces_detected = face_haar_cascade.detectMultiScale(gray_img, 1.32, 5) |
|
|
| for (x, y, w, h) in faces_detected: |
| cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), thickness=7) |
| roi_gray = gray_img[y:y + w, x:x + h] |
| roi_gray = cv2.resize(roi_gray, (224, 224)) |
| img_pixels = tf.keras.preprocessing.image.img_to_array(roi_gray) |
| img_pixels = np.expand_dims(img_pixels, axis=0) |
| img_pixels /= 255 |
|
|
| predictions = model.predict(img_pixels) |
|
|
| |
| max_index = np.argmax(predictions[0]) |
|
|
| emotions = ('angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral') |
| predicted_emotion = emotions[max_index] |
|
|
| cv2.putText(frame, predicted_emotion, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) |
|
|
| return frame[...,::-1] |
|
|
| inputs = gr.inputs.Video(source="webcam") |
| outputs = gr.outputs.Image(type="numpy") |
|
|
| iface = gr.Interface(fn=analyze_emotion, inputs=inputs, outputs=outputs, title="Facial Emotion Analysis", |
| description="Detects emotions in real-time from webcam video input") |
|
|
| iface.launch() |
|
|