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()