Introduction: Face Detection+recognition

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

Picture of 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

Picture of 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

Picture of 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

Picture of 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<br>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 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<br>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

Picture of 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)
while 1:
ret, img =
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

Picture of 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, gives you an up-to-date overview. Three interesting databases are (parts of the description are quoted from

  • 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 =
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)</p><p> 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

Picture of 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
mport 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 ='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.train(faces,Ids)"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,5,1,0,4) while 1: ret, img = 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",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 :)


noorthamer (author)2017-02-28

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

alok014 (author)noorthamer2017-10-18

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

durgshc (author)noorthamer2017-10-13

are u done this project on raspberry pi

pankaj4tech made it! (author)2017-10-05

I made it. its awesome project.

alok014 (author)pankaj4tech2017-10-05


geovas333 (author)2017-02-05

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

JustinC257 (author)geovas3332017-09-14

what major did you do at the university?

rehana25 (author)2017-02-15

Is this boot inside the arduino controller?

NguyễnĐ29 (author)2017-02-06

Awesome! More instructable pls :x

mderton (author)2017-01-31

This is Awesome!

alok014 (author)mderton2017-02-02


About This Instructable



Bio: can't say about my self it's totally depends on ur behavior
More by alok014:Diwali SpecialGesture Controlled MouseGetting Started With ARDUINO
Add instructable to: