Spaces:
Sleeping

opencv / app.py
faiz3123's picture
Update app.py
9b24f98 verified
Raw History Blame Contribute Delete
4.58 kB
from transformers import pipeline
import cv2
import numpy as np
from PIL import Image
import gradio as gr
# Load the Hugging Face pipeline
pipe = pipeline("image-classification", model="dima806/facial_emotions_image_detection")
# Load face detection model (Haar Cascade)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
# Emoji mapping for emotions
emoji_mapping = {
"disappointment": "๐Ÿ˜ž",
"sadness": "๐Ÿ˜ข",
"annoyance": "๐Ÿ˜ ",
"neutral": "๐Ÿ˜",
"disapproval": "๐Ÿ‘Ž",
"realization": "๐Ÿ˜ฎ",
"nervousness": "๐Ÿ˜ฌ",
"approval": "๐Ÿ‘",
"joy": "๐Ÿ˜„",
"anger": "๐Ÿ˜ก",
"embarrassment": "๐Ÿ˜ณ",
"caring": "๐Ÿค—",
"remorse": "๐Ÿ˜”",
"disgust": "๐Ÿคข",
"grief": "๐Ÿ˜ฅ",
"confusion": "๐Ÿ˜•",
"relief": "๐Ÿ˜Œ",
"desire": "๐Ÿ˜",
"admiration": "๐Ÿ˜Œ",
"optimism": "๐Ÿ˜Š",
"fear": "๐Ÿ˜จ",
"love": "โค๏ธ",
"excitement": "๐ŸŽ‰",
"curiosity": "๐Ÿค”",
"amusement": "๐Ÿ˜„",
"surprise": "๐Ÿ˜ฒ",
"gratitude": "๐Ÿ™",
"pride": "๐Ÿฆ"
}
def preprocess_face(face_rgb):
"""
Preprocess the face for the pipeline.
"""
try:
# Resize and normalize the face to match pipeline requirements
face_resized = cv2.resize(face_rgb, (224, 224))
face_normalized = face_resized / 255.0 # Normalize pixel values (0-1)
face_pil = Image.fromarray((face_normalized * 255).astype(np.uint8))
return face_pil
except Exception:
return None
def classify_mood_from_frame(frame):
"""
Detect faces in the frame, classify emotion for each face, and annotate the frame.
"""
try:
# Convert frame to grayscale for face detection
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
for (x, y, w, h) in faces:
# Extract and preprocess the face
face_rgb = frame[y:y + h, x:x + w] # Extract RGB region
face_pil = preprocess_face(face_rgb)
if face_pil is None:
continue # Skip if preprocessing failed
# Predict emotion using the Hugging Face pipeline
result = pipe(face_pil)
emotion_label = result[0]['label']
emotion_score = result[0]['score']
# Get the corresponding emoji
emotion_emoji = emoji_mapping.get(emotion_label.lower(), "โ“")
# Draw rectangle and emotion label on the frame
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.putText(frame, f"{emotion_label} {emotion_emoji} ({emotion_score:.2f})", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
# Convert frame to RGB for Gradio display
return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
except Exception:
return None
def process_webcam(frame):
"""
Main function to classify emotions from a webcam frame.
"""
if frame is None:
return None # Return if no frame is provided
# Classify the mood from the given frame
annotated_frame = classify_mood_from_frame(frame)
return annotated_frame
# Gradio interface for real-time webcam inference
# Gradio interface for real-time webcam inference
def interface_webcam():
return gr.Interface(
fn=process_webcam,
inputs=gr.Video(format="webcam", streaming=True), # Fixed for Gradio's webcam input
outputs=gr.Video(format="mp4"), # Explicitly specify output format
live=True, # Enable live streaming
title="Real-Time Mood Classifier ๐ŸŽญ",
description="Use your webcam to detect emotions in real time with facial emotion detection."
)
# Gradio interface for image-based inference
def process_image(image):
"""
Classify emotion for an uploaded image.
"""
frame = np.array(image)
return classify_mood_from_frame(frame)
def interface_image():
return gr.Interface(
fn=process_image,
inputs=gr.Image(type="pil", label="Upload Image"),
outputs=gr.Image(type="numpy", label="Emotion-Detected Image"),
title="Image-Based Mood Classifier ๐Ÿ˜Š",
description="Upload an image to detect emotions on faces."
)
# Tabbed interface for both webcam and image modes
def main():
gr.TabbedInterface(
[interface_webcam(), interface_image()],
tab_names=["Webcam", "Image"],
title="Emotion Detection Toolkit"
).launch()
if __name__ == "__main__":
main()