File size: 1,349 Bytes
401e1f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import cv2
from fer import FER
import numpy as np

# Function to start webcam feed, process frames, and detect emotions
def capture_webcam():
    """

    Captures an image from webcam and returns the detected emotion and confidence score

    Returns: tuple (emotion: str, confidence_score: float)

    """
    # Initialize the webcam
    cap = cv2.VideoCapture(0)
    
    # Check if the webcam is opened correctly
    if not cap.isOpened():
        raise IOError("Cannot open webcam")
    
    # Initialize the FER detector
    detector = FER(mtcnn=True)
    
    # Capture frame
    ret, frame = cap.read()
    
    if not ret:
        cap.release()
        return "neutral", 0.0
    
    # Detect emotions in the frame
    result = detector.detect_emotions(frame)
    
    # Release the webcam
    cap.release()
    
    # If no face is detected, return neutral
    if not result:
        return "neutral", 0.0
    
    # Get the emotions for the first face detected
    emotions = result[0]["emotions"]
    
    # Find the emotion with highest confidence
    max_emotion = max(emotions.items(), key=lambda x: x[1])
    emotion_label = max_emotion[0]
    confidence_score = max_emotion[1]
    
    return emotion_label, round(confidence_score, 2)

# Start capturing the webcam feed
#capture_webcam()