To perform face recognition we need to train a face recognizer, using a pre labeled dataset, In my previous post we created a labeled dataset for our face recognition system, now its time to use that dataset to train a face recognizer using opencv python,
[ictt-tweet-inline hashtags=”#opencv, #python, #facerecognition” via=”via thecodacus”]Lets Train A Face Recognizer[/ictt-tweet-inline]
First create a python “trainner.py” file in the same folder where we saved out dataset generator script in the previous post, and then create a folder in the same directory name it “trainner”, this is the folder where we are going to save our recognizer after training.
So the folder structure till now should be something like this
Those who don’t know how we got the dataset folder and script , it was created in my previous post you should check that first.
Before we start actual coding we need a new library called pillow,
open your cmd (run as administrator )and type following command to navigate to your python pip directory:
“cd c:/python27/scripts/”
now type the following to install pillow:
“pip install pillow”
this will install the latest version of pillow in your python library
Lets Start Coding
So now we rare ready to code the trainner,
Just like all the other opencv script we need:
import the opencv / cv2 library,
we will need the os to accress the file list in out dataset folder,
we also need to import the numpy library,
and we need to import the pillow / PIL library we installed before,
It will look something like this:
import cv2,os
import numpy as np
from PIL import Image
Now we need to initialize the recognizer and the face detector
recognizer = cv2.createLBPHFaceRecognizer()
detector= cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
Load The Training Data
Ok, now we will are going to create a function which will grab the training images from the dataset folder, and will also get the corresponding Ids from its file name, (remember we formatted the filename to be like User.id.samplenumber in our previous script)
So I am going to name this function “getImagesAndLabels” we need the path of the dataset folder so we will provide the folder path as argument. So the function will be like this
def getImagesAndLabels(path):
So now inside this function we are going to do the following
- Load the training images from dataset folder
- capture the faces and Id from the training images
- Put them In a List of Ids and FaceSamples and return it
To load the image we need to create the paths of the image
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
this will get the path of each images in the folder.
now we need to create two lists for faces and Ids to store the faces and Ids
faceSamples=[]
Ids=[]
Now we will loop the images using the image path and will load those images and Ids, we will add that in your lists
for imagePath in imagePaths:
pilImage=Image.open(imagePath).convert('L')
imageNp=np.array(pilImage,'uint8')
Id=int(os.path.split(imagePath)[-1].split(".")[1])
faces=detector.detectMultiScale(imageNp)
for (x,y,w,h) in faces:
faceSamples.append(imageNp[y:y+h,x:x+w])
Ids.append(Id)
In the above code we used used “Image.open(imagePath).convert(‘L’)” is loading the image and converting it to gray scale, but now its a PIL image we need to convert it to numpy array.
for that we are converting it to numpy array “imageNP=np.array(pilImage,’uint8′)”.
To get the Id we split the image path and took the first from the last part (which is “-1” in python) and that is the name of the imagefile. now here is the trick, we saved the file name in our previous program like this “User.Id.SampleNumber” so if we split this using “.” the we will get 3 token in a list “User”, “Id”, “SampleNumber”
so to get the Id we will choone 1st index (index starts from 0)
So we get:
Id=int(os.path.split(imagePath)[-1].split(".")[1])
Now we are using the detector to extract the faces and append them in the faceSamples list with the Id
which looks like:
for (x,y,w,h) in faces:
faceSamples.append(imageNp[y:y+h,x:x+w])
Ids.append(Id)
So we are done now we just have to return that value
return faceSamples,Ids
Now the entire function will look like this
def getImagesAndLabels(path):
#get the path of all the files in the folder
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
#create empth face list
faceSamples=[]
#create empty ID list
Ids=[]
#now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
#loading the image and converting it to gray scale
pilImage=Image.open(imagePath).convert('L')
#Now we are converting the PIL image into numpy array
imageNp=np.array(pilImage,'uint8')
#getting the Id from the image
Id=int(os.path.split(imagePath)[-1].split(".")[1])
# extract the face from the training image sample
faces=detector.detectMultiScale(imageNp)
#If a face is there then append that in the list as well as Id of it
for (x,y,w,h) in faces:
faceSamples.append(imageNp[y:y+h,x:x+w])
Ids.append(Id)
return faceSamples,Ids
Almost Done!!
We are almost finished, now we just have to call that function and feed the data to the recognizer to train
faces,Ids = getImagesAndLabels('dataSet')
recognizer.train(faces, np.array(Ids))
recognizer.save('trainner/trainner.yml')
Thats it!!
Now if we run this code it will create a “trainner.yml” file inside the trainner folder,
We will use this file in our next post to actually recognize the faces that we trained the face recognizer to recognize,
The Complete Code
import cv2,os
import numpy as np
from PIL import Image
recognizer = cv2.createLBPHFaceRecognizer()
detector= cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
def getImagesAndLabels(path):
#get the path of all the files in the folder
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
#create empth face list
faceSamples=[]
#create empty ID list
Ids=[]
#now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
#loading the image and converting it to gray scale
pilImage=Image.open(imagePath).convert('L')
#Now we are converting the PIL image into numpy array
imageNp=np.array(pilImage,'uint8')
#getting the Id from the image
Id=int(os.path.split(imagePath)[-1].split(".")[1])
# extract the face from the training image sample
faces=detector.detectMultiScale(imageNp)
#If a face is there then append that in the list as well as Id of it
for (x,y,w,h) in faces:
faceSamples.append(imageNp[y:y+h,x:x+w])
Ids.append(Id)
return faceSamples,Ids
faces,Ids = getImagesAndLabels('dataSet')
recognizer.train(faces, np.array(Ids))
recognizer.save('trainner/trainner.yml')
Now The Complete Video Tutorial
Updates:
To make sure the trainner doesn’t take any file other that the jpg files we will add an if condition in the method
import cv2,os
import numpy as np
from PIL import Image
recognizer = cv2.createLBPHFaceRecognizer()
detector= cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
def getImagesAndLabels(path):
#get the path of all the files in the folder
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
#create empth face list
faceSamples=[]
#create empty ID list
Ids=[]
#now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
# Updates in Code
# ignore if the file does not have jpg extension :
if(os.path.split(imagePath)[-1].split(".")[-1]!='jpg'):
continue
#loading the image and converting it to gray scale
pilImage=Image.open(imagePath).convert('L')
#Now we are converting the PIL image into numpy array
imageNp=np.array(pilImage,'uint8')
#getting the Id from the image
Id=int(os.path.split(imagePath)[-1].split(".")[1])
# extract the face from the training image sample
faces=detector.detectMultiScale(imageNp)
#If a face is there then append that in the list as well as Id of it
for (x,y,w,h) in faces:
faceSamples.append(imageNp[y:y+h,x:x+w])
Ids.append(Id)
return faceSamples,Ids
faces,Ids = getImagesAndLabels('dataSet')
recognizer.train(faces, np.array(Ids))
recognizer.save('trainner/trainner.yml')
Github links:
For this code: you can visit: https://github.com/thecodacus/Face-Recognition
nazmi69 has done a good job converting the code for python 3.x and opencv 3.0
available at https://github.com/nazmi69/Face-Recognition
Hi, I’m new in the openCV programming. I’ve openCV 3.2 (+ openCV contrib) installed on my PC with python 2.7 and when I compile the code appears this error:
recognizer = cv2.createEigenFaceRecognizer()
AttributeError: ‘module’ object has no attribute ‘face’
I’ve searched in forums and they suggest to put ‘face.’ before ‘createEigenFaceRecognizer()’ or to substitute ‘cv2.createEigenFaceRecognizer()’ with ‘cv2.createFisherFaceRecognizer()’ etc… I haven’t solved my problem… What can I do?
Thanks in advance and sorry for my bad English.
Why dont you try opencv2, you wont find and any issue with that
here is the step by step tutorial how to setup opencv2
http://thecodacus.com/opencv-python-face-detection/
The reason this no longer works is because the face recognition module has been moved out of the core OpenCV library from version 3. It now exists in a separate sub-library called ‘opencv_contrib’ which is less well supported and harder to get up and running. The joys of open source.
The Github page for the contributions module is here:
https://github.com/Itseez/o…
Theoretically if you can get that installed and built you should be able to access the face recognition module by changing ‘cv2.createLBPHFaceRecognizer’ to cv2.face.createLBPHFaceRecognizer’ but its possible the python bindings might not be up to date.
When the next? Thanks for the tuto
it will be updated soon, you can subscribe to this blog, you will get notified when ever there is a new post
Hello Anirban;
When i use
recognizer = cv2.createEigenFaceRecognizer()
an error occur that say “In Eigenfaces method all input samples (training images) must be of equal size! “.All images must be in same height and width (in pixel).
How can i create a dataset with this condition?
Thanks in advance.
you can use
face=cv2.resize(imageNp[y:y+h,x:x+w],(100,100))
faceSamples.append(face)
now all the samples will be same size always
Getting following error,
File “two_train.py”, line 35, in
faces,Ids = getImagesAndLabels(‘dataSet’)
File “two_train.py”, line 19, in getImagesAndLabels
pilImage=Image.open(imagePath).convert(‘L’)
File “/home/pi/.virtualenvs/cv/lib/python3.4/site-packages/PIL/Image.py”, line 2349, in open
% (filename if filename else fp))
OSError: cannot identify image file ‘dataSet/.DS_Store’
P.S: it takes 50% of data set and then it shows this error.
Actually there is a hidden file “dataSet/.DS_Store” -> “.DS_Store” and the script is taking that as input but not able to convert it as image, try to remove that file from the folder and it will work
where does that hidden file reside?
hey gaurav sorry for not replying sooner,
try this split the image path in by “.” so the 2nd part will be jpeg after “.” if its not then its not an image
token=imagePath.split(“.”)
if(token[-1]==’jpg’):
# put the rest of the code inside
Hello Anirban, I am having a similar issue, I am trying to filter out the hidden .DS_Store file, but I don’t quite understand your solution
Where should this occur?
token=imagePath.split(“.”)
if(token[1]==’jpeg’):
# put the rest of the code inside
As a component of this?
Id= int(os.path.split(imagePath)[-1].split(“.”)[1])
Thank you so much! Your tutorial has been great so far
I will modify the code in the blog itself so that every one can see this
HI, I am Shyam I using ubuntu 16.04 how could I have to do and save trainer/trainer .yml file can you help me for that. And you had changed the code in a video but you not mentioned in website.Did you face any problem in it?
anticipating for yor answer ,,,,
Hi Shyam, If you have saved your python script in the same folder as the “trainner” folder like in the image that is shown in the post then.
recognizer.save(‘trainner/trainner.yml’)
this above line will save the yml file inside the “trainner” folder. even if you are using ubuntu its not a problem and if your script is in a different location then
recognizer.save(‘[Fullpath]/trainner/trainner.yml’)
you have to enter the full path of the “trainner” folder then it will work
and about the difference in the blog and the video, its actually i didn’t wrote the both code same time so there is some difference in code but both logic is same you can follow any of them both will work. while writing the blog i broken down the code so that it becomes easier to explain in the blog that’s it
Hey That I am have been another doubt.This tutorial is for save yml file or we can check the face of our ID. It is confusing me can you explain to me.
This is only for face checking or Id checking
its just for training the recognizer with the dataset that we created in the previous post and save the recognizer in a file, in the next post we are using that file to recognize the faces
Getting this error how to resolve it please help
Traceback (most recent call last):
File “F:\New folder (6)\face reco\trainner.py”, line 21, in
Ids,faces=getImagesWithID(path)
File “F:\New folder (6)\face reco\trainner.py”, line 12, in getImagesWithID
faceImg=Image.open(imagePath).convert(‘L’);
File “C:\Python27\lib\site-packages\PIL\Image.py”, line 2349, in open
% (filename if filename else fp))
IOError: cannot identify image file ‘dataSet\\Thumbs.db’
I’m having the same error.. somebody please fix this !
This is fixed after doing this :
import cv2,os
import numpy as np
from PIL import Image
recognizer = cv2.createLBPHFaceRecognizer()
detector= cv2.CascadeClassifier(“haarcascade_frontalface_default.xml”);
def getImagesAndLabels(path):
#get the path of all the files in the folder
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
#create empth face list
faceSamples=[]
#create empty ID list
Ids=[]
#now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
token = imagePath.split(“.”)
if(token[1] ==’jpeg’):
#loading the image and converting it to gray scale
pilImage=Image.open(imagePath).convert(‘L’)
#Now we are converting the PIL image into numpy array
imageNp=np.array(pilImage,’uint8′)
#getting the Id from the image
Id=int(os.path.split(imagePath)[-1].split(“.”)[1])
# extract the face from the training image sample
faces=detector.detectMultiScale(imageNp)
#If a face is there then append that in the list as well as Id of it
for (x,y,w,h) in faces:
faceSamples.append(imageNp[y:y+h,x:x+w])
Ids.append(Id)
return faceSamples,Ids
faces,Ids = getImagesAndLabels(‘dataSet’)
recognizer.train(faces, np.array(Ids))
recognizer.save(‘trainner/trainner.yml’)
But having a new error :
Traceback (most recent call last):
File “C:\Users\User\Desktop\python opencv\Face Recog\trainner.py”, line 34, in
recognizer.train(faces, np.array(Ids))
error: ..\..\..\..\opencv\modules\contrib\src\facerec.cpp:917: error: (-210) Empty training data was given. You’ll need more than one sample to learn a model. in function cv::LBPH::train
did you manage to fix this issue?
same error
sorry did a mistake there,
in the dataset generator we used the extension as “jpg”
so if we change the line “if(token[1] ==’jpeg’):” to “if(token[-1] ==’jpg’):” it will work..
Getting this error. unable to solve. ( I followed your code from youTube)
Traceback (most recent call last):
File “K:/python project/face recognition/trainer.py”, line 25, in
recognizer.train(faces,Ids)
TypeError: labels data type = 18 is not supported.
when i pasted the code from this blog it works fine.
So it’s working then… maybe you mistype something previously
Hello,
How could I apply the same detection and recognition techniques but with a browse button instead of capturing it through the cam?
use cv2.VideoCapture(‘videofilepath’) instead of cv2.VideoCapture(0)… works well for avi
hey Anirban,
Thanks for the tutorial. But i am getting this error.
Traceback (most recent call last):
File “C:/Python27/prog/facerecog/trainner.py”, line 33, in
recognizer.train(faces, np.array(Ids))
TypeError: labels data type = 17 is not supported
change the variable name “id” if you are using it anywhere.. it causes issue in some cases
i am facing ….”””AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer “”‘
error …. what should i do….
this tutorials are based on opencv 2.. so opencv3 wont work with these.. try with opencv 2
use cv2.face.createEigenFaceRecognizer()
The reason this no longer works is because the face recognition module has been moved out of the core OpenCV library from version 3. It now exists in a separate sub-library called ‘opencv_contrib’ which is less well supported and harder to get up and running. The joys of open source.
The Github page for the contributions module is here:
https://github.com/Itseez/o…
Theoretically if you can get that installed and built you should be able to access the face recognition module by changing ‘cv2.createLBPHFaceRecognizer’ to cv2.face.createLBPHFaceRecognizer’ but its possible the python bindings might not be up to date.
hello sir
am developing your code on Anaconda navigator (Spyder) and python 3
all the previous codes works fine but only in this code I get this error
recognizer= cv2.createLBPHFaceRecognizer()
AttributeError: module ‘cv2’ has no attribute ‘createLBPHFaceRecognizer’
did you check your opencv version ?? is it 2/3? cuz in opencv 3 you dont have “createLBPHFaceRecognizer” out of the box
So, if we are download open cv3. how can we solve this issue with this version.
you have to compile the contrib library and face module. then you can use “cv2.face.createLBPHFaceRecognizer()”
hello sir I am using opencv 3.1.0 on raspberry pi and I am faced with the error
recognizer= cv2.createLBPHFaceRecognizer()
AttributeError: module ‘cv2’ has no attribute
I have downloaded the contrib library how do I compile it I currently have the library in my download do have to move it to my opencv3.1.0 folder
And how to do it ?
hello. I’m having this error.
AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’
you must be using opencv3
The reason this no longer works is because the face recognition module has been moved out of the core OpenCV library from version 3. It now exists in a separate sub-library called ‘opencv_contrib’ which is less well supported and harder to get up and running. The joys of open source.
The Github page for the contributions module is here:
https://github.com/Itseez/o…
Theoretically if you can get that installed and built you should be able to access the face recognition module by changing ‘cv2.createLBPHFaceRecognizer’ to cv2.face.createLBPHFaceRecognizer’ but its possible the python bindings might not be up to date.
hi Sir
I copy your code and run it but it error
Traceback (most recent call last):
File “trainner.py”, line 31, in
faces,Ids = getImagesAndLabels(‘dataSet’)
File “trainner.py”, line 22, in getImagesAndLabels
Id=int(os.path.split(imagePath)[-1].split(“.”)[1])
ValueError: invalid literal for int() with base 10: ‘cam’
Can you help me ? Thanks
what are the image file name in your dataset folder?
I save it in dataSet folder : ex: home/Desktop/code/dataSet/User.cam.18.jpg
Your File Name is wrong… its suppose to be the user id in place of “cam” in the file name “User.cam.18.jpg”
http://imagizer.imageshack.us/a/img923/297/Bcxlt3.png
sorry to bother. I was stupid so the ID was a string
Sorry for late reply, yes, your ID should be a integer
How to solve the above problem ?
cv2 has no attribute createlbphfacerecognizer() how i slove this
use opencv2 it wont happen
The reason this no longer works is because the face recognition module has been moved out of the core OpenCV library from version 3. It now exists in a separate sub-library called ‘opencv_contrib’ which is less well supported and harder to get up and running. The joys of open source.
The Github page for the contributions module is here:
https://github.com/Itseez/o…
Theoretically if you can get that installed and built you should be able to access the face recognition module by changing ‘cv2.createLBPHFaceRecognizer’ to cv2.face.createLBPHFaceRecognizer’ but its possible the python bindings might not be up to date.
Getting this error how to resolve it please help
Traceback (most recent call last):
File “F:\New folder (6)\face reco\trainner.py”, line 21, in
Ids,faces=getImagesWithID(path)
File “F:\New folder (6)\face reco\trainner.py”, line 12, in getImagesWithID
faceImg=Image.open(imagePath).convert(‘L’);
File “C:\Python27\lib\site-packages\PIL\Image.py”, line 2349, in open
% (filename if filename else fp))
IOError: cannot identify image file ‘dataSet\\Thumbs.db’
hey gaurav sorry for not replying sooner,
try this split the image path in by “.” so the 2nd part will be jpeg after “.” if its not then its not an image
token=imagePath.split(“.”)
if(token[-1]==’jpg’):
# put the rest of the code inside
Hi there Anirban,
When I tried running the code you have given here, I get the error
Traceback (most recent call last):
File “”, line 1, in
exec file(“D:/Pjjjjjj/pythonsamp/trainner.py”)
File “D:/Pjjjjjj/pythonsamp/trainner.py”, line 33, in
recognizer.save(‘trainner/trainner.yml’)
error: ..\..\..\..\opencv\modules\contrib\src\facerec.cpp:390: error: (-2) File can’t be opened for writing! in function cv::FaceRecognizer::save
What should I do?
check that you have write permission in that folder
Yes, it does
I deleted the folder and created it again. Now it works.
Thank you.
Same error yml file is not saving. What I need to check
#Here is my code…..
import os
import cv2
import numpy as np
cv2.imread(“filepath”)
recognizer=cv2.createLBPHFaceRecognizer()
path=’dataSet’
def getImagesWithID(path):
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
faces=[]
IDs=[]
for imagePath in imagePaths:
faceNp=cv2.imread(imagepath,0)
ID=int(os.path.split(imagePath)[-1].split(“.”)[1])
faces.append(faceNp)
print ID
IDs.append(ID)
cv2.imshow(“training”,faceNp)
cv2.waitKey(10)
return IDs,faces
IDs,faces = getImagesWithID(path)
recognizer.train(faces, np.array(Ids))
recognizer.save(‘recognizer/trainningData.yml’)
cv2.destroyAllWindow()
#And this error occurs…..
Traceback (most recent call last):
File “E:/Project & thesis/Face Recognition/trainner.py”, line 23, in
IDs,faces = getImagesWithID(path)
File “E:/Project & thesis/Face Recognition/trainner.py”, line 14, in getImagesWithID
faceNp=cv2.imread(imagepath,0)
NameError: global name ‘imagepath’ is not defined
# What should I do? Please help.
you variable name is imagePath not imagepath
Thanks a lot. Now it works fine.
Now I am facing a problem in Sqlite Database.
Here is my code…..
import cv2
import sqlite3
cam = cv2.VideoCapture(0)
detector=cv2.CascadeClassifier(‘Classifiers/face.xml’)
def insertOrUpdate(Id,Name):
conn=sqlite3.connect(“FaceBase.db”)
cmd=”SELECT * FROM People WHERE ID=”+str(Id)
cursor=conn.execute(cmd)
isRecordExist=0
for row in cursor:
isRecordExist=1
if(isRecordExist==1):
cmd=”UPDATE People SET Name=”+str(Name)+” WHERE ID=”+str(Id)
else:
cmd=”INSERT INTO People(ID,Name) Values(“+str(Id)+”,”+str(Name)+”)”
conn.execute(cmd)
conn.commit()
conn.close()
id=raw_input(‘enter your id’)
name=raw_input(‘enter your name’)
insertOrUpdate(id,name)
sampleNum=0
while(True):
ret, img =cam.read()
gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces=detector.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5, minSize=(100, 100), flags=cv2.CASCADE_SCALE_IMAGE)
for (x,y,w,h) in faces:
sampleNum=sampleNum+1
cv2.imwrite(“dataSet/user.”+id +’.’+ str(sampleNum) + “.jpg”, gray[y:y+h,x:x+w])
cv2.rectangle(img,(x-50,y-50),(x+w+50,y+h+50),(225,0,0),2)
cv2.imshow(‘img’,img)
cv2.waitKey(100)
if sampleNum>20:
cam.release()
cv2.destroyAllWindows()
break
# My problem is this code runs well but doesn’t detect my face and doesn’t create the dataSet of my face. Now what should I do?
I m facing this problem in ur code can u plz help
TypeError: labels data type = 18 is not supported
CODE :
import cv2
import os
import numpy as np
from PIL import Image
recognizer = cv2.createLBPHFaceRecognizer()
detector = cv2.CascadeClassifier(“haarcascade_frontalface_default.xml”);
def getImagesAndLabels(path):
#get the path of all the files in the folder
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
#create empth face list
faceSamples=[]
#create empty ID list
Ids=[]
#now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
token = imagePath.split(“.”)
if(token[1] ==’jpeg’):
#loading the image and converting it to gray scale
pilImage=Image.open(imagePath).convert(‘L’)
#Now we are converting the PIL image into numpy array
imageNp=np.array(pilImage,’uint8′)
#getting the Id from the image
Id=int(os.path.split(imagePath)[-1].split(“.”)[1])
# extract the face from the training image sample
faces=detector.detectMultiScale(imageNp)
#If a face is there then append that in the list as well as Id of it
for (x,y,w,h) in faces:
faceSamples.append(imageNp[y:y+h,x:x+w])
Ids.append(Id)
cv2.imshow(“Adding faces to trainning set. . . “,imageNp[y:y+h,x:x+w])
cv2.waitKey(50)
return faceSamples,Ids
faces,Ids = getImagesAndLabels(‘dataSet’)
recognizer.train(faces, np.array(Ids))
recognizer.save(‘trainner/trainner.yml’)
ERROR :
Traceback (most recent call last):
File “C:\Users\User\Desktop\python opencv\Face Recog\trainner.py”, line 37, in
recognizer.train(faces, np.array(Ids))
error: ..\..\..\..\opencv\modules\contrib\src\facerec.cpp:917: error: (-210) Empty training data was given. You’ll need more than one sample to learn a model. in function cv::LBPH::train
Please fix the error….
most probably your dataset folder is empty
How to solve this error
recognizer=cv2.createLBPHFaceRecognizer()
AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’
To follow along with this tutorial you need opencv 2.4.. you must be using opencv3
Is there a way by which we can use the same code in OpenCV 3.2.0 ?
how to apply FaceRecognizer using openCV3?
you need to add the face module
How to add face module for opencv3.2
try this pip install opencv-contrib-python
How to Add face module?
Im using python 2.7
pip install opencv-contrib-python
I am getting this error:
Image.register_decoder(‘MSP’, MspDecoder)
AttributeError: ‘module’ object has no attribute ‘register_decoder’
I was able to fix the first problem by installing PIL; now I get this error:
the first image.
IOError: cannot identify image file ‘dataSet/.DS_Store’
open our terminal.. change your directory to the dataset folder and run this “rm .DS_Store”
I cant relate it with this post.. what are you trying to to here exactly?
Hi, first of all thank you a lot, this is helping me for my school proyect so much.
I have a problem with the Face module of opencv I can not find how to install it, I saw some videos and they use cmake and visual studio, but right now Im using Liclipse. Also I tried to install opencv 2.3 and 2.4 but none of them had the module. Could you help me please?
Traceback (most recent call last):
File “E:/face recgn/trainner/trainner.py”, line 3, in
from PIL import Image
ImportError: No module named PIL
hello
bro your tutorial wthas awesome . i have one question.is cv2.createLBPHFaceRecognizer() a built-in function. which method u used for recognition. i mean for features extraction. thanks
C:\Python27\Scripts>pip install Pillow
Collecting Pillow
Using cached Pillow-4.1.1-cp27-cp27m-win32.whl
Collecting olefile (from Pillow)
Using cached olefile-0.44.zip
Complete output from command python setup.py egg_info:
—————————————-
Command “python setup.py egg_info” failed with error code 1 in c:\users\logesh\appdata\local\temp\pip-build-onu8pb\olefile
I’m getting the following error when I run Trainer.py —
AttributeError: module ‘cv2’ has no attribute ‘createLBPHFaceRecognizer’
Please help me with how to resolve this error without changing the OpenCV version.
I’m using OpenCV-3.2.0 and Python 2.7 on a RaspberryPi 3
Hi,
When I run trainer.py , I get the following error —
OpenCV Error: Unspecified error (File can’t be opened for writing!) in save, file /home/pi/opencv_contrib-3.2.0/modules/face/src/facerec.cpp, line 70
Traceback (most recent call last):
File “trainer.py”, line 33, in
recognizer.save(‘trainer/trainer.yml’)
cv2.error: /home/pi/opencv_contrib-3.2.0/modules/face/src/facerec.cpp:70: error: (-2) File can’t be opened for writing! in function save
PS: I’m using Opencv-3.2.0 , Python – 2.7 and RaspberryPi – 3.
HI Anirban , You did fantastic job !! Congratulations. I have one question – I tried this out – even when unknown faces are presented to webcam it says the same name for which Id is defined and trained.. It does not say Unkown.. any clue – what I can modify to make it work ?
I mentioned in my post on how to identify unknown face, check that out
hola me puedes ayudar con este problema por favor:
OpenCV Error: Bad argument (The number of samples (src) must equal the number of labels (labels). Was len(samples)=20, len(labels)=0.) in cv::LBPH::train, file ..\..\..\..\opencv\modules\contrib\src\facerec.cpp, line 791
Traceback (most recent call last):
File “trainner.py”, line 30, in
recognizer.train(faces,Ids )
cv2.error: ..\..\..\..\opencv\modules\contrib\src\facerec.cpp:791: error: (-5) The number of samples (src) must equal the number of labels (labels). Was len(samples)=20, len(labels)=0. in function cv::LBPH::train
este es el codigo:
import cv2,os
import numpy as np
from PIL import Image
recognizer = cv2.createLBPHFaceRecognizer()
detector= cv2.CascadeClassifier(“haarcascade_frontalface_default.xml”);
path=’E:\Vision Artificial\dataSet’
def getImagesAndLabels(path):
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
facesSamples=[]
Ids=[]
for imagePath in imagePaths:
Image_pil=Image.open(imagePath).convert(‘L’)
faceNp=np.array(Image_pil, ‘uint8’)
Id=int(os.path.split(imagePath)[-1].split(“.”)[1])
facesSamples=detector.detectMultiScale(faceNp)
Ids.append(Id)
cv2.imshow(‘entrenamiento’, faceNp)
cv2.waitKey(10)
return np.array(Ids), facesSamples
faces, Ids = getImagesAndLabels(path)
print(Ids)
recognizer.train(faces,Ids )
recognizer.save(‘recognizer/trainningData.yml’)
cv2.destroyAllWindows()
gracias
In the “getImagesAndLabels” method
you are returning “return np.array(Ids), facesSamples”
but you switched the variables in this line
“faces, Ids = getImagesAndLabels(path)”
the order should be same
Ids, faces = getImagesAndLabels(path)
hello Anriban
in the training folder i have only pictures of one person, and i dont want to put any other pictures because i want the recognizer to return true or false when comparing with any other picture. i just want him to return True if the recognizer successfully recognize me other wise False.
how could i do this
Thx a lot
Aladdin
in the next tutorial I used a section where I put a condition “if(conf<50):" which is a threshold to determine how much confident the recognizer is about its prediction… thats your answer
Why is it that you have returned faceSamples from the function but are training with faces instead?
Also conf50(and other values) seem to be working but not accurately. Help please?
How to improve the accuracy as it showing confidence around 80-100 and not lowering even with diverse dataset. Can LPBH be used to distinguish between 10-20 different people?
I Never tested it with that many people.. and LPBH is not that much accurate.. its better than others in case of low data. but you will get much better performance with eigen face recognizer
Traceback (most recent call last):
File “H:/face detection/trainer.py”, line 29, in
recognizer.train(faces, Ids)
TypeError: src is not a numpy array, neither a scalar
please sir explain this error .
my code here :
import os
import cv2
import numpy as np
import PIL
from PIL import Image
recognizer = cv2.face.LBPHFaceRecognizer_create()
path = ‘dataSet’
def getImagesWithID(path):
imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
faces = []
IDs = []
for imagePath in imagePaths:
faceImg = Image.open(imagePath).convert(‘L’)
faceNp = np.array(faceImg, ‘uint8’)
Id=int(os.path.split(imagePath)[-1].split(".")[1]) faces.append(faceNp) IDs.append(Id) <code>cv2.imshow('trainer',faceNp) cv2.waitKey(10)
return np.array(IDs), faces
faces, Ids = getImagesWithID(path)
recognizer.train(faces, Ids)
recognizer.save(‘recg/trainData.yml’)
cv2.destroyAllWindows()
correction :
Ids, faces = getImagesWithID(path)
I have 2 images in my dataset, say image1 and image2. when I am training the recogniser, the 1st image with id=1 gets succesfully trained but for the 2nd image, when it is displayed on screen(due to cv2.imshow()), it is showing both the 1st image and 2nd image i.e both the images are displayed with a partition line in between, so the 1st image and 2nd image both gets id=2. how to solve this problem?
that is unusual have you checked the code, properly ?
I did the same as you. but the confidence is less than 50 . Please guide me please
the value of the confidence variable is in reverse.. 1 means fully confident.. the more the value the less the confident in the recognizer
Thank you for sharing everything, much appreciated and grateful! I do face some issues and I hope you can help!
import os
import cv2
import numpy as np
from PIL import Image
recognizer = cv2.createLBPHFaceRecognizer()
path= ‘dataSet’
def getImagesWithID(path):
#get the path of all the files in the folder
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
#create empth face list
faces=[]
#create empty ID list
IDs=[]
#now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
token = imagePath.split(“.”)
if(token[1]==’jpg’):
#loading the image and converting it to gray scale
faceImg=Image.open(imagePath).convert(‘L’);
#Now we are converting the PIL image into numpy array
faceNp=np.array(faceImg,’uint8′)
#getting the Id from the image
ID=int(os.path.split(imagePath)[-1].split(‘.’)[1])
# ??? extract the face from the training image sample
faces.append(faceNp)
print ID
IDs.append(ID)
cv2.imshow(“training”, faceNp)
cv2.waitKey(10)
return IDs, faces
Ids, faces = getImagesWithID(path)
recognizer.train(faces, np.array(Ids))
recognizer.save(‘recognizer/trainningData.yml’)
cv2.destroyAllWindows()
With the error:
recognizer.train(faces, np.array(Ids))
error: C:build2_4_winpack-bindings-win32-vc14-staticopencvmodulescontribsrcfacerec.cpp:917: error: (-210) Empty training data was given. You’ll need more than one sample to learn a model. in function cv::LBPH::train
I do have images with id “1” in my dataSet folder so I’m not sure what is the issue!
you will need more samples per id
Hey, thanks for the reply. I have about 40 samples per id so I’m not sure why it’s not working
https://uploads.disquscdn.com/images/c609563027d890bf2ec9a5118b05dc5d075fa4f5feb8cb9bf9a9c7054c7777f6.png
I have used the codes exactly the same as your videos. Could you send me the files you used in your videos please? [email protected] it will really help me alot thank you
please can you help me
How to solve this error:
Traceback (most recent call last):
File “<pyshell#1>”, line 1, in
recog = cv2.createLBPHFaceRecognizer()
AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’
I’m https://uploads.disquscdn.com/images/880343838e094161181b6790df3828fd0d46e9754ac9ce4395085727a985b375.png facing this problem. I followed everything as u mentioned. Will you please tell me what’s wrong with my code?
you missed a “)” at the previous line
Brother https://uploads.disquscdn.com/images/4cdda4015a38a7716ae5da609e784c096ab9a324fb6796d0e482e8231a7601a4.png there’s a new problem now. Will you please help me one more time . Thanks in Advance
it should be Ids, faces use “comma” instead of “dot”
Thanks a lot brother. Thanks a lot. It solved .
Brother faching this problem now. https://uploads.disquscdn.com/images/ffe475d2cca0f7823a8f08eb0f68c3d28b8358c03376dd6b68d019c393153208.png
typo-> “Images” it should be “Image”
So theres a new one. Oh God . Sorry brother https://uploads.disquscdn.com/images/f212956d3ce2ea9662f39951fbf6eb68f5743cc2e4a438a4375536df9a80cd3e.png
already told you its a typo-> “Images” it should be “Image”
Changed to (Image) but there’s 2 new of that https://uploads.disquscdn.com/images/08fddffe96b978b82750af4eac51eecada98ff574ce144ab72a7be5e60b9ea37.png
your training image file has name in wrong format
So how can I solve that. I’m totally new at this sector that’s why I have to face a lot of problem. Sorry to irritate you again and again.
Brother I checked it again and they all are same as your video tutorial .And image file that we created using Data set generator named at User.1.1.jpg format. Unable to find what’s wrong with it. Will you please check it .
https://uploads.disquscdn.com/images/f49172a86cc67f2d7cafed808a2a1687db59aa7dd799ca0ec1a9f5894a1a1983.png
type one of the file name of the images
I saved my image file like this one https://uploads.disquscdn.com/images/ce9f581518c123beacc40fe1b2efc55429e2dd82a0b731342028eb200c83efbd.png
made some updates in the code check that. at the end of the article
Brother :/ I don’t know what’s wrong with the code. I just open my laptop then hit run of that script. executed :/
I didn’t change anything :/ Not a single tab
nothing is wrong with the code its that your dataset folder contained some temp files or hidden files other that jpg. and the script was trying to get the id from that file name. but its not able to convert it to numbers thats why it was giving errors
I got it . Thnaks a lot . I have another problem at detection. I made a comment though. Do you have time to check it brother?
Bro any help with the last one?
Traceback (most recent call last):
File “trainner.py”, line 24, in
recognizer.train(faces, np.array(Ids))
TypeError: labels data type = 17 is not supported
help ?
Hi Anirban,
I am getting this error when i try running detector.py:
C:Python27python.exe C:/Users/Admin/PycharmProjects/FullFaceID/detector.py
OpenCV Error: Unspecified error (File can’t be opened for writing!) in cv::FaceRecognizer::load, file C:build2_4_winpack-bindings-win32-vc14-staticopencvmodulescontribsrcfacerec.cpp, line 398
Traceback (most recent call last):
File “C:/Users/Admin/PycharmProjects/FullFaceID/detector.py”, line 8, in
recognizer.load(‘trainer/trainer.yml’)
cv2.error: C:build2_4_winpack-bindings-win32-vc14-staticopencvmodulescontribsrcfacerec.cpp:398: error: (-2) File can’t be opened for writing! in function cv::FaceRecognizer::load
Process finished with exit code 1
Any reason why?
Thanks in advance!
AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’
plz tell me how to fix this error
recognizer = cv2.face.LBPHFaceRecognizer_create()
i have done this code also, again show the same error plz tell me sir how to fix. any thing else require in the program tell me plzzz sir
AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’
plz tell me how to fix this error
https://uploads.disquscdn.com/images/1599e1c2773dd08944681066a34e0861aa5e1055ce101b03bd79de28be762f08.png
recognizer = cv2.face.LBPHFaceRecognizer_create()
what should I do if I have below error-
error: C:build2_4_winpack-bindings-win32-vc14-staticopencvmodulescontribsrcfacerec.cpp:390: error: (-2) File can’t be opened for writing! in function cv::FaceRecognizer::save
should I need to download face contrib??
I am 70 years old retired Telecom Engineer and my hobby is AI and Image processing. I am fascinated by your projects. I tried your Dataset Creator it works fine. But when I try your Trainer I get this error message, Please help.
Hello Sir,
I am guessing there is a hidden file named “Thumbs.db” that is auto generated by the operating system in the dataset folder. and the program is trying to load that as a sample image. Can you please check if you have the following line inside the for loop at the beginning. if its not there then please add it
if(os.path.split(imagePath)[-1].split(“.”)[-1]!=’jpg’):
continue
Dear Mr. Anirban Kar, Thank you for your immediate reply. I tried the option you suggested but still the error exists. I give below your code I am trying, please correct me where I am wrong.
Your Code:
import os
import cv2
import numpy as np
from PIL import Image
recognizer=cv2.createLBPHFaceRecognizer();
path=’dataSet’
def getImagesWithID(path):
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
faces=[]
IDs=[]
for imagePath in imagePaths:
if(os.path.split(imagePath)[-1].split(“.”)[-1]!=’jpg’):
faceImg=Image.open(imagePath).convert(‘L’);
faceNp=np.array(faceImg, ‘uint8’)
ID=int(os.path.split(imagePath) [-1] .split(‘.’)[1])
faces.append(faceNp)
print ID
IDs.append(ID)
cv2.imshow(“training”,faceNp)
cv2.waitKey(10)
return IDs, faces
Ids,faces=getImagesWithID(path)
recognizer.train(faces,np.array(Ids))
recognizer.save(‘recognizer/trainner.yml’)
cv2.destroyAllWindows()
You missed the “continoue” command after th if LINE .Please check the “Updates” section at the bottom of the article.
Thanks again for your concern and help. Now I am getting this error message, kindly help me. With Great Regards.
Traceback (most recent call last):
File “C:UsersMainUserDesktopABC_Facetrainer_02A.py”, line 27, in
recognizer.train(faces,np.array(Ids))
error: C:build2_4_winpack-bindings-win32-vc14-staticopencvmodulescontribsrcfacerec.cpp:917: error: (-210) Empty training data was given. You’ll need more than one sample to learn a model. in function cv::LBPH::train
Hello Anirban. I’ve tried to follow your tutorial here, but I got this error message
Traceback (most recent call last):
File “/home/pi/pythonpy/videofacedet/craft/codacus/trainer.py”, line 32, in
faces,Ids = getImagesAndLabels(‘trainingImage’)
File “/home/pi/pythonpy/videofacedet/craft/codacus/trainer.py”, line 24, in getImagesAndLabels
faces=detector.detectMultiScale(imageNp)
error: /home/pi/opencv-3.1.0/modules/objdetect/src/cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale
I did not use the dataset creator like you did, but I create my data set manually by taking some pictures with a camera, then put them in my dataset folder. Then I put them together in a folder. Can you help me to fix this problem please?
Hi Anirban .I’m using python 3.5 .After creating the dataset and trying to open the image in the dataset folder it gives me the message as :The file’s encoding is invalid for python 3.x.How can i solve this issue because while training the recogniser it gives the message as dataset is empty.
First thank you for the tutorial, i followed the python 3.5 version you provided from github, and exept some errors in the code that i managed to solve quickly i can’t really figure out why the face_recognition.py, which bt the way runs, gives me always the same result whether a face is the mine or not the result always give me id1 if you can tell me how to solve this problem i would be grateful
Thank you in advance
Sir Anirban, regarding with the trainer.yml file. Can I get any unique output in recognizer.predict() if there is no registered face in that file? Because I created an array of id (id=recognizer.predict()) and it gives random id if it detects unregistered face in the yml. I hope you’ll reply back. Thanks for making this tutorial!
please help me to get out of this error
please help me to get out of this error. https://uploads.disquscdn.com/images/96972451a22c21dc996d538bbadda50da5ba11f02ba5b21489d7bea08c5bc89c.png
Same problem here , need help
after running this on cmd: pip install opencv-contrib-python
and using this: recognizer = cv2.face.LBPHFaceRecognizer_create()
it worked for me
i did..it doesn’t show anything .please help me to overcome this
yeah it worked for me too.
recognizer = cv2.face.LBPHFaceRecognizer_create() .
problem still exists
https://uploads.disquscdn.com/images/316e06bb6d8b1dfb323af40115cdb010aa849b7da23a69f27c49bd21f38d597d.png
it didn’t work
https://uploads.disquscdn.com/images/63e1b2790b2634eb71560c3110d7017548fd7aab82046e005285baba51bae73e.png
syntax has changed slightly you’ll have to use:
recognizer1 = cv2.face.createEigenFaceRecognizer() ## opencv3.1
or:
recognizer1 = cv2.face.EigenFaceRecognizer_create() ## opencv3.3
good luck !
This is for Python3. But the user here is on Python2.
hello every one those who are facing issue with recognizer = cv2.createLBPHFaceRecognizer() , i have solution for it you need to install 2 library.
pip install face
pip install opencv-contrib-python
then it depend on your version which open cv you are using if it is 3 or above use this code.
recognizer1 = cv2.face.LBPHFaceRecognizer_create()
thankyou.
how to create dataset folder and script pleass help me
Traceback (most recent call last):
File “D:FACE_RECOGNITIONtrainer.py”, line 39, in
recognizer.train(faces, np.array(Ids))
TypeError: labels data type = 18 is not supported
please help with this only one error is there everything int he code is fine
same problem is with me
Traceback (most recent call last):
File “F:FACE RECOGNITION SYSTEMface recognitiontrainer.py”, line 27, in
recognizer.train(faces,IDs)
TypeError: labels data type = 18 is not supported
how to remove this error
unable to save trainningData.yml int he folder recognizer – recognizer.save(‘recognizer/trainningData.yml’)
Does it work if you remove the folder name, and just instead save it in the current folder ?
PLEASE HELP
i got error running the code .
error: ‘builtin_function_or_method’ object has no attribute ‘getitem‘
https://uploads.disquscdn.com/images/082bfb6a5cbb28161087a1dd59889a21b3d6cec7f4fa0dcee39642e0b26c4d0a.png
Hi, I have a problem that does not let me cv2.face.LBPHFaceRecognizer_create () and I try to do it in several ways but it does not let me, which with cv2.LineSegmentDetector () if it goes to the video part 6:33, but at the end of the video mark an error
Traceback (most recent call last):
File “C: /Users/CharyMricroCode/PycharmProjects/opencv/Recognition/trainner.py”, line 25, in
Ids, faces = getImagesWithID (path)
File “C: /Users/CharyMricroCode/PycharmProjects/opencv/Recognition/trainner.py”, line 17, in getImagesWithID
faceNp = np.array (faceImg, ‘unit8’)
TypeError: data type “unit8” not understood
if I add in the part 17faceNp = np.array_equal (faceImg, ‘unit8’)
just marks an error in train
recognizer.train (faces, np.array (Ids))
AttributeError: ‘cv2.LineSegmentDetector’ object has no attribute ‘train’
could you help me please, to continue with the course
I do not speak English very well.
Hi, I have a problem that does not let me cv2.face.LBPHFaceRecognizer_create () and I try to do it in several ways but it does not let me, which with cv2.LineSegmentDetector () if it goes to the video part 6:33, but at the end of the video mark an error
Traceback (most recent call last):
File “C: /Users/CharyMricroCode/PycharmProjects/opencv/Recognition/trainner.py”, line 25, in
Ids, faces = getImagesWithID (path)
File “C: /Users/CharyMricroCode/PycharmProjects/opencv/Recognition/trainner.py”, line 17, in getImagesWithID
faceNp = np.array (faceImg, ‘unit8’)
TypeError: data type “unit8” not understood
if I add in the line 17faceNp = np.array_equal (faceImg, ‘unit8’)
just marks an error in train
recognizer.train (faces, np.array (Ids))
AttributeError: ‘cv2.LineSegmentDetector’ object has no attribute ‘train’
could you help me please, to continue with the course
I do not speak English very well.
all this in python 3.6
https://uploads.disquscdn.com/images/7bbcccefec527e23b3cb4f2081e827048c4aab7f1b1a20977689f4567fa683c9.png