Facial attribute detection using machine learning in Python

In this tutorial, we will get to know the method for facial attribute detection using machine learning in Python using OpenCV library of Python. Here, we will learn about facial attribute detection or we can say object detection using Haarcascade Classifiers. Also, we will see a Python program for the same. So, if you are looking for facial attribute detection using machine learning in Python then you are in the right place.

Face Detection using OpenCV

OpenCV(Open Source Computer Vision Library) is Python library to solve computer vision related problems. Objects are detected in OpenCV  with the help of haarcascade classifiers.

Here is the script for face detection using Python:-

from cv2 import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye_tree_eyeglasses.xml')
#img = cv2.imread('test.jpg')
cap = cv2.VideoCapture(0)

First, we read the xml file of classifiers for different facial attributes such as eyes, nose, frontal-face etc. Then if you want to detect facial attributes in a image then image is read using imread() function of OpenCV and if you want to detect in a video then video is imported using VideoCapture() function in OpenCV.

while (True):
    _, frame = cap.read()
    if(type(frame)==type(None)):
      break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(frame, 1.1, 4)

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 3)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = frame[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), (255, 0, 0), 2)

    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

This while loop will run till the video we captured is running. This loop is doing the main facial attribute detection task. It captures the video frame by frame using read() function of OpenCV. If there is no image in video then loop will break out. Converting the frames captured to grayscale is the most important point as grayscale feature detects the object fast and its more convenient to detect the object. Detecting the face using detectMultiScale() function detects the faces in the video or image. After detecting the face put the rectangle around it. To break out of the output press ‘q’ key in keyboard.

cap.release()

release() function is used only when camera is used.

For object detection and haarcascade classifiers read here:-

https://docs.opencv.org/3.4/db/d28/tutorial_cascade_classifier.html

Also read about:-

Draw a rectangle on an image using OpenCV in Python

 

Leave a Reply

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