For any queries you can reach us at / WhatsApp us: +919158876092

Face Detection using OpenCV Python


In this tutorial, we will learn how to detect a face from a webcam using the Haar Cascades classifier. For the well-known tasks, the classifiers / detectors already exists, for example: detecting things like faces, cars, smiles, eyes and license plates.

Object Detection using Haar feature-based cascade classifiers is an effective object detection approach recommended by Paul Viola and Michael Jones in their paper, "Rapid Object Detection using a Boosted Cascade of Simple Features" in 2001.

Installing the modules

To install the OpenCV module and some other associated dependencies, we can use the pip command:

pip install opencv-python

Download the Haar Cascades

  1. Follow the URL:
  2. Click on haarcascade_frontalface_default.xml
  3. Click on Raw and then press Ctrl + S. This will help you save the Haar Cascade file for eyes.

The Code

import cv2
import sys

cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

video_capture = cv2.VideoCapture(0)

while True:
    res, frame =

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = cascade.detectMultiScale(
        scaleFactor = 1.1,
        minNeighbors = 5,
        minSize = (30, 30),
        flags = cv2.CASCADE_SCALE_IMAGE

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (155, 155, 0), 2)

    cv2.imshow('Video', frame)

    if cv2.waitKey(0) & 0xFF == ord('q'):


The Output

Face Detection using OpenCV Python