Face Detection Using OpenCV In Python | How To Setup OpenCV Python

Opencv is the most popular computer vision library, and today we are going to learn how to setup opencv, how to access your webcam and how easily we can write a face detection program with just a few lines of code.

Hi there, this is me Anirban, writing my first blog on face detection, I am a crazy person, and if you are like me you might like the stuff that are in my blog.
In my posts I will give you detailed description of the project that we are going to work on as well as a video tutorial of the same at the end of the post.
Before starting, I am assuming you already has a good knowledge in python, and if you are not confident,
Here are some suggested ebooks for python, to build your background in python first, this will help you to understand things later on,.
Additionally here is a suggested ebook to get started with opencv,
So without wasting anymore time lets move to the main stuff.

To setup opencv in python environment you will need these things ready ( match the versions to follow along with this tutorial),

First thing first download python and install it in its default location (i.e c:/python27)
after you have installed it download the opencv and extract it, go to “opencv/Build/python/2.7/x86” folder and copy “cv2.pyd” file to “c:/python27/Lib/site-packages/” folder.
And now we are ready to use opencv in python. just one single problem is there, Opencv uses numpy library for its images so we have to install numpy library too, Lets do that
Go to start and type “cmd” you will see the command prompt icon right click on it and select “run as administrator” this will bring us to the cmd window,
Now type
“cd c:/python27/scripts/”
hit enter then type
“pip install numpy”
This will install the numpy library in your python packages

Now We Are Ready To Do Some Coding

Go to Start and search “IDLE” and open it
To use opencv we need to import the opencv library first,
import cv2
After that we need to import the numpy library
import numpy as np
so now we can use opencv and numpy in our code
Now that everything is setup and running lets write a code to detect faces from the webcam.
This is kind of hello world program for opencv
The method that we are going to use in this program is a cascade classifier, which can be loaded with a pretrained xml file, these xml files are hard to train but luckily we dont have to worry opencv already has many of these pretrained classifier ready for face detection.
To use the face detection classifier we need to copy the classifier xml file from the “[opencv extracted folder]/sources/data/haarcascades/”, and then copy the file haarcascade_frontalface_default.xml to your project folder (same location where you will save the python program)
Now thats done we can proceed further
we can load the classifier now
detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
let add the video capture object now
cap=cv2.VideoCapture(0)
In the above line VideoCapture has one argument which is device id, for inbuilt webcam its usually ‘0’, and if you have some other webcam you can change that number so see that is your webcam’s Id
so lets test the camera now
ret,img=cap.read()
cv2.imshow('windowname',img)
cv2.waitKey(0)
Image of a persion captured by opencv
looks like its working fine
in the above code we read the image from the video capture object using cap.read() method, it returns one status variable which is just True/False and the captured frame then we used imshow() method to display the image, here first argument is the window name and second argument is the image that we want to display, the third line we used waitKey(10) is used for a delay of 10 milisecond it is important for the imshow() method to work properly
Before using the face detector we need comvert the captured image to Gray scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Now lets apply the face detector to detect faces in our captured image
faces = detector.detectMultiScale(gray, 1.3, 5)
the above line will get the x,y and height,width of all the faces present in the captured image in a list, So now we have to loop through all the faces and draw rectangle there
for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
I think its clear what this code is doing, let me explain the rectangle() the first argument is the input image in which we are going to draw the rectangles, second is the x,y coordinate of the face, then the height and weight, after that we are specifying the color of the line which is in the form of (blue,green,red) and you can adjust the value of each color, the range is 0-255, in this case its a green line, and the last argument is the line thickness
Now that we have marked the faces with green rectangles we can display them
cv2.imshow('frame',img)
cv2.waitKey(0)
image of face detection of a persion

Almost Done!!

now to detect face from the webcam live, we need to create a loop which will get the images form the webcam frame by frame and detect the faces and show them in a window. so if we arrange the above code in a loop it will look like this
while(True):
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = detector.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

    cv2.imshow('frame',img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
You can see that I changed the “waitKey” , because it aslo returns the value of the key pressed in the keyboard so we are comparing it with the key ‘q’ if its true the we are breaking the loop
after the program ends we need to release the video capture object and distroy all the windows
cap.release()
cv2.destroyAllWindows()

The Complete Face Detection Code In One Piece

import numpy as np
import cv2

detector= cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)

while(True):
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = detector.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

    cv2.imshow('frame',img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
cap.release()
cv2.destroyAllWindows()

The Complete Video Tutorial

Summary

In this post, you discovered how to setup opencv in python, and wrote your own face detection program
Specifically, you learned the most basic steps in opencv including:

  • How to use a classifier.
  • How to read images from camera
  • How to Draw on images
  • How to display images
  • Mainly you learnt face detection in real-time

Do you have any questions about opencv or about this tutorial?
Ask your question in the comments and I will do my best to answer.

You May also like

  • Nazeer

    awesome dear , i want to know how to hand gesture recognise , iam new to opencv and python will you help
    thanks

    • Anirban

      this is actually more advanced topic.. and as you are a beginner I advice you to learn the basics first like cascade classifiers and image segmentation, contours etc, then you will be able to understand guesture recognition more easily

  • Dhruv

    error
    Traceback (most recent call last):
    File “C:/Users/Dell/AppData/Desktop/Project/P.py”, line 9, in
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    error: ..\..\..\..\opencv\modules\imgproc\src\color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor
    Code
    import numpy as np
    import cv2

    detector= cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)
    cap = cv2.VideoCapture(0)

    while(True):
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = detector.detectMultiScale(gray, 1.3, 5)
    if(len(faces)!=0):
    for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

    cv2.imshow(‘frame’,img)
    if cv2.waitKey(1) & 0xFF == ord(‘q’):
    break

    cap.release()
    cv2.destroyAllWindows()

    • Anirban

      add “print ret” after this line “ret, img = cap.read()” and see if its printing “false” if yes then there might be some issue with the camera try changing the device id in the line “cv2.VideoCapture(0)” to other number like “cv2.VideoCapture(1)”

    • JohnnyBlaze

      Use cap.read() before entering the while loop. This will help your camera to spool up

  • Befkadu Belete

    Hi Anirban !

    This is very good job, all are work for me .
    Anirban, how can i used this script for lip reading ?

    if you have any idea about this ,pls help me , Thanks

    • Anirban

      aaa.. I dont have any Idea 🙂

  • ram

    I am getting this error
    Traceback (most recent call last):
    File “C:\face_recognizer\face_recognizer.py”, line 10, in
    faceCascade = cv2.CascadeClassifier(cascadePath)
    AttributeError: ‘module’ object has no attribute ‘CascadeClassifier’

    • Anirban

      did you check your opencv version ?? is it 2/3?

  • Jude

    HI Anirban:
    Do you know why my fram of webcam is black screen, thanks so much for your help.
    Thanks

    • try changing the webcam device id

  • J.K. Gravett

    Good post. I noticed that at the beginning you said:

    “To setup opencv in python environment you will need these things ready:
    – Python 2.x (NOT 3.x)
    – OpenCV 2.x (Again NOT 3.x)
    – Numpy library (later will download it using pip)”

    I assume you meant in order to specifically follow along with your post because you can use Python 3.x with OpenCV(3.x). Just saying, in case that was holding someone back from trying OpenCv that had moved on to Python 3.

    • Yeah it just in order to follow along with this tutorial.. let me edit my statement there

  • Andrea

    Hello Anirban,

    Great tutorial!
    I am trying to run the code, I do not get any errors, and the camera seems to be working. But I am not able to se the square around the faces. I already copied the haarcascade_frontalface_default.xml file to the same python project folder.
    How can i fix this?
    Thank you,
    Andrea

    • hi Andrea Sorry for late reply. if you haven’t solved it yet. can you post the code here ?

  • Aladdin

    Hello,
    in your code you used a casscade scripts that built in the cv2 library
    detector= cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)

    if i want to use another file like HOG code that i have on another python file how should i change this the line above in order to call the external code

    t hx
    Aladdin

    • just use your classifier file name instead of “‘haarcascade_frontalface_default.xml’”

  • Ryo Takagi

    I need Help! I did everything you did and it was working fine the first day, but the next day I got the error below. I even reset cleaned my PC and reinstalled but still got this.
    Traceback (most recent call last):
    File “C:UsersrtakaDesktopFaceDetectiontestlol.py”, line 9, in
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    error: ……..opencvmodulesimgprocsrccolor.cpp:3739: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor