Introduction: Face Detection+recognition
This is a simple example of running face detection and recognition with OpenCV from a camera.
NOTE: I MADE THIS PROJECT FOR SENSOR CONTEST AND I USED CAMERA AS A SENSOR TO TRACK AND RECOGNITION FACES.
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):
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. cap.release() out.release()
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: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 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: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) print "found " +str(len(faces)) +" face(s)" cv2.imshow('img',img) k = cv2.waitKey(30) & 0xff if k == 27: break cap.release() cv2.destroyAllWindows()
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') sampleN=0; 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: sampleN=sampleN+1; cv2.imwrite("F:/Program Files/projects/face_rec/facesData/User."+str(id)+ "." +str(sampleN)+ ".jpg", gray[y:y+h, x:x+w]) cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) cv2.waitKey(100) cv2.imshow('img',img) cv2.waitKey(1) if sampleN > 20: break cap.release() cv2.destroyAllWindows()
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 #getImagesWithID(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(".")) # Detect the face in the image faces.append(faceNP) IDs.append(ID) cv2.imshow("Adding faces for traning",faceNP) cv2.waitKey(10) return np.array(IDs), faces Ids,faces = getImagesWithID(path) recognizer.train(faces,Ids) recognizer.save("F:/Program Files/projects/face_rec/faceREC/trainingdata.yml") cv2.destroyAllWindows()
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
IN THIS STEP THERE ARE TWO OPERATIONS WHICH ARE GOING TO PERFORME....
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 :)
pankaj4tech made it!
We have a be nice policy.
Please be positive and constructive.
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 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