February 21, 2017

Face detection example

In this post I will show you a very simple example of how to detect faces inside an image using Python 3 and OpenCV library.

First of all you have to install the prerequisite software as described in this post.

Download the PyFaceRec repository in a directory of your choice. In the examples we assume you have downloaded it into C:\PyFaceRec.

The example described here is located in the SimpleFaceDetection folder and automatically identifies faces in a picture of the famous pop group Abba.
Open a command Prompt, move into the SimpleFaceDetection folder an run the sample script as follows.

cd C:\PyFaceRec\SimpleFaceDetection
python simple_face_detection.py

You should get an output like this.



The source is quite self-explanatory.

# Import the OpenCV library
import cv2

# Load the sample image
image = cv2.imread('data/abba.jpg')

# Load the OpenCV classifier to detect faces
faceCascade = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml')

# Detect faces in the image
faces = faceCascade.detectMultiScale(
    image,
    scaleFactor=1.2,
    minNeighbors=5,
    minSize=(50, 50)
)

# The faces variable now contains an array of Nx4 elements
# where N is the number faces detected

print("Found", len(faces), "faces")

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

# Display the image
cv2.imshow("Faces found", image)

# Wait for any key before exiting
cv2.waitKey(0)


2 comments:

  1. QUANTUM BINARY SIGNALS

    Professional trading signals sent to your mobile phone daily.

    Start following our signals right now & gain up to 270% a day.

    ReplyDelete
  2. If you need your ex-girlfriend or ex-boyfriend to come crawling back to you on their knees (no matter why you broke up) you gotta watch this video
    right away...

    (VIDEO) Text Your Ex Back?

    ReplyDelete