Upload WebCam.py
Browse files
WebCam.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
from fer import FER
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
# Function to start webcam feed, process frames, and detect emotions
|
6 |
+
def capture_webcam():
|
7 |
+
"""
|
8 |
+
Captures an image from webcam and returns the detected emotion and confidence score
|
9 |
+
Returns: tuple (emotion: str, confidence_score: float)
|
10 |
+
"""
|
11 |
+
# Initialize the webcam
|
12 |
+
cap = cv2.VideoCapture(0)
|
13 |
+
|
14 |
+
# Check if the webcam is opened correctly
|
15 |
+
if not cap.isOpened():
|
16 |
+
raise IOError("Cannot open webcam")
|
17 |
+
|
18 |
+
# Initialize the FER detector
|
19 |
+
detector = FER(mtcnn=True)
|
20 |
+
|
21 |
+
# Capture frame
|
22 |
+
ret, frame = cap.read()
|
23 |
+
|
24 |
+
if not ret:
|
25 |
+
cap.release()
|
26 |
+
return "neutral", 0.0
|
27 |
+
|
28 |
+
# Detect emotions in the frame
|
29 |
+
result = detector.detect_emotions(frame)
|
30 |
+
|
31 |
+
# Release the webcam
|
32 |
+
cap.release()
|
33 |
+
|
34 |
+
# If no face is detected, return neutral
|
35 |
+
if not result:
|
36 |
+
return "neutral", 0.0
|
37 |
+
|
38 |
+
# Get the emotions for the first face detected
|
39 |
+
emotions = result[0]["emotions"]
|
40 |
+
|
41 |
+
# Find the emotion with highest confidence
|
42 |
+
max_emotion = max(emotions.items(), key=lambda x: x[1])
|
43 |
+
emotion_label = max_emotion[0]
|
44 |
+
confidence_score = max_emotion[1]
|
45 |
+
|
46 |
+
return emotion_label, round(confidence_score, 2)
|
47 |
+
|
48 |
+
# Start capturing the webcam feed
|
49 |
+
#capture_webcam()
|