DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Face Detection Using Python and OpenCV

Face Detection Using Python and OpenCV

Facial recognition is always a hot topic, and it's also never been more accessible. In this post, we start with taking a look at how to detect faces using Python.

Mike Driscoll user avatar by
Mike Driscoll
·
Aug. 21, 18 · Tutorial
Like (1)
Save
Tweet
Share
15.52K Views

Join the DZone community and get the full member experience.

Join For Free

machine learning, artificial intelligence and face recognition are big topics right now. so i thought it would be fun to see how easy it is to use python to detect faces in photos. this article will focus on just detecting faces, not face recognition which is actually assigning a name to a face. the most popular and probably the simplest way to detect faces using python is by using the opencv package. opencv is a computer vision library that's written in c++ and had python bindings. it can be kind of complicated to install depending on which os you are using, but for the most part you can just use pip:

pip install opencv-python


i have had issues with opencv on older versions of linux where i just can't get the newest version to install correctly. but this works fine on windows and seems to work okay for the latest versions of linux right now. for this article, i am using the 3.4.2 version of opencv's python bindings.

finding faces

there are basically two primary ways to find faces using opencv:

  • haar classifier
  • lbp cascade classifier

most tutorials use haar because it is more accurate, but it is also much slower than lbp. i am going to stick with haar for this tutorial. the opencv package actually has all the data you need to use harr effectively. basically, you just need an xml file with the right face data in it. you could create your own if you knew what you were doing or you can just use what comes with opencv. i am not a data scientist, so i will be using the built-in classifier. in this case, you can find it in your opencv library that you installed. just go to the /lib/site-packages/cv2/data folder in your python installation and look for the haarcascade_frontalface_alt.xml . i copied that file out and put it in the same folder i wrote my face detection code in.

haar works by looking at a series of positive and negative images. basically someone went and tagged the features in a bunch of photos as either relevant or not and then ran it through a machine learning algorithm or a neural network. haar looks at edge, line and four-rectangle features. there's a pretty good explanation over on the opencv site . once you have the data, you don't need to do any further training unless you need to refine your detection algorithm.

now that we have the preliminaries out of the way, let's write some code.

the first thing we do here are our imports. the opencv bindings are called cv2 in python. then we create a function that accepts a path to an image file. we use opencv's imread method to read the image file and then we create a copy of it to prevent us from accidentally modifying the original image. next we convert the image to grayscale. you will find that computer vision almost always works better with gray than it does in color, or at least that is the case with opencv.

the next step is to load up the haar classifier using opencv's xml file. now we can attempt to find faces in our image using the classifier object's detectmultiscale method. i print out the number of faces that we found, if any. the classifier object actually returns an iterator of tuples. each tuple contains the x/y coordinates of the face it found as well as width and height of the face. we use this information to draw a rectangle around the face that was found using opencv's rectangle method. finally we show the result:

that worked pretty well with a photo of myself looking directly at the camera. just for fun, let's try running this royalty free image i found through our code:

when i ran this image in the code, i ended up with the following:

as you can see, opencv only found two of the four faces, so that particular cascades file isn't good enough for finding all the faces in the photo.

finding eyes in photos

opencv also has a haar cascade eye xml file for finding the eyes in photos. if you do a lot of photography, you probably know that when you do portraiture, you want to try to focus on the eyes. in fact, some cameras even have an eye autofocus capability. for example, i know sony has been bragging about their eye focus function for a couple of years now and it actually works pretty well in my tests of one of their cameras. it is likely using something like haars itself to find the eye in real time.

anyway, we need to modify our code a bit to make an eye finder script:

import cv2
import os

def find_faces(image_path):
    image = cv2.imread(image_path)

    # make a copy to prevent us from modifying the original
    color_img = image.copy()

    filename = os.path.basename(image_path)

    # opencv works best with gray images
    gray_img = cv2.cvtcolor(color_img, cv2.color_bgr2gray)

    # use opencv's built-in haar classifier
    haar_classifier = cv2.cascadeclassifier('haarcascade_frontalface_alt.xml')
    eye_cascade = cv2.cascadeclassifier('haarcascade_eye.xml')

    faces = haar_classifier.detectmultiscale(gray_img, scalefactor=1.1, minneighbors=5)
    print('number of faces found: {faces}'.format(faces=len(faces)))

    for (x, y, width, height) in faces:
        cv2.rectangle(color_img, (x, y), (x+width, y+height), (0, 255, 0), 2)
        roi_gray = gray_img[y:y+height, x:x+width]
        roi_color = color_img[y:y+height, x:x+width]
        eyes = eye_cascade.detectmultiscale(roi_gray)
        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

    # show the faces / eyes found
    cv2.imshow(filename, color_img)
    cv2.waitkey(0) 
    cv2.destroyallwindows()

if __name__ == '__main__':
    find_faces('headshot.jpg')


here we add a second cascade classifier object. this time around, we use opencv's built-in haarcascade_eye.xml file. the other change is in our loop where we loop over the faces found. here we also attempt to find the eyes and loop over them while drawing rectangles around them. i tried running my original headshot image through this new example and got the following:

this did a pretty good job, although it didn't draw the rectangle that well around the eye on the right.

wrapping up

opencv has lots of power to get you started doing computer vision with python. you don't need to write very many lines of code to create something useful. of course, you may need to do a lot more work than is shown in this tutorial training your data and refining your dataset to make this kind of code work properly. my understanding is that the training portion is the really time consuming part. anyway, i highly recommend checking out opencv and giving it a try. it's a really neat library with decent documentation.

related reading

  • opencv – face detection using haar cascades
  • face recognition with python
  • datasciencego – opencv face detectio n

OpenCV Python (language)

Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Important Data Structures and Algorithms for Data Engineers
  • 5 Common Firewall Misconfigurations and How to Address Them
  • The Beauty of Java Optional and Either
  • How To Select Multiple Checkboxes in Selenium WebDriver Using Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: