OpenCV is an open-source computer vision library that uses machine learning algorithms for face detection, object tracking or colors detection. In this blog post, we’ll learn how to use the Haar Cascade algorithm to detect faces and eyes in an image or real-time video. Let’s dive in.


  • Capture the video from the webcam.
  • Convert the frames to gray scale since cascade algorithm works only with gray scale.
  • Detect the faces using multi-scale. It takes 3 arguments — the input image, scaleFactor and minNeighbors.Scale Factor specify how much the image size is reduced at each image scale and min neighbors specify how many neighbors each candidate rectangle should have to retain it. You can read more about the arguments on this stack overflow post.
  • Draw the blue rectangle on the faces.
  • Draw the green rectangle on the eyes.

Don’t forget to import the libraries.

Make sure you have Python, OpenCV and Numpy already installed. I personally prefer Anaconda distribution but you are good to go without Anaconda if you have mentioned libraries installed.

The code once all written out will look like this.

#Haar Cascade Classifiers
import numpy as np
import cv2

cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier( + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier( + 'haarcascade_eye.xml')

while True:
    ret, frame =

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        roi_gray = gray[x:x+w, y:y+w]
        roi_color = frame[x:x+h, y:y+w]
        eyes = eye_cascade.detectMultiScale(roi_gray,1.3,5)
        for (ex,ey,ew,eh) in eyes:

    cv2.imshow('frame', frame)
    if cv2.waitKey(1) == ord('q'):

So that’s it! I hope you found it helpful, and also I hope that you have a nice day.

Till next time :) Happy Learning!

Bilal K.