Face detection

In this tutorial we learn how to detect faces in images searching for hair cascades. For the implementation we need two input files. 1. Hair cascade model.

  1. Image with human face(s) on it. Either make a group/portrait photo of you and your friends or get something suitable from the internet(No one will judge you.).

Implementation

First of all we import the computer vision package.

import cv2

Now we define the paths to the two input files. We assume that the files are in the execution folder.

imagePath = "image.png"
cascPath = "haarcascade_frontalface_default.xml"

Read the image and convert it to grayscale.

image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Detect faces in the image.

faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30)
)

print("Found {0} faces!".format(len(faces)))

Draw a rectangle around the faces.

for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

Show the result.

cv2.imshow("Faces found", image)
cv2.waitKey(0)

OpenCV computer vision python package.