• Home
  • Computer Vision
  • Neural Network
  • Forums
  • About
  • Contact
  • Privacy Policy
  • Disclaimer

The Codacus

The Coding Abacus

  • Home
  • About
  • Contact
  • Privacy Policy
  • Disclaimer
You are here: Home / Computer Vision / Face Recognition OpenCV – Training A Face Recognizer

Face Recognition OpenCV – Training A Face Recognizer

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

Comments

  1. Alberto says

    February 11, 2017 at 8:55 pm

    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.

    Reply
    • Anirban says

      February 13, 2017 at 3:46 pm

      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/

      Reply
    • Anish jain says

      May 17, 2017 at 6:57 pm

      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.

      Reply
  2. Jose Morales says

    February 14, 2017 at 5:48 am

    When the next? Thanks for the tuto

    Reply
    • Anirban says

      February 17, 2017 at 1:39 am

      it will be updated soon, you can subscribe to this blog, you will get notified when ever there is a new post

      Reply
  3. Mehdi says

    February 21, 2017 at 1:35 am

    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.

    Reply
    • Anirban says

      February 21, 2017 at 1:42 am

      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

      Reply
  4. patel says

    February 21, 2017 at 5:28 pm

    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.

    Reply
    • Anirban says

      February 22, 2017 at 1:07 am

      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

      Reply
      • gaurav says

        March 1, 2017 at 5:46 pm

        where does that hidden file reside?

        Reply
        • Anirban says

          March 29, 2017 at 1:21 pm

          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

          Reply
          • Xiao says

            March 31, 2017 at 1:21 am

            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

          • Anirban says

            April 1, 2017 at 2:21 pm

            I will modify the code in the blog itself so that every one can see this

  5. shyamsundar PL says

    February 23, 2017 at 5:36 pm

    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 ,,,,

    Reply
    • Anirban says

      February 23, 2017 at 6:19 pm

      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

      Reply
  6. shyamsundar PL says

    February 24, 2017 at 12:12 pm

    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

    Reply
    • Anirban says

      February 27, 2017 at 5:20 pm

      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

      Reply
  7. gaurav says

    March 1, 2017 at 6:02 pm

    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’

    Reply
    • Arshad Ali says

      April 11, 2017 at 7:41 pm

      I’m having the same error.. somebody please fix this !

      Reply
    • Arshad Ali says

      April 12, 2017 at 11:28 am

      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

      Reply
      • Jane Chow says

        October 6, 2017 at 2:09 am

        did you manage to fix this issue?

        Reply
    • lucky says

      June 15, 2017 at 4:38 pm

      same error

      Reply
      • Anirban says

        June 15, 2017 at 10:12 pm

        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..

        Reply
  8. Rithesh says

    March 3, 2017 at 8:34 pm

    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.

    Reply
    • Anirban says

      March 3, 2017 at 9:10 pm

      So it’s working then… maybe you mistype something previously

      Reply
  9. Mike says

    March 3, 2017 at 11:58 pm

    Hello,
    How could I apply the same detection and recognition techniques but with a browse button instead of capturing it through the cam?

    Reply
    • Anirban says

      March 5, 2017 at 2:18 pm

      use cv2.VideoCapture(‘videofilepath’) instead of cv2.VideoCapture(0)… works well for avi

      Reply
  10. Taru says

    March 6, 2017 at 3:59 pm

    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

    Reply
    • Anirban says

      March 7, 2017 at 8:15 pm

      change the variable name “id” if you are using it anywhere.. it causes issue in some cases

      Reply
  11. kundan kumar says

    March 11, 2017 at 1:12 am

    i am facing ….”””AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer “”‘
    error …. what should i do….

    Reply
    • Anirban says

      March 17, 2017 at 1:52 pm

      this tutorials are based on opencv 2.. so opencv3 wont work with these.. try with opencv 2

      Reply
    • Apurva Agrawal says

      May 5, 2017 at 12:34 pm

      use cv2.face.createEigenFaceRecognizer()

      Reply
    • Anish jain says

      May 17, 2017 at 6:59 pm

      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.

      Reply
  12. Musab says

    March 19, 2017 at 1:10 pm

    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’

    Reply
    • Anirban says

      March 20, 2017 at 2:31 pm

      did you check your opencv version ?? is it 2/3? cuz in opencv 3 you dont have “createLBPHFaceRecognizer” out of the box

      Reply
      • younid says

        March 24, 2017 at 8:26 pm

        So, if we are download open cv3. how can we solve this issue with this version.

        Reply
        • Anirban says

          March 24, 2017 at 10:47 pm

          you have to compile the contrib library and face module. then you can use “cv2.face.createLBPHFaceRecognizer()”

          Reply
          • joseph says

            May 6, 2017 at 9:45 pm

            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

          • Anish jain says

            May 17, 2017 at 6:32 pm

            And how to do it ?

      • Jhanvi Shah says

        May 26, 2017 at 1:31 pm

        hello. I’m having this error.
        AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’

        Reply
        • Anirban says

          June 8, 2017 at 3:55 am

          you must be using opencv3

          Reply
    • Anish jain says

      May 17, 2017 at 6:56 pm

      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.

      Reply
  13. Divide says

    March 22, 2017 at 9:11 pm

    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

    Reply
    • Anirban says

      March 23, 2017 at 7:54 pm

      what are the image file name in your dataset folder?

      Reply
      • Divide says

        March 24, 2017 at 7:03 am

        I save it in dataSet folder : ex: home/Desktop/code/dataSet/User.cam.18.jpg

        Reply
        • Anirban Kar says

          June 16, 2017 at 2:03 pm

          Your File Name is wrong… its suppose to be the user id in place of “cam” in the file name “User.cam.18.jpg”

          Reply
      • Divide says

        March 24, 2017 at 7:54 am

        http://imagizer.imageshack.us/a/img923/297/Bcxlt3.png

        Reply
      • Divide says

        March 24, 2017 at 8:55 am

        sorry to bother. I was stupid so the ID was a string

        Reply
        • Anirban says

          March 24, 2017 at 1:11 pm

          Sorry for late reply, yes, your ID should be a integer

          Reply
          • Jyoti says

            April 28, 2017 at 1:09 am

            How to solve the above problem ?

  14. pradeep says

    March 24, 2017 at 5:42 pm

    cv2 has no attribute createlbphfacerecognizer() how i slove this

    Reply
    • Anirban says

      March 24, 2017 at 10:48 pm

      use opencv2 it wont happen

      Reply
    • Anish jain says

      May 17, 2017 at 6:56 pm

      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.

      Reply
  15. gaurav says

    March 29, 2017 at 3:24 pm

    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’

    Reply
    • Anirban says

      March 29, 2017 at 9:01 pm

      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

      Reply
  16. Shyam Saravanan says

    March 31, 2017 at 10:59 pm

    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?

    Reply
    • Anirban says

      April 1, 2017 at 2:20 pm

      check that you have write permission in that folder

      Reply
      • Shyam Saravanan says

        April 1, 2017 at 6:07 pm

        Yes, it does

        Reply
        • Shyam Saravanan says

          April 1, 2017 at 6:32 pm

          I deleted the folder and created it again. Now it works.
          Thank you.

          Reply
      • Vasantha Vasu says

        June 25, 2017 at 5:23 pm

        Same error yml file is not saving. What I need to check

        Reply
  17. Arif says

    April 6, 2017 at 2:51 pm

    #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.

    Reply
    • Anirban says

      April 6, 2017 at 8:35 pm

      you variable name is imagePath not imagepath

      Reply
      • Arif says

        April 8, 2017 at 9:51 pm

        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?

        Reply
        • AMAL SAAD says

          May 19, 2017 at 3:26 pm

          I m facing this problem in ur code can u plz help

          TypeError: labels data type = 18 is not supported

          Reply
  18. Arshad Ali says

    April 12, 2017 at 7:08 pm

    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….

    Reply
    • Anirban says

      April 13, 2017 at 3:15 pm

      most probably your dataset folder is empty

      Reply
  19. Juliet says

    April 18, 2017 at 11:10 pm

    How to solve this error
    recognizer=cv2.createLBPHFaceRecognizer()
    AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’

    Reply
    • Anirban says

      April 25, 2017 at 8:53 pm

      To follow along with this tutorial you need opencv 2.4.. you must be using opencv3

      Reply
      • Anish jain says

        May 17, 2017 at 6:31 pm

        Is there a way by which we can use the same code in OpenCV 3.2.0 ?

        Reply
      • Jhanvi Shah says

        May 26, 2017 at 1:56 pm

        how to apply FaceRecognizer using openCV3?

        Reply
        • Anirban says

          June 8, 2017 at 3:53 am

          you need to add the face module

          Reply
          • Vasantha Vasu says

            June 25, 2017 at 2:55 pm

            How to add face module for opencv3.2

          • Anirban Kar says

            June 28, 2017 at 4:41 pm

            try this pip install opencv-contrib-python

          • Ahmed Imam says

            June 26, 2017 at 8:33 pm

            How to Add face module?
            Im using python 2.7

          • Anirban Kar says

            June 28, 2017 at 4:41 pm

            pip install opencv-contrib-python

  20. Damilola says

    April 24, 2017 at 6:35 pm

    I am getting this error:
    Image.register_decoder(‘MSP’, MspDecoder)

    AttributeError: ‘module’ object has no attribute ‘register_decoder’

    Reply
    • Damilola says

      April 24, 2017 at 7:10 pm

      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’

      Reply
      • Anirban says

        April 25, 2017 at 8:46 pm

        open our terminal.. change your directory to the dataset folder and run this “rm .DS_Store”

        Reply
    • Anirban says

      April 25, 2017 at 9:02 pm

      I cant relate it with this post.. what are you trying to to here exactly?

      Reply
  21. Rodrigo says

    April 27, 2017 at 12:57 am

    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?

    Reply
  22. zuhair says

    April 27, 2017 at 9:07 pm

    Traceback (most recent call last):
    File “E:/face recgn/trainner/trainner.py”, line 3, in
    from PIL import Image
    ImportError: No module named PIL

    Reply
  23. muhammad zaheer says

    April 29, 2017 at 6:47 pm

    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

    Reply
  24. Logesh says

    May 15, 2017 at 4:15 pm

    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

    Reply
  25. Anish jain says

    May 17, 2017 at 6:36 pm

    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

    Reply
  26. Anish jain says

    May 17, 2017 at 7:25 pm

    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.

    Reply
  27. chan says

    June 9, 2017 at 1:51 am

    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 ?

    Reply
    • Anirban Kar says

      June 9, 2017 at 1:59 am

      I mentioned in my post on how to identify unknown face, check that out

      Reply
  28. wander mi says

    June 12, 2017 at 1:24 am

    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

    Reply
    • Anirban says

      June 12, 2017 at 2:16 am

      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)

      Reply
  29. Aladdin Hammodi says

    June 17, 2017 at 3:50 am

    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

    Reply
    • Anirban Kar says

      June 18, 2017 at 12:24 am

      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

      Reply
  30. Parth Joshi says

    June 29, 2017 at 12:49 pm

    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?

    Reply
  31. Parth Joshi says

    June 29, 2017 at 3:48 pm

    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?

    Reply
    • Anirban Kar says

      August 22, 2017 at 1:26 am

      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

      Reply
  32. Ramjilal Choudhary says

    August 21, 2017 at 11:58 pm

    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()

    Reply
    • Anirban Kar says

      August 22, 2017 at 1:20 am

      correction :
      Ids, faces = getImagesWithID(path)

      Reply
  33. Sayantan Gupta says

    August 26, 2017 at 4:17 pm

    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?

    Reply
    • Anirban Kar says

      August 29, 2017 at 9:05 am

      that is unusual have you checked the code, properly ?

      Reply
  34. Khem Puthea says

    September 1, 2017 at 9:25 pm

    I did the same as you. but the confidence is less than 50 . Please guide me please

    Reply
    • Anirban Kar says

      September 1, 2017 at 9:56 pm

      the value of the confidence variable is in reverse.. 1 means fully confident.. the more the value the less the confident in the recognizer

      Reply
  35. Jane Chow says

    October 6, 2017 at 2:50 am

    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!

    Reply
    • Anirban Kar says

      October 28, 2017 at 6:31 pm

      you will need more samples per id

      Reply
      • Jane Chow says

        October 29, 2017 at 12:56 am

        Hey, thanks for the reply. I have about 40 samples per id so I’m not sure why it’s not working

        Reply
      • Jane Chow says

        October 29, 2017 at 1:01 am

        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

        Reply
  36. H.J.A-K Hassoun says

    October 19, 2017 at 9:06 pm

    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’

    Reply
  37. Kawsur Abeddin Noori says

    October 27, 2017 at 12:47 pm

    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?

    Reply
    • Anirban Kar says

      October 28, 2017 at 6:30 pm

      you missed a “)” at the previous line

      Reply
      • Kawsur Abeddin Noori says

        October 28, 2017 at 6:45 pm

        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

        Reply
        • Anirban Kar says

          October 28, 2017 at 6:48 pm

          it should be Ids, faces use “comma” instead of “dot”

          Reply
          • Kawsur Abeddin Noori says

            October 28, 2017 at 6:50 pm

            Thanks a lot brother. Thanks a lot. It solved .

          • Kawsur Abeddin Noori says

            October 28, 2017 at 9:26 pm

            Brother faching this problem now. https://uploads.disquscdn.com/images/ffe475d2cca0f7823a8f08eb0f68c3d28b8358c03376dd6b68d019c393153208.png

          • Anirban Kar says

            October 28, 2017 at 9:29 pm

            typo-> “Images” it should be “Image”

          • Kawsur Abeddin Noori says

            October 28, 2017 at 9:36 pm

            So theres a new one. Oh God . Sorry brother https://uploads.disquscdn.com/images/f212956d3ce2ea9662f39951fbf6eb68f5743cc2e4a438a4375536df9a80cd3e.png

          • Anirban Kar says

            October 28, 2017 at 10:17 pm

            already told you its a typo-> “Images” it should be “Image”

          • Kawsur Abeddin Noori says

            October 28, 2017 at 10:25 pm

            Changed to (Image) but there’s 2 new of that https://uploads.disquscdn.com/images/08fddffe96b978b82750af4eac51eecada98ff574ce144ab72a7be5e60b9ea37.png

          • Anirban Kar says

            October 28, 2017 at 10:38 pm

            your training image file has name in wrong format

          • Kawsur Abeddin Noori says

            October 28, 2017 at 10:44 pm

            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.

          • Kawsur Abeddin Noori says

            October 29, 2017 at 9:29 am

            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

          • Anirban Kar says

            October 29, 2017 at 4:29 pm

            type one of the file name of the images

          • Kawsur Abeddin Noori says

            October 29, 2017 at 4:33 pm

            I saved my image file like this one https://uploads.disquscdn.com/images/ce9f581518c123beacc40fe1b2efc55429e2dd82a0b731342028eb200c83efbd.png

          • Anirban Kar says

            October 29, 2017 at 4:44 pm

            made some updates in the code check that. at the end of the article

          • Kawsur Abeddin Noori says

            October 29, 2017 at 4:46 pm

            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

          • Anirban Kar says

            October 29, 2017 at 4:49 pm

            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

          • Kawsur Abeddin Noori says

            October 29, 2017 at 4:57 pm

            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?

          • Kawsur Abeddin Noori says

            October 28, 2017 at 10:03 pm

            Bro any help with the last one?

  38. Patrik Polčan says

    November 1, 2017 at 4:52 pm

    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 ?

    Reply
  39. Frankie says

    November 27, 2017 at 9:10 am

    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!

    Reply
  40. Vivek Kumar says

    November 27, 2017 at 3:59 pm

    AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’

    plz tell me how to fix this error

    Reply
    • Chase Lawson says

      November 30, 2017 at 1:53 am

      recognizer = cv2.face.LBPHFaceRecognizer_create()

      Reply
      • Vivek Kumar says

        November 30, 2017 at 6:02 am

        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

        Reply
  41. Vivek Kumar says

    November 27, 2017 at 4:02 pm

    AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’

    plz tell me how to fix this error

    https://uploads.disquscdn.com/images/1599e1c2773dd08944681066a34e0861aa5e1055ce101b03bd79de28be762f08.png

    Reply
    • unknown unknown says

      February 11, 2018 at 12:55 am

      recognizer = cv2.face.LBPHFaceRecognizer_create()

      Reply
  42. Ramu Kunwar says

    November 29, 2017 at 8:02 am

    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??

    Reply
  43. Ragnar says

    December 9, 2017 at 11:24 pm

    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.

    Reply
    • Anirban Kar says

      December 9, 2017 at 11:49 pm

      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

      Reply
      • Ragnar says

        December 10, 2017 at 8:25 am

        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()

        Reply
        • Anirban Kar says

          December 10, 2017 at 2:03 pm

          You missed the “continoue” command after th if LINE .Please check the “Updates” section at the bottom of the article.

          Reply
          • Ragnar says

            December 11, 2017 at 8:12 am

            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

            >

  44. ian maynard bramasto says

    December 10, 2017 at 7:42 pm

    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?

    Reply
  45. Adi Madan says

    January 5, 2018 at 8:03 pm

    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.

    Reply
  46. Alessandro Brunello says

    January 8, 2018 at 1:21 am

    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

    Reply
  47. Lucian Kudo says

    January 12, 2018 at 7:23 am

    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!

    Reply
  48. dilip bhattarai says

    January 31, 2018 at 1:02 pm

    please help me to get out of this error

    Reply
  49. dilip bhattarai says

    January 31, 2018 at 1:03 pm

    please help me to get out of this error. https://uploads.disquscdn.com/images/96972451a22c21dc996d538bbadda50da5ba11f02ba5b21489d7bea08c5bc89c.png

    Reply
    • Adil Hossain says

      February 8, 2018 at 7:10 pm

      Same problem here , need help

      Reply
      • Taha Anwar says

        February 12, 2018 at 8:47 pm

        after running this on cmd: pip install opencv-contrib-python
        and using this: recognizer = cv2.face.LBPHFaceRecognizer_create()
        it worked for me

        Reply
        • nagamani manivannan says

          February 16, 2018 at 10:14 am

          i did..it doesn’t show anything .please help me to overcome this

          Reply
        • dilip bhattarai says

          April 26, 2018 at 4:13 pm

          yeah it worked for me too.

          Reply
    • unknown unknown says

      February 11, 2018 at 12:55 am

      recognizer = cv2.face.LBPHFaceRecognizer_create() .

      Reply
      • dilip bhattarai says

        February 12, 2018 at 7:00 pm

        problem still exists
        https://uploads.disquscdn.com/images/316e06bb6d8b1dfb323af40115cdb010aa849b7da23a69f27c49bd21f38d597d.png

        Reply
      • dilip bhattarai says

        February 12, 2018 at 7:13 pm

        it didn’t work
        https://uploads.disquscdn.com/images/63e1b2790b2634eb71560c3110d7017548fd7aab82046e005285baba51bae73e.png

        Reply
        • H moudi says

          February 23, 2018 at 1:19 pm

          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 !

          Reply
      • Shashi Kiran says

        April 20, 2018 at 2:19 pm

        This is for Python3. But the user here is on Python2.

        Reply
  50. gvsagar says

    March 6, 2018 at 9:03 pm

    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.

    Reply
  51. thuwaragan says

    March 21, 2018 at 6:36 pm

    how to create dataset folder and script pleass help me

    Reply
  52. chirag says

    March 21, 2018 at 8:24 pm

    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

    Reply
    • Somendra Shukla says

      April 14, 2018 at 7:03 pm

      same problem is with me

      Reply
  53. Somendra Shukla says

    April 13, 2018 at 1:37 am

    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

    Reply
  54. ILA MISHRA says

    April 20, 2018 at 9:50 am

    unable to save trainningData.yml int he folder recognizer – recognizer.save(‘recognizer/trainningData.yml’)

    Reply
    • Shashi Kiran says

      April 20, 2018 at 2:39 pm

      Does it work if you remove the folder name, and just instead save it in the current folder ?

      Reply
  55. dilip bhattarai says

    April 29, 2018 at 6:10 pm

    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

    Reply
  56. charly says

    May 29, 2018 at 10:21 pm

    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.

    Reply
  57. charly says

    May 29, 2018 at 10:29 pm

    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

    Reply

Trackbacks

  1. Python-OpenCV训练一个人脸识别器 - 煎鱼不可能有BUG! says:
    May 17, 2018 at 1:24 pm

    […] 原文,若有错误之处请指出,更多地关注煎鱼。 […]

    Reply
  2. Python-OpenCV训练一个人脸识别器 - 奇奇问答 says:
    June 12, 2018 at 4:55 pm

    […] 原文,若有错误之处请指出,更多地关注煎鱼。 […]

    Reply
  3. Python-OpenCV训练一个人脸识别器 - 造壳 says:
    November 6, 2018 at 9:56 pm

    […] 原文,若有错误之处请指出,更多地关注煎鱼。 […]

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Lets Build An Image Classifier Using Tensorflow
  • Prepare Real life Data Set To Train Your Tensorflow Model
  • TensorBoard Tutorial, Visualize Your Networks Graphically
  • TensorFlow Tutorial Ground Zero | How To Start
  • Gesture Recognition Virtual Mouse Using OpenCV

Categories

  • Computer Vision
    • Face Recognition
    • Object Recognition
  • Machine Learning
    • Neural Network

Archives

  • September 2017
  • August 2017
  • July 2017
  • June 2017
  • March 2017
  • February 2017
  • January 2017

Recent Comments

  • Python-OpenCV人脸识别之数据集生成 - 造壳 on Face Recognition – OpenCV Python | Dataset Generator
  • Python-OpenCV训练一个人脸识别器 - 造壳 on Face Recognition OpenCV – Training A Face Recognizer
  • Deep Learning Tutorial in Python #3 – Tensorflow Operations Part 1 | Quantum Code on TensorFlow Tutorial Ground Zero | How To Start
  • Python-OpenCV训练一个人脸识别器 - 奇奇问答 on Face Recognition OpenCV – Training A Face Recognizer
  • Vangipuram Sainath on Build Neural Network From Scratch in Python (no libraries)

Copyright © 2021 · Magazine Pro Theme on Genesis Framework · WordPress · Log in