DEV Community

Debajyati Dey
Debajyati Dey

Posted on • Originally published at devsunite.com

Face Detection in Python Using OpenCV HAAR CASCADE Method

Let's learn about face detection in Python using the OpenCV library.

Introduction

OpenCV is a highly useful and popular computer vision library that supports programming languages like Python, C++, etc.

You must have seen some LinkedIn posts go viral where they are demonstrating their project which has something to do with hand gestures. There's no way you have been in LinkedIn and didn't see any of those projects' videos.

The key thing that is similar in those projects is Realtime object detection using the captures of the webcam of laptop as the data source. And most of those projects utilise an algorithm or method called, OpenCV Haar Cascade.

So, let's learn and implement OpenCV Haar Cascade for facial image detection (in Python).

Implementation

Haar Cascade classifiers are a cornerstone of face detection methods, because of the speed and simplicity.

Now you might be thinking, what are Haar Cascades?

Haar features are simple rectangular features that capture contrast differences in adjacent regions.

The classifier is trained using positive images (with the object) and negative images (without the object).

OpenCV provides pre-trained XML files for common objects like faces, eyes, smiles, etc.

Initial Setup

First things first, let's initialise a virtual environment, with -

python3 -m venv .venv

Now activate the virtual environment -

source .venv/bin/activate

     (for bash shell)

.venv\Scripts\activate

     (for command prompt)

.venv\Scripts\activate.ps1

     (for powershell)
Enter fullscreen mode Exit fullscreen mode

Install Dependencies

.venv/bin/pip3 install opencv-python numpy matplotlib

      (for Linux/macOS)
Enter fullscreen mode Exit fullscreen mode
.venv\Scripts\pip3.exe install opencv-python numpy matplotlib

      (for Windows)
Enter fullscreen mode Exit fullscreen mode

Step By Step Code

First download and load the Haar cascade classifiers from these links: - front_face_cascade , eye_cascade.

Now start importing the necessary modules.

import cv2
import numpy as np
import matplotlib.pyplot as plt

face_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('./haarcascade_eye.xml')
Enter fullscreen mode Exit fullscreen mode

How we define the detection functions -

def detect_faces(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
    return img

def detect_eyes(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    eyes = eye_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
    for (x, y, w, h) in eyes:
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
    return img
Enter fullscreen mode Exit fullscreen mode

Good. Now the only thing left is, loading image and applying detection.

img = cv2.imread('your_image.jpg')
face_img = detect_faces(img.copy())
eye_img = detect_eyes(img.copy())

# Display results
plt.imshow(cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB))
plt.title("Face Detection")
plt.show()

plt.imshow(cv2.cvtColor(eye_img, cv2.COLOR_BGR2RGB))
plt.title("Eye Detection")
plt.show()
Enter fullscreen mode Exit fullscreen mode

Well, for example I used a photo of mine and it worked perfectly well. The matplotlib output for my photo using the code is given below ->

Face & Eye Region Detected by OpenCV and specified with a blue box and two green boxes respectively

See, it detected the eyes and face portion accurately! How, cool, is that!

Now try with your own face images.

The Drawbacks of Haar Cascades

Well, Haar Cascades are fast and easy to use. But it not the ultimate solution of all face detection tasks. It has its own drawbacks too. What are they?

Haar Cascades can be prone to false positives. It can happen that an image has no human face but there are some dots and marks in the wall that appear to the algorithm as a face structure. This can bring problematic results to your application. So, beware of that!

For a robust detection, consider using deep learning-based detectors like Multi-Task Cascaded Convolutional Neural Network (MTCNN).

Conclusion

Face detection using Haar Cascades in OpenCV offers a fast and accessible entry point into the world of computer vision.

Whether you're building a simple image scanner or experimenting with real-time webcam feeds, this method provides a solid foundation for learning and prototyping.

However, as we've seen, Haar Cascades have limitations—especially in complex environments or with varied lighting. For more robust and scalable solutions, exploring deep learning–based detectors like MTCNN or RetinaFace is the best choice.

Still, mastering Haar Cascades is a valuable milestone in any developer’s journey into visual intelligence.

Now, if you found this article helpful, if this blog added some value to your time and energy, please show some love by giving the article some likes and share it with your dev friends.

Feel free to connect with me :)

Thanks for reading! 🙏🏻
Written with 💚 by Debajyati Dey
My GitHub My LinkedIn My Daily.dev My Peerlist My Twitter

Follow me on Dev to motivate me so that I can bring more such tutorials like this on here!

Happy coding 🧑🏽‍💻👩🏽‍💻! Have a nice day ahead! 🚀

Thank you

Top comments (4)

Collapse
 
shricodev profile image
Shrijal Acharya

Great going, Deb 🙌

Collapse
 
ddebajyati profile image
Debajyati Dey • Edited

Thanks Shrijal! Hope you found it useful!

Collapse
 
shemith_mohanan_6361bb8a2 profile image
shemith mohanan

Super clear explanation! I’ve seen a lot of posts about OpenCV, but this one really breaks down Haar Cascades in a way beginners can follow easily. Great job — loved the mention of MTCNN too!

Collapse
 
ddebajyati profile image
Debajyati Dey

Glad that you found it so easy to understand. Thanks a lot for reading!

Stay tuned for more such content!