• 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 Using OpenCV | Loading Recognizer

Face Recognition Using OpenCV | Loading Recognizer

In my previous post we learnt to train a recognizer using a dataset, in this post we are loading recognizer to see how we can use that recognizer to recognize faces.

If you are following my previous posts then you already have the trained recognizer with you inside a folder named “trainner” and “trainner.yml” file inside it. Now we are going to use that training data to recognize some faces we previously trained .

Lets Start By Importing The Libraries

import cv2
import numpy as np

Yes that’s it, thats all we need for this projects.

Now Loading Recognizer

next we create a recognizer object using opencv library and load the training data (before that just sve your script in the same location where your “trainner” folder is located)

recognizer = cv2.createLBPHFaceRecognizer()
recognizer.load('trainner/trainner.yml')

Now we will create a cascade classifier using haar cascade for face detection, assuming u have the cascade file in the same location,

cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);

Now we will create the video capture object

cam = cv2.VideoCapture(0)

Next we need a “font” that’s because we are going to write the name of that person in the image so we need a font for the text

font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) 

Okay so the first parameter is the font name, 2nd and 3rd is the horizontal and the vertical scale,4rth is shear (like italic), 5th is thickness of line, 6th is line type

So we have all setup

Lets Start the main Loop

Lets start the main loop and do the following basic steps

  • Starts capturing frames from the camera object
  • Convert it to Gray Scale
  • Detect and extract faces from the images
  • Use the recognizer to recognize the Id of the user
  • Put predicted Id/Name and Rectangle on detected face
while True:
    ret, im =cam.read()
    gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    faces=faceCascade.detectMultiScale(gray,1.2,5)
    for(x,y,w,h) in faces:
        cv2.rectangle(im,(x-50,y-50),(x+w+50,y+h+50),(225,0,0),2)
        Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
        cv2.cv.PutText(cv2.cv.fromarray(im),str(Id), (x,y+h),font, 255)
    cv2.imshow('im',im)
    if cv2.waitKey(10) & 0xFF==ord('q'):
        break

So its pretty similar to the face detection code the only difference is the following lines

        Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
        cv2.cv.PutText(cv2.cv.fromarray(im),str(Id), (x,y+h),font, 255)

in the above two line the recognizer is predicting the user Id and confidence of the prediction respectively
in the next line we are writing the User ID in the screen below the face, which is (x, y+h) coordinate

 

[ictt-tweet-inline hashtags=”#opencv,#python,#facerecognition” via=”via thecodacus”]Just Little Finishing Touch (For Unknown Faces)[/ictt-tweet-inline]

 

Now with this we are pretty much done we can add some more finishing touch like its showing user Id instead of the name,
and it cant handle unknown faces,

So to add this additional features we can do the following,

        Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
        if(conf<50):
            if(Id==1):
                Id="Anirban"
            elif(Id==2):
                Id="Obama"
        else:
            Id="Unknown"
        cv2.cv.PutText(cv2.cv.fromarray(im),str(Id), (x,y+h),font, 255)

 

Now Some Cleanup

cam.release()
cv2.destroyAllWindows()

Now that everything is done, we need to close the camera and the windows. and we are done!!!!

And this is the results

Loading recognizer which is previously trained, and using it in face recognition system, names are being displayed below there faces

 

[ictt-tweet-inline hashtags=”#opencv, #python, #facerecognition” via=”via thecodacus”]The Complete Face Recognition Code In One Piece[/ictt-tweet-inline]

Now as Promised

import cv2
import numpy as np

recognizer = cv2.createLBPHFaceRecognizer()
recognizer.load('trainner/trainner.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);


cam = cv2.VideoCapture(0)
font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1)
while True:
    ret, im =cam.read()
    gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    faces=faceCascade.detectMultiScale(gray, 1.2,5)
    for(x,y,w,h) in faces:
        cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2)
        Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
        if(conf<50):
            if(Id==1):
                Id="Anirban"
            elif(Id==2):
                Id="Sam"
        else:
            Id="Unknown"
        cv2.cv.PutText(cv2.cv.fromarray(im),str(Id), (x,y+h),font, 255)
    cv2.imshow('im',im) 
    if cv2.waitKey(10) & 0xFF==ord('q'):
        break
cam.release()
cv2.destroyAllWindows()

Complete Video Tutorial

Feel Free to Subscribe my blog and my youtube channel

 

Updates:
Github links:

For this code: you can visit: https://github.com/thcodacus/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. Mark Summerfield says

    February 21, 2017 at 10:39 pm

    Anirban – this is the best explanation and example code of how to get started with opencv face recognition that I have found. Your code works first time and your explanations of what it is doing are excellent – thank you very much. The only mistake I made (and this may be of use to others) is that I did not give the full path to haarcascade_frontalface_default.xml (your code assumes it is in the current folder – my files are with the opencv installed files) . Simply nothing happens if the path is wrong – and after a short worry I realised my mistake and everything worked. Brilliant.

    Reply
    • Anirban says

      February 22, 2017 at 3:46 am

      Thanks for the feedback 🙂

      Reply
      • Deepan Chakkaravarthy says

        July 11, 2017 at 11:26 pm

        hi anirban ,i had an error
        Traceback (most recent call last):
        File “detector.py”, line 27, in
        cv2.PutText(im,str(Id), (x,y+h),font, 255)
        AttributeError: ‘module’ object has no attribute ‘PutText’
        i’m using opencv 3.1 version .please provide me solution.
        thanks in advance.

        Reply
        • Anirban Kar says

          July 13, 2017 at 1:59 pm

          for opencv 3 its putText … small ‘p’

          Reply
  2. Jose Morales says

    February 22, 2017 at 2:00 am

    Excelent the next is here.. thanks

    Reply
  3. ajith says

    March 4, 2017 at 3:24 pm

    I worked on the coding on seeing your fouth video but i got two errors on compiling in the datasetgenerator file. There is no face.xml file in the opencv so how to solve it.

    Reply
    • Anirban says

      March 5, 2017 at 2:21 pm

      follow from the first video.. cuz 4rth one have some variation in code cuz I reorganized my code after the previous code was deleted by mistake.. So if you follow from he 1st you wont have any problem.. and ignore the variations… (I renamed the same xml file and placed it is a new folder called cascade to make it clean)

      Reply
      • ajith says

        March 8, 2017 at 10:42 pm

        But i getting two errors while running the last coding in your fourth video , upto third video everything is alright.

        Reply
  4. Oleg p says

    March 5, 2017 at 2:57 pm

    Hello Anirban

    How could I do the following:

    1) Browse photos from a folder
    2) detect faces from these photos and save it to another folder
    3) recognize faces from 2 different photos

    thanks for your help in advance

    Reply
    • Anirban says

      March 7, 2017 at 8:18 pm

      if you see the post about training recognizer, you will have clue on how to load images from files.. and if you go back to the dataset creation post you will see we already used some way to same a captures faces.. I think with these two methods you can do what you are wanting to do

      Reply
  5. Abhishek says

    March 6, 2017 at 8:50 pm

    can you make a tutorial for java also?

    Reply
    • Anirban says

      March 7, 2017 at 8:15 pm

      sorry I never used opencv in java

      Reply
    • Janet says

      May 20, 2017 at 11:43 am

      Great arictle, thank you again for writing.

      Reply
  6. ajith says

    March 8, 2017 at 10:40 pm

    I want to connect my wifi camera with my laptop. My main cam in laptop should not open instead of that my SJ5000x wifi cam to be run , which is to detect faces from longer distance. Do you have any coding to connect wifi cam with laptop or any ideas.

    Reply
    • Musab says

      March 22, 2017 at 1:06 pm

      cam = cv2.VideoCapture(0)

      try changing 0 to 1 or 2 and so on tell it work

      Reply
    • Anirban says

      March 22, 2017 at 1:25 pm

      Yes Mussab is almost correct, but before that you need to add a driver so that your ip webcam acts as usb device

      for that if you are using Windows and you have a video your coming from your wifi cam,
      example : “192.168.1.12:8080/video”

      then you can use a Ip webcm adapter to make that link a virtual webcam

      check this ip webcam adapter here
      http://ip-webcam.appspot.com/static/doc.html

      and then you can directly use that cam as
      cv2.VideoCapture(1)

      Reply
      • ajith says

        March 22, 2017 at 11:46 pm

        ok after installing and running the ipwebcam what should i do next

        Reply
        • Anirban says

          March 24, 2017 at 1:15 pm

          Ajith, You can try this tutorial
          https://www.youtube.com/edit?o=U&video_id=2xcUzXataIk

          Reply
  7. Ruben V says

    March 16, 2017 at 3:34 pm

    I’ve just got it working on OpenCV3.0 on my rPi. Had to tweak some opencv syntax to make up for the difference in 2.x3.0. I also had to use the PiCamera() to gather and record the images because the image/videocapturing through OpenCV didn’t work.

    Only problem I still have is that my own face only get’s to a ‘conf’ of 60-70, so my face remains unknown.

    Reply
    • Anirban says

      March 17, 2017 at 1:51 pm

      thrushold for conf can vary depending on how well you trained your recognizer.. just increase the number to 75 maybe

      Reply
    • Anto Finch says

      June 28, 2017 at 3:23 pm

      did the code work on raspi? if it did would you send the edited code to my email please? [email protected]

      Reply
  8. Ash says

    March 17, 2017 at 10:48 am

    hi great tutorial on face recognition. i am having trouble in recognition of my face. i had saved my face by running datasetcreator.py code and trainner.py code. but when i run the main program for recognition it always shows unknown as Id. i dont know how that is happening as i had set Id =1 for my face. i did it 3-4 times but it always shows unknown as Id. pls help !!!!….

    Reply
    • Anirban says

      March 17, 2017 at 1:55 pm

      you have that line for “conf<50" increase the threshold to 70 and try again. i hope that will work

      Reply
      • Ash says

        March 17, 2017 at 3:06 pm

        can u tell me that what does the code:

        conf<50

        Exactly meant for ??

        And thanks btw my issue has been solved. Thanks again. Great tutorial.

        Reply
        • Anirban says

          March 20, 2017 at 2:36 pm

          in conf variable, the recognizer will store the confidence level of its prediction, the lower the value to more stronger the prediction.
          So conf<50 here we are setting a border between known and unknown faces if the confidence level is very low (i.e. the value is very large) then we are considering it as unknown regardless of whatever the prediction is

          Reply
          • Ash says

            March 21, 2017 at 6:18 pm

            Okay thanks very much.

            Also I would like to know about object detection and recognition. Since for Face detection and recognition we have this haar cascade classifiers xml files right, so for object detection like simply table or an apple or a chair do we have any xml files for it???

          • Anirban says

            March 22, 2017 at 1:30 pm

            Ash, I already made an object recognition tutorial in my youtube channel, I will write it in my blog soon,
            and yes you can use xmls that whould be best but you dont have xmls for those ready for you, and training your own xmls are too much time consuming,
            So we can use something called feature matching. and opencv has few feature matching algorithm built in, (i.e. Surf, Sift) we can use those

  9. ram says

    March 21, 2017 at 9:31 am

    Thank you it works perfectly but if a person not in the database appears infront of camera, its showing the existing persons name while recognising. I want to predict them as others who are not in the database list. How to change the code sir?

    Reply
    • Anirban says

      March 22, 2017 at 1:18 pm

      if(conf<50): change the number to a lower one for example 40 and try again

      Reply
      • ram says

        March 22, 2017 at 2:20 pm

        In which code file that conf line is in trainer or detector dataset creator?

        Reply
        • Anirban says

          March 22, 2017 at 2:54 pm

          in detector, “rec.predict()” this returns conf

          Reply
          • ram says

            March 22, 2017 at 4:25 pm

            marvellous thanks

  10. vinod kumar says

    March 21, 2017 at 12:11 pm

    Hi Anirban , Hope you are doing Good!, i have followed your tutorial it was really nice and interesting,it was helped a lop in my development.

    with opencv mainly I am facing the issue with CPU utilization it is very high is there any way to reduce that?? .

    Now we are recognising the face ,please let me know the how to recognise number plates as well if possible !!!!

    Thanks in advance!!…..

    Reply
    • Anirban says

      March 22, 2017 at 1:14 pm

      your camera resolution is maybe very high, and the larger the image the more cpu intensive i becomes, resize the image after capturing it to lower that 640×480, that should do it, I am guessing

      Reply
  11. Shweta Agarwal says

    March 29, 2017 at 11:52 am

    I need the script for the database for face recognition in python. so, please this script.

    Reply
  12. Jose says

    April 1, 2017 at 7:09 am

    hello
    Traceback (most recent call last):
    File “recognizer.py”, line 10, in
    font = cv2.cv.InitFont(cv2.CV_FONT_HERSHEY_COMPLEX_SMALL, 5, 1, 0, 4)
    AttributeError: ‘module’ object has no attribute ‘cv’

    Reply
    • Anirban says

      April 1, 2017 at 2:18 pm

      what is your opencv version?

      Reply
      • Jose says

        April 12, 2017 at 12:03 am

        opencv 3.1.0

        Reply
    • tbanda says

      April 11, 2017 at 7:06 pm

      in your Open CV installation folder “C:\CV Packages\opencv\build\python\2.7\x86\cv2.pyd”
      if you are using a 32Bit Python copy the cv2.pyd and paste it in “C:\Python27\Lib\site-packages\cv2.pyd”

      after doing so type:
      import cv2
      if there is no error cv2 will have imported properly

      Reply
      • Robin Rai says

        July 24, 2017 at 6:53 pm

        ya i did but still showing same problem

        Reply
        • Robin Rai says

          July 24, 2017 at 6:58 pm

          py python version is 2.7 and open cv is 2.4

          Reply
          • Anirban Kar says

            August 6, 2017 at 1:25 pm

            you might have multiple installation of python.. and you are putting cv2.pyd in one of then while running you are using a different one

    • Robin Rai says

      August 6, 2017 at 12:48 pm

      bro me also getting same problem ,are get solution?

      Reply
      • Anirban Kar says

        August 6, 2017 at 1:26 pm

        try just “cv2” instead of “cv2.cv”

        Reply
    • Anirban Kar says

      August 6, 2017 at 1:23 pm

      if you are using Opencv3 then “cv2.cv” in not present in there.. its only “cv2”

      Reply
  13. Shyam Saravanan says

    April 1, 2017 at 7:34 pm

    Great tutorial Anirban.
    It’s awesome.
    Thanks a lot. 😀 😀 😀

    Reply
    • Anirban says

      April 2, 2017 at 4:12 pm

      thanks 🙂

      Reply
  14. sagar says

    April 3, 2017 at 3:59 pm

    File “faceRecog.py”, line 19, in
    id,conf=rec.predict(gray[y:y+h , x:x+w]);
    TypeError: ‘int’ object is not iterable

    i am getting this error in 3 part detection my python version is 3 and opencv is 3.1.0
    please help me solve

    Reply
    • Anirban says

      April 3, 2017 at 4:07 pm

      use this instead
      Id=rec.predict(gray[y:y+h , x:x+w]);

      Reply
      • sagar says

        April 4, 2017 at 9:33 am

        Thanks bro its working now .
        By the way nice tutorials it was amazing time learning from ur videos

        Reply
        • Nasha Goran says

          June 8, 2017 at 6:36 pm

          How working for you
          Please help me i have some problem
          When i change error say me:
          TypeError: ‘rec’ object is not iterable

          Plz help me

          Reply
      • Doan-hq says

        April 10, 2017 at 12:47 pm

        Thank for share, but I have a question:

        if I use this “Id=rec.predict(gray[y:y+h , x:x+w]);”
        next I have to write if(Id<50) ?

        Reply
        • Anirban says

          April 10, 2017 at 10:21 pm

          if you are using opencv3 it doesn’t return conf variable it only returns ID do

          Reply
          • Doan-hq says

            April 11, 2017 at 1:18 pm

            So, how to increase accuracy of detector.
            there are many mistake when i detector face.
            Example: people A but detect to people B
            Please help me

  15. MP says

    April 9, 2017 at 8:17 pm

    Hi! Firstly thank you so much for this tutorial, it helped immensely! There were a lot of errors occurring,and after a lot of sweating finally everything is working. BUT. And I cry when I say this, the recognition part isn’t really doing well. ID keeps showing numbers which I didn’t even save. I trained for ID 1 and 2 only, and for others gave ID=”unknown”, but on running detector.py I get ID sometimes 19 sometimes 20. I tried to put conf<70 even 75. Nothing is working. Please suggest something?

    Reply
    • Anirban says

      April 9, 2017 at 9:05 pm

      your trainer is taking sample numbers as id instead of the id from the dataset images

      Reply
      • MS says

        April 9, 2017 at 10:30 pm

        Thanks! But my code is the same as given here…

        Reply
      • MS says

        April 9, 2017 at 10:47 pm

        How would you suggest I could deal with that? It would be a bummer if this didn’t work after all the sweating 🙁 Thanks anyway!

        Reply
        • Anirban says

          April 10, 2017 at 10:24 pm

          what is the images naming format.. can you copy one of the name in the comment

          Reply
          • MS says

            April 10, 2017 at 11:26 pm

            Sure! They are saved as
            User1.1.jpg
            User1.2.jpg
            …
            User3.1.jpg
            You are definitely right about the fact that it is taking the sample number instead of the id.

          • Anirban says

            April 11, 2017 at 8:40 pm

            you missed a dot it should be “User.1.1.jpg”… thats the reason it was taking sample number instead of id.. it counts dots to get separate them

          • MS says

            April 13, 2017 at 11:40 am

            Oh dear! So silly of me! Thanks a ton ton! Will definitely subscribe to your blog and look forward to your future posts! 🙂

          • Anirban says

            April 13, 2017 at 3:05 pm

            Thanks 🙂

  16. doan-hq says

    April 10, 2017 at 1:07 pm

    Thank you for share. But I have a question. Can you help me
    When other people in camera. It don’t show “Unknow” face, in some case it recognizer mistake.
    My code:
    Id =rec.predict(gray[y:y+h,x:x+w])
    if(Id<70):

    else:
    Id="Unknow"

    Reply
    • chan says

      June 9, 2017 at 1:58 am

      same issue I see anirban.. pls advise.. ?

      Reply
  17. Arefin says

    April 11, 2017 at 7:53 pm

    Thank you so much for sharing a great tutorial. Indeed, it’s a really great work. I have a question to you. Is it possible to print recognised face’s name or id below the square sign on the face.If possible, how ? Thanks again.

    Reply
    • Anirban says

      April 11, 2017 at 8:35 pm

      i am actually doing the same thing

      Reply
  18. gourav says

    April 15, 2017 at 10:01 pm

    hey Anirban i am doing the same thing in raspberry pi i have trained i got the trainner.yml file but when i load it says it is read-only can u help me

    Reply
    • Anirban says

      April 25, 2017 at 8:58 pm

      can you paste the exact error

      Reply
  19. ankit pratap singh says

    April 16, 2017 at 11:41 am

    hey anirban,
    Your explanation is pretty good but I have stuck, that my code is not recognising the face in the dataSet. I followed all three videos.

    Reply
    • Anirban says

      April 25, 2017 at 8:58 pm

      can you please explain little more

      Reply
  20. Ash says

    April 17, 2017 at 1:51 pm

    Hey Anirban, what if i want to hear the name of the person being detected every time? Then what changes i should​ do in the code? I know that for speech output in raspberry pi there are available software like espeak and festival but how to work with them in ur code please suggest any answer….

    Reply
    • Anirban says

      April 25, 2017 at 8:56 pm

      if you have a text to speech library for python.. then you can add a list in the beginning of the code and every time a new name comes up which is not in the list you add it to the list and use text2speech to call the name.. just an idea i didn’t test it

      Reply
  21. vishwam k says

    April 24, 2017 at 3:41 pm

    hi anirban
    thanks for the great tutorial
    but I have a problem in detecting Multiple user id’s
    It shows 1st id to all the remaining other Ids also. the trainer is not differentiating form one Id to Other as expected.
    can you please help me solve this problem

    Reply
    • Anirban says

      April 25, 2017 at 9:00 pm

      check the images… the file name should show the ids.. are they all same?

      Reply
      • vishwam k says

        May 20, 2017 at 2:24 pm

        no gave different ids for different faces i have checked many times

        Reply
  22. Vasantha says

    May 3, 2017 at 10:51 am

    Hai Anirban, thank u for guiding us from this tutorials. I too done the same code and got output. I am trying to count the recognised face of one person. and want to check how many times his face is recognised by incrementing numbers and store that number in excel sheet. I have done seperate coding for writing into excel sheet, but inside this face recognition code this will not work. Can anyone help me to do the code..

    Reply
  23. Faheem Nawaz says

    May 11, 2017 at 10:42 pm

    Nice

    Reply
  24. Vasantha says

    May 13, 2017 at 11:40 am

    Hai Anirban, can i detect multiple face in this code by using different IDs in the same dataSet.

    Reply
    • Anirban says

      June 8, 2017 at 5:08 am

      yes in fact i did that in the video

      Reply
  25. avaneesh kumar says

    May 17, 2017 at 5:49 am

    Can You help me with this error: though this error was aforementioned by someone else also, the solution is not clear.

    import cv2
    import numpy as np

    cascadePath=’/Users/avaneeshkumar/opencv/data/haarcascades/haarcascade_frontalface_default.xml’
    faceCascade=cv2.CascadeClassifier(cascadePath)
    recognizer = cv2.face.createLBPHFaceRecognizer()
    recognizer.load(‘trainner/trainner.yml’)
    id=0
    #cam = cv2.VideoCapture(0)
    font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1)
    while True:
    ret, im =cam.read()
    gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    faces=faceCascade.detectMultiScale(gray, 1.2,5)
    for(x,y,w,h) in faces:
    cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2)
    id, conf = recognizer.predict(gray[y:y+h,x:x+w])
    cv2.PutText(cv2.cv.fromarray(im),str(Id), (x,y+h),font, 255)
    cv2.imshow(‘im’,im)
    if (cv2.waitKey(1)==ord(‘q’)):
    break
    cam.release()
    cv2.destroyAllWindows()

    —————————————————————————
    AttributeError Traceback (most recent call last)
    in ()
    8 id=0
    9 #cam = cv2.VideoCapture(0)
    —> 10 font = cv2.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1)
    11 while True:
    12 ret, im =cam.read()

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

    Reply
    • avaneesh kumar says

      May 17, 2017 at 5:56 am

      I removed cv from the place due to some debugging,
      else

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

      is the error

      Reply
      • avaneesh kumar says

        May 17, 2017 at 6:19 am

        Done :

        Other issue is

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

        Reply
  26. Anish Jain says

    May 18, 2017 at 9:53 am

    Hi, thanks for the great tutorial.
    Can you please provide the above python code for the detector.py file, for OpenCV version 3.2.0 ?
    I’m having syntax errors in the “font, puttext, and fromarray” parts.
    It would be of great help to me as well as many people.
    Hope to hear from you soon. 🙂

    Reply
  27. longuyen says

    June 1, 2017 at 11:37 pm

    hi anirban
    thanks for the great tutorial
    but I have a problem erro:
    gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    cv2.error: ..\..\..\..\opencv\modules\imgproc\src\color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

    can you please help me solve this problem

    Reply
  28. chan says

    June 9, 2017 at 1:57 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
    • Oliver says

      May 6, 2018 at 7:39 pm

      I have the same problem!

      Reply
  29. Nasha Goran says

    June 17, 2017 at 4:32 pm

    how to increase accuracy of detector.
    there are many mistake when i run detector.py
    For Example: people 1 but detect to people 2
    Please help me
    Regards

    Reply
    • Anirban says

      June 18, 2017 at 12:19 am

      For this technique you have to use quality and variety of images of a person.. for more accuracy and the webcam also have to be good

      Reply
  30. kazi mosiur rahman says

    June 22, 2017 at 2:16 pm

    Thanks for the immense support in explaining the process pretty well. I have been able to recognize one particular face recognized. But whenever there is more than one image to recognize the program stops and throws the error. Any particular solution to this. The error thrown is as follows

    OpenCV Error: Assertion failed (s >= 0) in cv::setSize, file ……modulescoresrcmatrix.cpp, line 306

    Reply
    • Anirban Kar says

      July 13, 2017 at 2:01 pm

      there might be some error in your code.. it indicating that the image is empty “Assertion failed (s >= 0)”

      Reply
  31. Aladdin Hammodi says

    June 28, 2017 at 7:00 pm

    Hi Anriban, im using python 2.7 and openCV 3.2im working on windows 64 bit. when i run this code i get this error
    recognizer = cv2.createLBPHFaceRecognizer()
    AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’
    i tried recognizer = cv2.face.createLBPHFaceRecognizer() but still have the same error
    what should i do ?

    Reply
    • Anirban Kar says

      July 13, 2017 at 2:00 pm

      to use face module in opencv 3 you need the contrib library… install it throught pip install

      Reply
      • Robin Rai says

        July 24, 2017 at 7:10 pm

        ya i was getting same problem but i solve it by using python 27 32bit version opencv 2.4.13

        Reply
        • Harish Harz says

          August 7, 2017 at 3:51 am

          thanks robin… i tried opencv 2.4.13…it worked…

          Reply
          • Robin Rai says

            August 14, 2017 at 11:46 pm

            thanks bro it also start to work in 3.14 version

          • Robin Rai says

            August 21, 2017 at 7:40 pm

            well come bro

  32. MayThu Khine says

    August 3, 2017 at 2:41 pm

    cv2.putText(cv2.fromarray(img),str(id),(x,y+h),cv2.FONT_HERSHEY_COMPLEX_SMALL,2,255)
    AttributeError: module ‘cv2’ has no attribute ‘fromarray’

    i use python3.6
    if cv2.fromarry not include,all input image show id=1

    Reply
    • Anirban Kar says

      August 3, 2017 at 3:06 pm

      its actually cv2.cv.fromarray

      Reply
  33. Harish Harz says

    August 7, 2017 at 3:26 am

    i m using python 2.7.13 on windows 64 bit. when i run this code i get this error
    recognizer = cv2.createLBPHFaceRecognizer()
    AttributeError: ‘module’ object has no attribute ‘createLBPHFaceRecognizer’
    i tried recognizer = cv2.face.createLBPHFaceRecognizer() but still have the same error
    what should i do ?

    Reply
    • Anirban Kar says

      August 7, 2017 at 6:13 pm

      you are using opencv 3… so you have to install contrib library of opencv separately to use face module

      Reply
    • KENGTIAN TAN says

      April 22, 2018 at 1:50 pm

      or you can try recognizer = cv2.face.LBPHFaceRecognizer_create()

      Reply
  34. Carson Roberts says

    August 12, 2017 at 12:43 am

    When I run the code it works but is not accurate at all how can I fix this? I have it running on a windows 64bit with opencv 2.4 and python 2.7.

    Reply
  35. ИВАН ПЛОТНИКОВ says

    September 26, 2017 at 2:47 pm

    At attracting windows 7,32 bit.
    Python 3.5.3
    opencv-3.3.0-vc14
    Through PIP I establish:
    numpy-1.12.1+mkl-cp35-cp35m-win32.whl
    opencv_python-3.3.0+contrib-cp35-cp35m-win32.whl
    PIL-2.0+dummy-py2.py3-none-any.whl
    Pillow-4.2.1-cp35-cp35m-win32.whl

    python gives out an error:

    Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 15:51:26) [MSC v.1900 32 bit (Intel)] on win32
    Type “copyright”, “credits” or “license()” for more information.

    RESTART: C:111111111111пока самое лушееFace-Recognition-mastertraining.py
    Traceback (most recent call last):
    File “C:111111111111пока самое лушееFace-Recognition-mastertraining.py”, line 9, in
    import cv2, os
    ImportError: DLL load failed:The specified module is not found.

    Please tell in what a problem? Forgive for my English.

    Reply
    • Anirban Kar says

      September 28, 2017 at 7:45 pm

      Not sure but this might help
      https://stackoverflow.com/questions/20201868/importerror-dll-load-failed-the-specified-module-could-not-be-found

      Reply
      • ИВАН ПЛОТНИКОВ says

        September 29, 2017 at 3:09 pm

        Hi Anirban Kar! Thanks, with this problem I have understood.
        (opencv_python-3.3.0+contrib-cp35-cp35m-win32.whl) Has replaced (opencv_contrib_python-3.3.0.10-cp35-cp35m-win32.whl).

        There was other problem. Did not see the module.
        In (face_recognition.py) I have changed (recognizer = cv2.face.createLBPHFaceRecognizer ()) on (recognizer = cv2.face. LBPHFaceRecognizer_create ()) Then he has seen it. And again an error:

        RESTART: C:111111111111poka most lusheeFace-Recognition-masterface_recognition.py
        Traceback (most recent call last):
        File “C:111111111111poka most lusheeFace-Recognition-masterface_recognition.py”, line 17, in
        recognizer.load (‘ trainer/trainer.yml ‘)
        AttributeError: ‘ cv2.face_LBPHFaceRecognizer ‘ object has no attribute ‘ load’

        Why cannot (load)?
        Before in (training.py) record has passed (recognizer.save (‘ trainer.yml ‘)).
        In what there can be a problem?
        Forgive for my English.

        Reply
        • Anirban Kar says

          October 2, 2017 at 10:27 am

          I would suggest you use anaconda to install opencv 3.2 in windows. I just tested it. and its working perfectly.
          add the following channels and install the “opencv” package using Anaconda Navigator
          https://uploads.disquscdn.com/images/4d919f4bb386e623871a71e3113a0f7ac2e220b5d45f2fb439ef1515fbf5c243.png
          https://uploads.disquscdn.com/images/d556e1d7e48abce06e3ef3b42847746b401caafa14ea9288818903507d101cbe.png

          Reply
        • Sri Harsha says

          January 8, 2018 at 12:43 am

          In training.py replace last line i.e,
          recognizer.load (‘ trainer/trainer.yml ‘)
          with
          recognizer.write(‘trainer/trainer.yml’)
          and rerun trainer and reconizer

          hope this helps

          Reply
          • ИВАН ПЛОТНИКОВ says

            January 8, 2018 at 1:28 am

            I corrected this mistake, just as you wrote. (replaced recognizer.load by recognizer.write)

            2018-01-07 22:13 GMT+03:00 Disqus notifications@disqus.net:

      • ИВАН ПЛОТНИКОВ says

        October 1, 2017 at 9:51 pm

        Hi Anirban Kar! Has replaced a line recognizer.load (‘ trainer/trainer.yml ‘), with this recognizer.read (‘ trainer/trainer.yml ‘).
        http://docs.opencv.org/3.3.0/dd/d65/classcv_1_1face_1_1FaceRecognizer.html

        There was a following error:

        RESTART: C:111111111111Face-Recognition-masterfacedetectionandrecoginiton.py
        Traceback (most recent call last):
        File “C:111111111111Face-Recognition-masterfacedetectionandrecoginiton.py”, line 18, in
        Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
        cv2.error: C:projectsopencv-pythonopencv_contribmodulesfacesrclbph_faces.cpp:396: error: (-5) This LBPH model is not computed yet. Did you call the train method? in function cv::face::LBPH::predict

        Why? Help please.

        Reply
  36. sam siddiquiz says

    October 9, 2017 at 4:12 pm

    Not Opening Cam :/
    Traceback (most recent call last):
    File “C:Userssam_oDownloadsCompressedFace-Recognition-masterFace-Recognition-masterdataSetGenerator.py”, line 15, in
    cv2.imshow(‘im’,im[y-offset:y+h+offset,x-offset:x+w+offset])
    error: C:buildsmaster_PackSlaveAddon-win32-vc12-staticopencvmoduleshighguisrcwindow.cpp:271: error: (-215) size.width>0 && size.height>0 in function cv::imshow

    Reply
  37. Kawsur Abeddin Noori says

    October 28, 2017 at 7:13 pm

    There’s a new problem at the last stage of recognition. Syntax error. But I checked it and found none. https://uploads.disquscdn.com/images/34be71968da7b1a347ba3a9ca7a368d49b595da02200465230904040a0738123.png oblem

    Reply
  38. Kawsur Abeddin Noori says

    October 29, 2017 at 4:52 pm

    At detector they are showing me this one. Too many value to unpack. It start camera but when something come infront of it it showing me this error !! https://uploads.disquscdn.com/images/ca53c1bcaf7ad4c87fe5d3bb6fc5e7cbebb3496a36a44a56e50a0d89176eac55.png

    Reply
    • Anirban Kar says

      October 29, 2017 at 5:02 pm

      its for(x,y,w,h)

      Reply
      • Kawsur Abeddin Noori says

        October 29, 2017 at 5:12 pm

        It’s working brother. Thanks a lot.

        Reply
  39. Mohini Mohan Behera says

    November 1, 2017 at 7:07 pm

    Sir my face detector working nicely but it is not detecting the unknown although i use else: Id=”unknown” in the code and i print the id for unknown person it still showing 1 or 2.Can you plz tell me the reason and help me to rectify this.

    Reply
  40. Abe says

    November 12, 2017 at 8:59 pm

    Look at my code please
    import numpy as np
    import cv2
    from pip._vendor.distlib.compat import raw_input

    face_cascade = cv2.CascadeClassifier(‘haarcascade_frontalface_default.xml’)

    eye_cascade = cv2.CascadeClassifier(‘haarcascade_eye.xml’)

    cap = cv2.VideoCapture(0)
    rec = cv2.face.LBPHFaceRecognizer_create();
    rec.read(“recognizer\TD.yml”)
    id = 0
    font = cv2.FONT_HERSHEY_COMPLEX_SMALL,5,1,0,4

    while (True):
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x,y,w,h) in faces: <code>cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] eyes = eye_cascade.detectMultiScale(roi_gray) for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) id,conf=rec.predict(gray[y:y+h,x:x+w]) if(id==1): id="Abhay" elif(id==2): id="Amma" cv2.cv.PutText(cv2.cv.fromarray(img),str(id),(x,y+h),font,255);

    cv2.imshow(‘img’,img)
    if (cv2.waitKey(1)==ord(‘q’)):
    break;

    cap.release()
    cv2.destroyAllWindows()

    I have this error
    Traceback (most recent call last):
    File “F:Face DetectionFace_Detection_And_RecognizationDetector.py”, line 32, in
    id,conf=rec.predict(gray[y:y+h,x:x+w])
    cv2.error: C:projectsopencv-pythonopencv_contribmodulesfacesrclbph_faces.cpp:396: error: (-5) This LBPH model is not computed yet. Did you call the train method? in function cv::face::LBPH::predict

    Please help me solve this this is really important to me by the way I’m using python 3.6.2

    Reply
  41. ian maynard bramasto says

    December 11, 2017 at 11:20 am

    Hello Anirban, nice tutorial blog here. I am currently working with raspberry pi 3, opencv 3.1.0, and python 2.7.9 so i found the link to nazmi69 is somehow faultless to follow. But my question is actually the same with some people here. How can we distinguish between the known people (people in dataset) and the unknown people (random people/face that detected by the camera)? I tried to find a way to get the confidence value so i can put them in as argument in “if” like you did( “if (conf >=80)” maybe), but i cant find any.. can you help me please?

    Reply
  42. Himanshu Bhoraniya says

    December 16, 2017 at 7:44 pm

    I want to do road symbol recognition, but this doesn’t help me much, can you please suggest me how to do it.

    Reply
  43. aveek says

    January 7, 2018 at 2:50 am

    error showing up, ‘bool’ object has no attribute ‘predict’. please help

    Reply
  44. Roberto Bendinelli says

    January 9, 2018 at 3:38 am

    Hi,
    thanks a lot about your tutorials.
    can we use this code on raspberry p3?
    thanks
    Roberto

    Reply
    • Taha Anwar says

      February 13, 2018 at 12:04 am

      Yes but ofcourse u have to install opencv first

      Reply
  45. Lucian Kudo says

    January 12, 2018 at 7:24 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
    • Taha Anwar says

      February 13, 2018 at 12:03 am

      use if conf < 55 :
      Id =”Unkown”

      Reply
  46. Mirja Ashraf says

    January 25, 2018 at 1:50 pm

    id=rec.predict(gray[y:y+h,x:x+h])
    cv2.error: C:projectsopencv-pythonopencv_contribmodulesfacesrclbph_faces.cpp:403: error: (-5) This LBPH model is not computed yet. Did you call the train method? in function cv::face::LBPH::predict
    help me bro.

    Reply
    • Movie Craze says

      March 2, 2018 at 9:07 pm

      train the model once again… just run the trainer code again before using recognizer.

      Reply
  47. hadia arif says

    January 29, 2018 at 12:19 am

    i am having trouble in recognition of my face. i had saved my face by running datasetcreator.py code and trainner.py code. but when i run the main program for recognition it always shows unknown as Id. i dont know how that is happening as i had set Id =1 for my face. i did it 3-4 times but it always shows unknown as Id. pls help ……
    inspite i have changed “conf<50” increase the threshold to 70 ,but its not working yet!
    pls help me out

    Reply
    • Lee puiwah says

      April 12, 2018 at 9:48 pm

      hi there. i have the same problem as you do. Have you solve the issue yet?

      Reply
  48. Anoop krishnan says

    February 5, 2018 at 8:53 pm

    can anyone help this is the error i am getting

    C:Python27python.exe “D:/third eye/face/face/detector.py”OpenCV Error: Bad argument (This LBPH model is not computed yet. Did you call the train method?) in cv::face::LBPH::predict, file C:projectsopencv-pythonopencv_contribmodulesfacesrclbph_faces.cpp, line 403
    Traceback (most recent call last):
    File “D:/third eye/face/face/detector.py”, line 18, in
    id = rec.predict(gray[y:y+h,x:x+w])
    cv2.error: C:projectsopencv-pythonopencv_contribmodulesfacesrclbph_faces.cpp:403: error: (-5) This LBPH model is not computed yet. Did you call the train method? in function cv::face::LBPH::predict

    [ INFO:0] Initialize OpenCL runtime…

    Process finished with exit code 1

    Reply
  49. mehak shahid says

    February 22, 2018 at 2:24 pm

    if(Id==1):
    Id=”Anirban”
    elif(Id==2):
    Id=”Sam”

    Any suggestion on how to not hard code it but save it in the while creating the user and saving data? Like asking the name along with ID. Then trying to train the trainer with ID and name. Any suggestions?

    Reply
  50. Movie Craze says

    March 4, 2018 at 11:55 am

    hey i have an error ‘ C:bldopencv_1506447021968workopencv-3.3.0modulesimgprocsrccolor.cpp:10638: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor’
    I tried really hard but couldn’t get any help from anywhere(including stackoverflow). Please help me bro…
    here’s my code :

    import cv2
    import numpy as np

    recognizer = cv2.face.LBPHFaceRecognizer_create()

    FaceDetect = cv2.CascadeClassifier(‘haarcascade_frontalface_alt.xml’)
    cap = cv2.VideoCapture(0)
    recognizer.read(“recognizer\trainingData.yml”)
    id=0
    while 1:
    ret,img = cap.read()
    gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
    faces = FaceDetect.detectMultiScale(gray,1.3,5)
    for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
    id,conf=recognizer.predict(gray[y:y+h,x:x+w])
    cv2.cv.PutText(cv2.cv.fromarray(img),str(id),(x,y+h),(0,0,255))
    cv2.imshow(“Face”,img)
    if cv2.waitKey(1) & 0xFF==ord(‘q’):
    break
    cap.release()
    cv2.destroyAllWindows()

    Reply
    • Marco De Groskovskaja says

      April 22, 2018 at 10:32 pm

      I had the same issue, I’ve figured out running the script on another computer. The problem:
      OpenCV in my laptop was not able to use the webcam (I don’t know why) so it doesn’t take the image and it throws an error when I tried to convert the image in grayscale (that doesn’t exists cause I have captured nothing).

      Reply
  51. Austin Joy says

    March 10, 2018 at 11:47 am

    Thank you for the tutorial, ive made some changes where the names and ids are stored in a separtate text file, However is it possible to extract names from the text file instead of inserting names manually in the if and elif conditions?

    Reply
  52. Aniket Rathore says

    March 10, 2018 at 9:03 pm

    Hello Sir ..
    I’m getting ” ‘int’ object is not iterable” error. I look for this and tried but did’t work.Sir please help me out.
    I’m adding code image with it. https://uploads.disquscdn.com/images/5e6eb1aed315ecd6325f38b70585c07786b2b062d03f60c8db129427d131ba4d.png

    Reply
  53. Shashidhar Kumbar says

    March 19, 2018 at 8:24 am

    hey nice work there, plz can help me getting rid of this error
    File “o.py”, line 19
    if(conf<50):
    ^
    SyntaxError: invalid syntax

    Reply
    • KENGTIAN TAN says

      April 22, 2018 at 1:22 pm

      i used if(conf<=50):

      worked for me.

      Reply
  54. Kenny Blaze says

    March 22, 2018 at 7:42 pm

    I am getting an issue while running the program, where it prompts that it cannot read the file which is as programmed
    for this part——–> rec.read(‘recognizers/trainingData.yml’)
    Traceback (most recent call last):
    File “F:/opencv/python projects/face recognition/detector.py”, line 7, in
    rec.read(‘recognizers/trainingData.yml’)
    error: C:projectsopencv-pythonopencv_contribmodulesfacesrcfacerec.cpp:61: error: (-2) File can’t be opened for reading! in function cv::face::FaceRecognizer::read

    please help me at this part

    Reply
    • KENGTIAN TAN says

      April 22, 2018 at 2:11 pm

      try recognizer.read(file path) instead, your file path should be something that looks like (“C:User/Desktop/Trainner/trainner.yml”)

      Reply
  55. Shyrene Mae DAGO-OC says

    April 13, 2018 at 7:03 am

    it only recognized the last id with name i entered.

    Reply
  56. Oliver says

    May 6, 2018 at 5:13 pm

    https://uploads.disquscdn.com/images/85d60a4a0f203c6eda1cd88bd566104843d1893c79bff362e40e5b9c4f579cf4.png

    I have trained my system with the trainer. After that I want to start my recognizer and I get always this error messages (un the picture).

    Can anybody help me further with this problem?

    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