Face Detection in an Image with Computer Vision

May 02, 2020

By leveraging the power of existing libraries for computer vision, it is possible to write (apparently) quite simple scripts to automate menial image processing tasks. Following is how we can write a Python script for detecting faces in image files with the OpenCV python wrapper.

Installing OpenCV

I choose to install OpenCV with pip. Doing it this way is as simple as running the following in your terminal.

pip install --user opencv-python

The --user switch is for performing a local install for current user account.

Detecting Faces

Following is a Python script written for the task.

#!/usr/bin/env python3

"""
Detect Faces in a given image and save new image with faces marked.
"""

import cv2
import sys

def detect_faces(image_path):
  # Locate haarcascade file
  casc_path = "haarcascade_frontalface_default.xml"

  # Create classifier based on located haarcascade
  face_classifier = cv2.CascadeClassifier(casc_path)

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

  # Detect faces in image
  faces = face_classifier.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(150, 150)
  )

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

  # Draw rectangles around the faces
  for (x, y, w, h) in faces:
      cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

  cv2.imshow("Faces found", image)
  status = cv2.imwrite("{0}_detected.{1}".format(image_path.split(".")[0], image_path.split(".")[1]), image)
  print ("Image written to file-system: ", status)
  cv2.waitKey(0)

def main():
  import argparse
  parser = argparse.ArgumentParser()
  parser.add_argument("-i", "--img",
                      help="Path to input image")
  detect_faces((parser.parse_args()).img)

if __name__ == "__main__":
  main()

Give the script (i.e. detect_faces_img.py) permission to execute with:

chmod u+x face_detection_img.py

Run the script from residing directory as ./face_detection_img.py image.jpg to detect faces in image.jpg.

OpenCVPython

Face Detection in a Video with Computer Vision

Resize Virtual Disk Image and Expand Linux LVM