Face and Eye detection using Haar Cascades – Python

In today’s world, which is changing quickly, there are many computer programs that can recognize a face and eye in a digital image. These programs are used in security systems, criminal identification, health care, and so on. To find faces and eyes in a photograph, OpenCV use machine learning algorithms.

In this OpenCV with Python tutorial, we’ll look at face and eye detection using Haar Cascades. To accomplish object recognition/detection using cascade files, you must first have cascade files.

What are Haar Cascades?

Haar cascade is an algorithm capable of detecting objects in photos regardless of their size or location. A haar-cascade detector can be trained to recognise a variety of items, including faces, buildings, cars, and more.

Two Haar cascade files—one for the face and one for the eyes—are required for this tutorial. It can be downloaded here.

So, let’s get this tutorial started…

First and foremost, make sure that you have imported all of the necessary Python packages.

#import necssary modules
import cv2
import numpy as np

We will specify our OpenCV-built face and eye classifiers as the XML files displayed below in code.

#harcascades
eye_classifier = cv2.CascadeClassifier('haarcascade_eye.xml')
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

We read the image first, then convert each frame to grayscale, and finally detect faces and eyes in the input image. Now that the face images have been categorized, our task will be to draw rectangles on them and then classify the eyes inside each rectangle. To this end, after creating the rectangles, we included the eye classifier and created rectangles around the eyes as well. Finally, the image will be saved.

#reading the image
img = cv2.imread('image.jpg')
#conversion to gray for faster processing
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#face detection
faces = face_classifier.detectMultiScale(gray, 1.3, 5)

for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(127,0,255),2)
    
    plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    cv2.imwrite('img.jpg', image)
    
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_classifier.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(255,255,0),8)
        plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        cv2.imwrite('img_v2.jpg', img)

It’s all finished, yay! Let us have a look at the results.

In this lesson, we learned how to use haar cascade classifiers to detect faces and eyes. We can also use haar cascade classifiers to detect other objects. We hope this tutorial was enjoyable for you to read.

Leave a Reply

Your email address will not be published.