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.

Approach:

  • 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(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

while True:
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
        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.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

    
    cv2.imshow('frame', frame)
    
    if cv2.waitKey(1) == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

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.