Python | Haar cascades for object detection

What are Haar Cascades?
Haar Cascade Classifiers are an effective way of detecting objects. This method was proposed by Paul Viola and Michael Jones in their article “ cascade” a href = https://www.researchgate.net/publication/3940582_Rapid_Object_Detection_using_a_Boosted_Cascade_of_Simple_Features rel = noopener target = _blank> simple functions. Haar cascade — it is a machine learning approach that uses many positive and negative images to train the classifier.

  • Positive images — these images contain images that we want our classifier to identify.
  • Negative images — images of everything else that do not contain the object we want to detect.

Requirements

  • Make sure you have python, Matplotlib and OpenCV (all latest versions) installed on your machine.
  • The haar cascade files can be downloaded from OpenCV Github repository .

Implementation

# Import all required packages

import cv2

import numpy as np

import matplotlib.pyplot as plt % matplotlib inline

 

 
# Read in cascading face and eye classifiers

face_cascade = cv2.CascadeClassifier ( `. ./DATA / haarcascades / haarcascade_frontalface_default.xml` )

eye_cascade = cv2.CascadeClassifier ( `../ DATA / haarcascades / haarcascade_eye.xml` )

  

  

  
# create a function for face detection

def adjusted_detect_face ( img):

 

face_img = img.copy ()

 

face_rect = face_cascade.detectMultiScale (face_img, 

scaleFactor = 1.2

minNeighbors = < / code> 5 )

 

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

cv2.rectangle (face_img, (x, y), 

(x + w, y + h), ( 255 , 255 , 255 ), 10 )

  

return face_img 

 

 
# create a function to detect eyes

def detect_eyes (img):

 

eye_img = img.copy () 

eye_rect = eye_cascade.detectMultiScale (eye_img, 

scaleFactor = 1.2

minNeighbors = 5

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

  cv2.rectangle (eye_img, (x, y), 

(x + w, y + h ), ( 255 , 255 , 255 ), 10

return eye_img

  
# Read on image and make copies

img = cv2.imread ( `../ sachin.jpg` )

img_copy1 = img.copy ()

img_copy2 = img.copy ()

img_copy3 = img.copy ()

 
# Face detection

face = adjusted_detect_face (img_copy)

plt.imshow (face)

Code: Eye Detection

 

eyes = detect_eyes (img_copy2)

plt.imshow (eyes)

Code: face and eye detection

eyes_face = adjusted_detect_face (img_copy3)

eyes_face = detect_eyes (eyes_face)

plt.imshow (eyes_face)

Haar cascades can be used to detect any type of object if you have an appropriate XML file for that. You can even create your own XML files from scratch to discover any type of object you want.