Mastering Face Detection with Haar Cascade Classifier using Python and OpenCV

Aniroodh Prasad
4 min readJul 20, 2023

--

Introduction:

Face detection is a fundamental task in computer vision and has numerous applications, ranging from security systems to augmented reality. In this blog post, we will explore how to implement face detection using the Haar Cascade classifier with Python and OpenCV. The Haar Cascade model is an effective and popular machine learning-based approach for detecting objects in images and videos.

I’ll provide you with the step-by-step code to implement face detection using the Haar Cascade classifier in Python with OpenCV and display the detected faces in a window with rectangles. Here’s how you can do it:

Step 1:

Install Required Libraries Make sure you have Python installed on your system and install the necessary libraries using pip:

pip install opencv-python

Step 2:

Import Libraries In your Python script, import the required libraries:

import cv2

Step 3:

Load the Pre-trained Haar Cascade Model:Download the pre-trained Haar Cascade model for face detection from the OpenCV GitHub repository or use the following link: https://github.com/opencv/opencv/tree/master/data/haarcascades. Place the XML file in the same directory as your Python script.

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

Note: When you open the above link, search for this file ‘haarcascade_frontalface_default.xml’ and download it and upload it in your python script, in my case my python script is Jupyter Notebook.

Step 4:

Capture Video from Webcam: If you want to detect faces from a live video stream from your webcam, you can use the following code. If you prefer to work with an image, you can skip this step and directly load an image in Step 5.

cap = cv2.VideoCapture(0)

Step 5:

Process the Video Stream or Load an Image: You can either process the video stream or load an image and convert it to grayscale (Haar Cascade works on grayscale images).

For video stream:

while True:
ret, img = cap.read()
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

For an image:

img = cv2.imread('path/to/your/image.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Step 6:

Perform Face Detection Use the detectMultiScale method to detect faces in the image:

faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

Step 7:

Draw Rectangles around Detected Faces and Display in a Window: Loop through the detected faces, draw rectangles around them on the original image, and display the image in a window:

for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Crop the face region and display it in a separate window
face_roi = img[y:y + h, x:x + w]
cv2.imshow('Detected Face', face_roi)

cv2.imshow('Face Detection', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Step 8:

Save and Share (Optional) If you want to save the image with detected faces, you can use the cv2.imwrite() function. To share your work on LinkedIn, you can create a blog post or article showcasing the code and explaining the step-by-step process.

That’s it! With these steps, you can implement face detection using the Haar Cascade classifier and display the detected faces in a window with rectangles. Whether you’re working with a live video stream or an image, the code will help you detect and visualize the faces within the video or image.

Here’s the whole code in one go for your refrence, just follow this code and you are good to go. But remember, you need to upload your face model which you have download earlier.

import cv2

# Step 2: Load the Pre-trained Haar Cascade Model
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Step 4: Capture Video from Webcam (Optional)
cap = cv2.VideoCapture(0)

# Step 5: Process the Video Stream or Load an Image
while True:
ret, img = cap.read()
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Step 6: Perform Face Detection
faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

# Step 7: Draw Rectangles around Detected Faces and Display in a Window
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Crop the face region and display it in a separate window
face_roi = img[y:y + h, x:x + w]
cv2.imshow('Detected Face', face_roi)

cv2.imshow('Face Detection', img)

# Exit the loop when 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break

cap.release()
cv2.destroyAllWindows()

I’ll suggest you guys to perform this project one by one mean’s, one by one do the coding part and run these code one by one and not all at once.

--

--