Emotion detection system using python
An emotion detection system using Python and a pre-trained model like fer
(Facial Emotion Recognition) or DeepFace
. This code will use the DeepFace
library, which supports multiple models for facial emotion recognition.
Step 1: Install Required Libraries
pip install deepface opencv-python
Step 2: Write the Emotion Detection Code
import cv2from deepface import DeepFace
# Load the pre-trained DeepFace model for emotion detection
def detect_emotion(image_path):
# Analyze the image to detect emotions
analysis = DeepFace.analyze(img_path=image_path, actions=['emotion'])
# Get the dominant emotion
dominant_emotion = analysis['dominant_emotion']
return dominant_emotion
# Capture video from the webcam
def emotion_from_webcam():
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
# Save the frame as a temporary image
cv2.imwrite("temp.jpg", frame)
# Detect emotion in the current frame
emotion = detect_emotion("temp.jpg")
# Display the detected emotion on the frame
cv2.putText(frame, emotion, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA)
# Show the frame
cv2.imshow('Emotion Detection', frame)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the video capture object and close all OpenCV windows
cap.release()
cv2.destroyAllWindows()
# Run the emotion detection from webcam
emotion_from_webcam()
How the Code Works:
- DeepFace: The
DeepFace.analyze
function is used to analyze the image and detect emotions. It supports several models, but the default model isVGG-Face
. - Webcam Capture: The code captures video from the webcam and detects emotions in real-time.
- Display Emotion: The detected emotion is overlaid on the video frame.
Step 3: Run the Code
When you run the code, it will open a webcam feed, detect emotions in real-time, and display the dominant emotion on the video stream. Press q
to exit the webcam feed.
Notes:
- The emotion detection is based on facial expressions, so ensure your face is visible in the webcam for accurate results.
- You can replace
"temp.jpg"
withframe
directly if you prefer to analyze the frame without saving it as an image file. However, the current approach ensures that the frame is properly analyzed in case of any format issues.
Comments
Post a Comment