Download app.py from mano66/faceemo: direct link, hf CLI and curl.
- Browser
- Download file 1.47 kB
-
https://huggingface.co/spaces/mano66/faceemo/resolve/main/app.py
- Command line
-
hf download hf://spaces/mano66/faceemo/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mano66/faceemo/resolve/main/app.py
1.47 kB
| import gradio as gr | |
| import cv2 | |
| import numpy as np | |
| from keras.models import load_model | |
| # Load your model | |
| model = load_model('model.keras') | |
| # Load the Haar Cascade for face detection | |
| face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') | |
| # Emotion labels | |
| labels_dict = { | |
| 0: 'Angry', 1: 'Disgust', 2: 'Fear', 3: 'Happy', | |
| 4: 'Neutral', 5: 'Sad', 6: 'Smirk', 7: 'Surprise' | |
| } | |
| # Define prediction function | |
| def detect_emotion(image): | |
| frame = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) | |
| gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) | |
| faces = face_cascade.detectMultiScale(gray, 1.3, 5) | |
| for (x, y, w, h) in faces: | |
| face = gray[y:y+h, x:x+w] | |
| resized = cv2.resize(face, (48, 48)) | |
| normalized = resized / 255.0 | |
| reshaped = np.reshape(normalized, (1, 48, 48, 1)) | |
| result = model.predict(reshaped) | |
| label = np.argmax(result, axis=1)[0] | |
| emotion = labels_dict[label] | |
| # Draw on frame | |
| cv2.rectangle(frame, (x, y), (x + w, y + h), (50, 50, 255), 2) | |
| cv2.rectangle(frame, (x, y - 40), (x + w, y), (50, 50, 255), -1) | |
| cv2.putText(frame, emotion, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, | |
| 0.8, (255, 255, 255), 2) | |
| return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) | |
| # Create the Gradio Interface | |
| iface = gr.Interface( | |
| fn=detect_emotion, | |
| inputs=gr.Image(source="webcam", type="numpy"), | |
| outputs="image", | |
| live=False | |
| ) | |
| iface.launch() | |