Computer Vision : Face Detection using DLIB

Computer Vision is a fascinating field with enormous opportunities. As of now, models are being built to process X-Ray images to detect potential Covid-19 patients. While detecting the Covid-19 patients using CV is a usecase I can not implement at the moment, lets try a simple usecase of Finding Faces in an image.

We will use DLIB and OpenCV to accomplish this task.

DLIB's face detector uses HOG+SVM based model to detect faces in the image.
  1. We will use dlib.get_frontal_face_detector to detect the faces
  2. Loop over the detected faces and convert the dlibs bounding box types to proper OpenCV style rectangular bounding boxes.
  3. Draw the bounding boxes around the faces

###########################################################################
#                        Face Detection using DLIB                        #
###########################################################################

import numpy as np
import dlib,cv2

def dlib_bounding_to_rect(rect_boxes):
    # take a bounding predicted by dlib and convert it
    # to the format (x, y, w, h) as we would normally do
    # with OpenCV
    x = rect_boxes.left()
    y = rect_boxes.top()
    w = rect_boxes.right() - x
    h = rect_boxes.bottom() - y
    return (x, y, w, h)

# initialize dlib's face detector (HOG-based) 

detector = dlib.get_frontal_face_detector()

# load the input image, resize it, and convert it to grayscale
imageFilename = "ellen_oscar_selfie.jpg"
#imageFilename = "dog_human.jpg"
image = cv2.imread(imageFilename)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

facesDetected = detector(gray, 1)
print("Number of faces detected: ",len(facesDetected))
print(facesDetected)


# Loop over all detected face rectangles
for faces in facesDetected: 
  (x, y, w, h) = dlib_bounding_to_rect(faces)
  cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
 
cv2.imshow("Face Recognition", image)
cv2.waitKey(0)
cv2.destroyAllWindows() 


Sample Output Images:




Comments