I’m sharing what I learned with you. Let’s get started!
🚀 Step 1: Install Required Libraries
First, make sure you have the necessary libraries installed. Open a terminal and run the following:
pip install opencv-python matplotlib
🎯 Step 2: Download the Haar-Cascade Classifier
OpenCV provides a pre-trained Haar-cascade classifier for face detection. You’ll need the Haar-cascade XML file to proceed. You can download it here.
After downloading, load it into your Python script as follows:
import cv2
import matplotlib.pyplot as plt
# Load the Haar-cascade classifier
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
🖼️ Step 3: Detect Faces in an Image
Here’s the complete code to detect faces and draw rectangles around them in an image:
# Load the image
img = cv2.imread('test.png')
# Detect faces
faces = face_cascade.detectMultiScale(image=img, scaleFactor=1.1, minNeighbors=5)
# Draw rectangles around detected faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Print the number of faces detected
print(f"{len(faces)} face(s) detected!")
# Convert image to RGB format and display it
final_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(10, 10))
plt.imshow(final_img)
plt.axis("off")
plt.show()
Face Detection Example
📹 Bonus: Face Detection in a Live Video Feed
If you want to extend this to detect faces in a live video feed, it’s very straightforward. You’ll need to capture video from your webcam and process each frame in real-time. This involves:
- Using OpenCV’s
VideoCapture
to access your webcam. - Running a
while
loop to continuously capture frames. - Applying the same face detection logic to each frame.
- Displaying the results using OpenCV’s
imshow
.
Just a few tweaks to the image detection code, and you’ll have a working live feed setup!
⚙️ Understanding Key Parameters
- scaleFactor: Controls the size reduction of the image at each scale. Default is
1.1
. - minNeighbors: Defines how many neighboring rectangles must be detected for an area to be classified as a face. Default is
5
.
Experiment with these parameters to improve detection accuracy for different lighting or image conditions.