Facial expression detection using Deepface module in Python
Facial expression detection is a popular application of computer vision and deep learning. Deepface is a Python module for facial recognition and facial expression analysis. It is built on top of Keras and TensorFlow and provides a simple API for detecting facial expressions in images and videos.
Here are the steps to perform facial expression detection using Deepface module in Python:
- Install Deepface module: You can install Deepface module using pip command in your terminal or command prompt.
pip install deepface
- Import necessary libraries: Import the necessary libraries such as Deepface, OpenCV, and Matplotlib.
import cv2
import matplotlib.pyplot as plt
from deepface import DeepFace
- Load the image: Load the image on which you want to perform facial expression detection using OpenCV.
img = cv2.imread('image.jpg')
- Detect faces: Use the detectFace function of DeepFace module to detect faces in the image.
faces = DeepFace.detectFace(img, detector_backend='opencv')
- Analyze facial expressions: Use the analyze function of DeepFace module to analyze the facial expressions of the detected faces.
result = DeepFace.analyze(faces, actions=['emotion'])
- Visualize the results: Use Matplotlib to visualize the results.
plt.imshow(cv2.cvtColor(faces[0], cv2.COLOR_BGR2RGB))
plt.title('Detected Face')
plt.show()
print('Facial Expressions:')
for emotion, score in result['emotion'].items():
print(f'{emotion}: {score}')
This will display the detected face and the facial expressions detected in the image.
There are other methods to perform facial expression detection using Deepface module such as using a pre-trained model, using a webcam to detect facial expressions in real-time, and using a video file to detect facial expressions. Here are some examples:
- Using a pre-trained model:
model = DeepFace.build_model('FacialExpression')
result = DeepFace.analyze(img, model=model, actions=['emotion'])
- Using a webcam:
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
faces = DeepFace.detectFace(frame, detector_backend='opencv')
result = DeepFace.analyze(faces, actions=['emotion'])
for face in faces:
cv2.imshow('Facial Expression Detection', face)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
- Using a video file:
cap = cv2.VideoCapture('video.mp4')
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
faces = DeepFace.detectFace(frame, detector_backend='opencv')
result = DeepFace.analyze(faces, actions=['emotion'])
for face in faces:
cv2.imshow('Facial Expression Detection', face)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
These are some of the methods to perform facial expression detection using Deepface module in Python.