OpenCV HAAR CASCADES

Haar Cascade is an object detection algorithm which is used to identify faces/objects in an image or a real time/live video.

The research paper “Rapid Object Detection using a Boosted Cascade of Simple Features” which is published in 2001 by Viola and Jones has the algorithm, which uses edge or line detection feature.

The above algorithm is consisting of lot of positive images with faces, and a lot of negative images will not consist of any face to train on them.

One can find the trained model at the OpenCV github repository : https://github.com/opencv/opencv/tree/master/data/haarcascades

The repository contains of different models like face detection, eye detection, upper body and lower body detection etc.

          HAAR features:

The features shown above makes it easy to find the edges or the lines in an image. To detect the edges or the lines anywhere in an image HAAR feature traverses through the whole image.

The haar feature continuously traverses from the top left of the side to the bottom right to search for features and also traverses pixel by pixel in the image.

Depending on the feature, they are classified into three categories:

  • The first set is two rectangle features that are responsible for finding the edges in both horizontal or in vertical direction or vice-versa.
  • The second set is three rectangle features which are responsible for finding out if any lighter region surrounded by darker regions are present.
  • The third set is four rectangle features which are responsible for finding out the change of pixel intensities across diagonals.

The difference of sum of pixels under white rectangle and sum of pixels under black rectangle gives a single value for each feature.

Haar-cascade Detection in OpenCV

OpenCV consist of many pre-trained classifiers for face, eyes, smile detection etc. Those XML files are stored in opencv/data/haarcascades/ folder.

       import numpy as np

       import cv2

       face_cascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)

       eye_cascade = cv2.CascadeClassifier(‘haarcascade_eye.xml’)

     img = cv2.imread(‘cold_face.jpg’)

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

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in faces:

         img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

         roi_gray = gray[y:y+h, x:x+w]

         roi_color = img[y:y+h, x:x+w]

         eyes = eye_cascade.detectMultiScale(roi_gray)

         for (ex,ey,ew,eh) in eyes:

             cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

   cv2.imshow(‘img’,img)

   cv2.waitKey(0)

   cv2.destroyAllWindows()

Haar Cascade Detection is one of the powerful face detection algorithms.Haar Features were not only used to detect faces, but also for lips, license number plates and eyes etc.

1 thought on “OpenCV HAAR CASCADES”

Leave a Comment

Your email address will not be published. Required fields are marked *