Face Detection+recognition





Introduction: Face Detection+recognition

About: I am an Engineer in the field of Embedded system & Robotics.

This is a simple example of running face detection and recognition with OpenCV from a camera.


So, Our Goal

In this session,

1. Install Anaconda
2. Download Open CV Package
3. Set Environmental Variables
4. Test to confirm
5. Make code for face detection
6. Make code to create data set
7. Make code to train the recognizer
8. Make code to recognize the faces &Result.

Step 1: Install Anaconda

Anaconda is essentially a nicely packaged Python IDE that is shipped with tons of useful packages, such as NumPy, Pandas, IPython Notebook, etc. It seems to be recommended everywhere in the scientific community. Check out Anaconda to get it installed.

Step 2: Download Open CV Package

Firstly, go to the official OpenCV site to download the complete OpenCV package. Pick a version you like (2.x or 3.x). I am on Python 2.x and OpenCV 2.x - mainly because this is how the OpenCV-Python Tutorials are setup/based on.

In my case, I've extracted the package (essentially a folder) straight to my F drive. (F:\opencv).

Step 3: Set Environmental Variables

Copy and Paste the cv2.pyd file

The Anaconda Site-packages directory (e.g. F:\Program Files\Anaconda2\Lib\site-packages in my case) contains the Python packages that you may import. Our goal is to copy and paste the cv2.pyd file to this directory (so that we can use the import cv2 in our Python codes.).

To do this, copy the cv2.pyd file...

From this OpenCV directory (the beginning part might be slightly different on your machine):

# Python 2.7 and 64-bit machine: F:\opencv\build\python\2.7\x64
# Python 2.7 and 32-bit machine: F:\opencv\build\python\2.7\x84

To this Anaconda directory (the beginning part might be slightly different on your machine):

 F:\Program Files\Anaconda2\Lib\site-packages

After performing this step we shall now be able to use import cv2 in Python code. BUT, we still need to do a little bit more work to get FFMPEG (video codec) to work (to enable us to do things like processing videos.)

Right-click on "My Computer" (or "This PC" on Windows 8.1) -> left-click Properties -> left-click "Advanced" tab -> left-click "Environment Variables..." button.
Add a new User Variable to point to the OpenCV (either x86 for 32-bit system or x64 for 64-bit system.) I am currently on a 64-bit machine.



Append %OPENCV_DIR%\bin to the User Variable PATH.

For example, my PATH user variable looks like this...





This is it we are done! FFMPEG is ready to be used!

Step 4: Test to Confirm

We need to test whether we can now do these in Anaconda (via Spyder IDE):

  • Import OpenCV package
  • Use the FFMPEG utility (to read/write/process videos)

Test 1: Can we import OpenCV?

To confrim that Anaconda is now able to import the OpenCV-Python package (namely, cv2),

issue these in the IPython Console:

import cv2

print cv2.__version__

If the package cv2 is imported ok with no errors, and the cv2 version is printed out, then we are all good!

Test 2: Can we Use the FFMPEG codec?

Place a sample


video file in a directory. We want to test whether we can:

  • read this .mp4 video file, and
  • write out a new video file (can be .avi or .mp4 etc.)

To do this we need to have a test python code, call it test.py. Place it in the same directory as the sample



This is what


may look like (Note: many thanks to Pete's and Warren's suggestions in the comment field - I have replaced my original test code with his - please test it yourself and let us know if this works better):

import cv2

cap = cv2.VideoCapture("input_video.mp4")

print cap.isOpened()   # True = read video successfully. False - fail to read video.

fourcc = cv2.VideoWriter_fourcc(*'XVID')

out = cv2.VideoWriter("output_video.avi", fourcc, 20.0, (640, 360))

print out.isOpened()  # True = write out video successfully. False - fail to write out video.



This test is VERY IMPORTANT. If you'd like to process video files, you'd need to ensure that Anaconda / Spyder IDE can use the FFMPEG (video codec). It took me days to have got it working. But I hope it would take you much less time! :)
Note: one more very important tip when using the Anaconda Spyder IDE. Make sure you check the Current Working Directory (CWD)!!!

Step 5: Make Code for Face Detection


In this session,

  • We will see the basics of face detection using Haar Feature-based Cascade Classifiers
  • We will extend the same for eye detection etc

Haar-cascade Detection in OpenCV

Here we will deal with detection. OpenCV already contains many pre-trained classifiers for face, eyes, smile etc. Those XML files are stored in opencv/data/haarcascades/ folder. Let's create face and eye detector with OpenCV.
First we need to load the required XML classifiers. Then load our input image (or video) in grayscale mode OR we can use camera( for Real time face detection)

import numpy as np

import cv2

face_cascade = cv2.CascadeClassifier('F:/Program Files/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')

eye_cascade = cv2.CascadeClassifier('F:/Program Files/opencv/sources/data/haarcascades/haarcascade_eye.xml')

cap = cv2.VideoCapture(0)<br>while 1:

    ret, img = cap.read()

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.5, 5)

    for (x,y,w,h) in faces:


        roi_gray = gray[y:y+h, x:x+w]

        roi_color = img[y:y+h, x:x+w]

        eyes = eye_cascade.detectMultiScale(roi_gray)

        for (ex,ey,ew,eh) in eyes:


    print "found " +str(len(faces)) +" face(s)"


    k = cv2.waitKey(30) & 0xff

    if k == 27:




Step 6: Make Code to Create Data Set

We are doing face recognition, so you’ll need some face images! You can either create your own dataset or start with one of the available face databases, http://face-rec.org/databases/ gives you an up-to-date overview. Three interesting databases are (parts of the description are quoted from http://face-rec.org):

  • AT&T Facedatabase
  • Yale Facedatabase A
  • Extended Yale Facedatabase B

HERE i m using my own dataset....with the help of code which is given below:

import numpy as np

import cv2

face_cascade = cv2.CascadeClassifier('F:/Program Files/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)

id = raw_input('enter user id')


while 1:

    ret, img = cap.read()

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in faces:


        cv2.imwrite("F:/Program Files/projects/face_rec/facesData/User."+str(id)+ "." +str(sampleN)+ ".jpg", gray[y:y+h, x:x+w])





    if sampleN > 20:




Step 7: Make Code to Train the Recognizer

Create the function to prepare the training set

Now, we will define a function


that takes the absolute path to the image database as input argument and returns tuple of 2 list, one containing the detected faces and the other containing the corresponding label for that face. For example, if the ith index in the list of faces represents the 5th individual in the database, then the corresponding ith location in the list of labels has value equal to 5.

Now convert the dataset faces(which is created in step 6) into .yml file with the help of code which is given below:

import os

import numpy as np

import cv2

from PIL import Image # For face recognition we will the the LBPH Face Recognizer 

recognizer = cv2.createLBPHFaceRecognizer();

path="F:/Program Files/projects/face_rec/facesData"

def getImagesWithID(path):

    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]   

 # print image_path   


    faces = []

    IDs = []

    for imagePath in imagePaths:      

  # Read the image and convert to grayscale

        facesImg = Image.open(imagePath).convert('L')

        faceNP = np.array(facesImg, 'uint8')

        # Get the label of the image

        ID= int(os.path.split(imagePath)[-1].split(".")[1])

         # Detect the face in the image



        cv2.imshow("Adding faces for traning",faceNP)


    return np.array(IDs), faces

Ids,faces  = getImagesWithID(path)


recognizer.save("F:/Program Files/projects/face_rec/faceREC/trainingdata.yml")


by using this code all face dataset converted into a single .yml file.....path location is ("F:/Program Files/projects/face_rec/faceREC/trainingdata.yml")

Step 8: Make Code to Recognize the Faces & Result

Guyzz this is the final step in which we can create the code to recognize the faces with the help of your webcam

1. capturing the video from cam
2. compare it with your .yml file

import numpy as np
import cv2 face_cascade = cv2.CascadeClassifier('F:/Program Files/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml') cap = cv2.VideoCapture(0) rec = cv2.createLBPHFaceRecognizer(); rec.load("F:/Program Files/projects/face_rec/faceREC/trainingdata.yml") id=0 font=cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_COMPLEX_SMALL,5,1,0,4) while 1: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.5, 5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) id,conf=rec.predict(gray[y:y+h,x:x+w]) if(id==2): id="alok" if id==1: id="alok" if id==3: id="anjali" if id==4: id="Gaurav" if id==5: id='rahul' if id==6: id="akshay" cv2.cv.PutText(cv2.cv.fromarray(img),str(id),(x,y+h),font,255) cv2.imshow('img',img) if cv2.waitKey(1) == ord('q'): break cap.release()


and finally result will came in front off your eyes......

u can also download the zip file from below the link :

Click here to download the codes

So, in this instructable we performed the task of face detection+recognition using OpenCV.....if you like this instructable..... plzzz subscribe me and vote for me .....thanks friends :)



  • Oil Contest

    Oil Contest
  • Clocks Contest

    Clocks Contest
  • Creative Misuse Contest

    Creative Misuse Contest

25 Discussions

i am working on face recognition as well, using LBPH recognizer but i am not able to figure out one thing, in the recognizer we feed two lists

  1. the image
  2. the label

but how does the recognizer links the label with the image to know which image belongs to which label, please help, thank you


Question 2 months ago

I'm using same concept to detect and recognize face I need a little help from you I'm using opencv and python 3 for my work.

Please answer to my questions asap.

Q no 1:when I try to detect a face that is not in my dataset or training data then it predicts me with false result?

Q no 2:I also wanted to know weather the image contains face or not?

1 more answer

1: yes it will give u false result and u can use else : print("unknown person")

2:yes, image contains faces..

Face recognition is in the process of registering. If more than one person passes in front of the camera, faces are confused. How can I separate them? You help me please.

3 replies

if you trained your system with 1000k samples for 1 person i think after that your problem will be solved ...

Thank you very much. I made the application, it works for 1 face. But when trying to record more than one face, hundreds are getting involved. The face is going to someone else.

I education 21 piece face for one people.I want to recognition more face at synchronous.And I want to educate 21 pictures for everyone. Make these things at the same time. No one ever complains. Thank you for your answer.

need help,

everything is working fine so far, just wanted to ask how can I save the data of those whose face is getting recognized into an excel sheet or anywhere


2 replies

I am just trying to make the attendance marking project

You have to read about file concept like how to open,close or append file by using python...

there is no yml file has been created while training the data.but the images in the dataset has been read.how can get rid of this?

i am trying to do the face detection but am not knowing how to remove this error.

My system onboard camra switches on but no output comes along with this error popping up


Question 5 months ago

I am using python3.6, cv 3.3.1, my issue is I detect the perfectly and train is also working fine, but
when I run recognition some issue is occur:-

in this line cv2.cv is not working , and InitFont is also. , I remove the cv

in this line load is not working , I can change it to read .

so tell me the solution why its not working.

This program is not reading video successfully


esp8266 is a wi-fi module.Tell me more about ur project what you want to do.

hello sir
please i want the algorithim of object track by python ?because i use the raspberry pi :(

2 replies

object tracking is another project but if u want to make this project on raspberry pi... coding is same...

are u done this project on raspberry pi

I done something like this when I studied in university. Good instructable!