Detect faces in photos using OpenCV

Detect faces in photos using OpenCV
Ad debug output

The ad is displayed on the page

current post: Detect faces in photos using OpenCV, ID: 5642

Ad: Long (5803)
Placement: Before Content 2 (before-content_2)





Find solutions in the manual
Ad debug output

The ad is displayed on the page

current post: Detect faces in photos using OpenCV, ID: 5642

Ad: Long (5803)
Placement: Before Content (before-content)





Find solutions in the manual

In this article, I will show you how simple it is to detect faces or any objects in photos using Python and OpenCV library. I will be explaining how the program works. Let’s get started.

Prerequisite

I assume you have already installed and configured the OpenCV library and Python on your machine. There are many good tutorials available online on how to install OpenCV on your machine.
You can double-check if it’s installed properly by the following commands.

python
import cv2
cv2.__version__

How does it work?

OpenCV is an Open-Source computer vision and machine learning library.
This library uses machine learning algorithms to detect the objects in the image. We will use haar cascade classifier. Since we need to detect faces from the image. So we ill be using haarcascade_frontalface_default
classifier.

Ad debug output

The ad is displayed on the page

current post: Detect faces in photos using OpenCV, ID: 5642

Ad: Long (5803)
Placement: Content (content)





Find solutions in the manual

What’s a Cascade Classifier?

Cascade is a long XML file which has OpenCV data to detect certain objects.
Here we need to detect faces from the image so we will be using haarcascade_frontalface_default.xmlclassifier by OpenCV
You can change the cascade file depending upon your requirement. You can even create your own cascade files.

Here the classifier loaded is haarcascade_frontalface_default.xml which detects frontal faces in the image.

Here also I used the same program the only change I made is the classifier.
The classifier used here is haarcascade_eye.xml . This classifier will look for eyes in the input image.

Not only face and eye there are many classifiers made by openCV to detect different human body parts. Have a look at their GitHub repo.

I hope you got a rough idea of what task the classifier does.
For something complicated like face it requires 1000 or even more classifiers. For making the calculation simple the algorithm splits the task into many blocks. Each block does a quick analysis and checks if it matches with the features. Once it’s done it will pass on to the next block. To detect an object it needs to pass all the blocks.

Code

You can download the code and image files I have used from here

import cv2
import sys

# Path for image to be detected and classifier path
#imagePath = "HappyKids1.png"
imagePath = sys.argv[1]
cascPath = "haarcascade_frontalface_default.xml"

# Creating haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)

# Read the image and convert it to gray
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = faceCascade.detectMultiScale(
    gray,               # Matrix where image are stored.
    scaleFactor=1.1,    # This specify how much the image size is reduced.
    minNeighbors=5,     # Minimum distance between nearby detected faces
    minSize=(30, 30),   # Minimum size of face, here face smaller than this are ignored.
)

print("Detected {0} faces from the image.".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)

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

Code Explanation

import cv2
import sys

Imports the required modules for the program. In our case, we need 2 modules OpenCV cv2 and System-specific parameters module for command-line argument sys

#imagePath = "HappyKids1.png"
imagePath = sys.argv[1]
cascPath = "haarcascade_frontalface_default.xml"

Here, you need to pass the image name as a command-line argument like python3 faceDetect.py filename.png
or
You can directly mention the file name in the code. If the image is in the same project directory you can just mention it by its filename.extension. Otherwise, you need to provide complete path to the image like /home/xxx/xxx/xxx.jpg. Make sure the extension is the same at both places.
The default cascade for detecting faces is loaded. Since we are detecting faces.

faceCascade = cv2.CascadeClassifier(cascPath)

faceCascade variable is created and initialised it with the frontalface cascade. Now we are ready to use the cascade.

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

Here the image is read and then converted to grayscale. This is done because many processing are done on grayscale in OpenCV

faces = faceCascade.detectMultiScale(
    gray,               # Matrix where image are stored.
    scaleFactor=1.1, 
    minNeighbors=5,
    minSize=(30, 30),
)

Here the face detection takes place. The detectMultiScale function detects the object in different sizes in the image and returns it as a list of rectangles. We pass 4 parameters.

  • image First parameter image is the grayscaled image
  • scaleFactor This parameter specifies how much the image size is reduced. In some with photos multiple faces, one will be larger than the other face this can be compensated using this scaleFactor.
  • minNeighbor The minimum distance between nearby detected faces.
  • minSize The minimum size of the object (face) to be detected. Objects smaller than this will be ignored.
print("Detected {0} faces from the image.".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)

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

Here the number of detected faces in the image is printed. and a rectangle is drawn around the detected face. (x,y) is the position and (w,h) is the width and height of the rectangle.
The output image is displayed at last.

Output

You can test image by entering the following commands on the command line
python3 face_detector.py HappyKids1.png
Make sure you are inside the project directory

Photo by samer daboul from Pexels

Here the result is 100% accurate. But every time you won’t get 100% percentage accuracy. Let’s try different images of same people

Photo by samer daboul from Pexels

Here the kid on the top left corner didn’t got recognised. It might be due to many reason. His face is partially covered.

Photo by samer daboul from Pexels

But still, you can make it proper by tweaking with scaleFactor and minNeighbors parameters try adjusting it manually.

What’s next ?

This is just a basic introduction. there is plenty of things to do with this. I upcoming articles I will show you how to detect objects and faces from a live video feed. And how to create your own classifiers for your project.

Update : Detecting faces from live webcam video article is live now !!!

One thought on “Detect faces in photos using OpenCV

Leave a Reply

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