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
[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
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.
Thanks for the feedback 🙂
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.
for opencv 3 its putText … small ‘p’
Excelent the next is here.. thanks
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.
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)
But i getting two errors while running the last coding in your fourth video , upto third video everything is alright.
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
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
can you make a tutorial for java also?
sorry I never used opencv in java
Great arictle, thank you again for writing.
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.
cam = cv2.VideoCapture(0)
try changing 0 to 1 or 2 and so on tell it work
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)
ok after installing and running the ipwebcam what should i do next
Ajith, You can try this tutorial
https://www.youtube.com/edit?o=U&video_id=2xcUzXataIk
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.
thrushold for conf can vary depending on how well you trained your recognizer.. just increase the number to 75 maybe
did the code work on raspi? if it did would you send the edited code to my email please? [email protected]
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 !!!!….
you have that line for “conf<50" increase the threshold to 70 and try again. i hope that will work
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.
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
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???
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
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?
if(conf<50): change the number to a lower one for example 40 and try again
In which code file that conf line is in trainer or detector dataset creator?
in detector, “rec.predict()” this returns conf
marvellous thanks
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!!…..
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
I need the script for the database for face recognition in python. so, please this script.
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’
what is your opencv version?
opencv 3.1.0
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
ya i did but still showing same problem
py python version is 2.7 and open cv is 2.4
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
bro me also getting same problem ,are get solution?
try just “cv2” instead of “cv2.cv”
if you are using Opencv3 then “cv2.cv” in not present in there.. its only “cv2”
Great tutorial Anirban.
It’s awesome.
Thanks a lot. 😀 😀 😀
thanks 🙂
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
use this instead
Id=rec.predict(gray[y:y+h , x:x+w]);
Thanks bro its working now .
By the way nice tutorials it was amazing time learning from ur videos
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
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) ?
if you are using opencv3 it doesn’t return conf variable it only returns ID do
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
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?
your trainer is taking sample numbers as id instead of the id from the dataset images
Thanks! But my code is the same as given here…
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!
what is the images naming format.. can you copy one of the name in the comment
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.
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
Oh dear! So silly of me! Thanks a ton ton! Will definitely subscribe to your blog and look forward to your future posts! 🙂
Thanks 🙂
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"
same issue I see anirban.. pls advise.. ?
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.
i am actually doing the same thing
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
can you paste the exact error
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.
can you please explain little more
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….
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
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
check the images… the file name should show the ids.. are they all same?
no gave different ids for different faces i have checked many times
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..
Nice
Hai Anirban, can i detect multiple face in this code by using different IDs in the same dataSet.
yes in fact i did that in the video
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’
I removed cv from the place due to some debugging,
else
AttributeError: ‘module’ object has no attribute ‘cv’
is the error
Done :
Other issue is
AttributeError: ‘module’ object has no attribute ‘PutText’
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. 🙂
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
HI Anirban , You did fantastic job !! Congratulations. I have one question – I tried this out – even when unknown faces are presented to webcam it says the same name for which Id is defined and trained.. It does not say Unkown.. any clue – what I can modify to make it work ?
I have the same problem!
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
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
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
there might be some error in your code.. it indicating that the image is empty “Assertion failed (s >= 0)”
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 ?
to use face module in opencv 3 you need the contrib library… install it throught pip install
ya i was getting same problem but i solve it by using python 27 32bit version opencv 2.4.13
thanks robin… i tried opencv 2.4.13…it worked…
thanks bro it also start to work in 3.14 version
well come bro
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
its actually cv2.cv.fromarray
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 ?
you are using opencv 3… so you have to install contrib library of opencv separately to use face module
or you can try recognizer = cv2.face.LBPHFaceRecognizer_create()
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.
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.
Please tell in what a problem? Forgive for my English.
Not sure but this might help
https://stackoverflow.com/questions/20201868/importerror-dll-load-failed-the-specified-module-could-not-be-found
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:
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.
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
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
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:
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:
Why? Help please.
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
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
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
its for(x,y,w,h)
It’s working brother. Thanks a lot.
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.
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
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?
I want to do road symbol recognition, but this doesn’t help me much, can you please suggest me how to do it.
error showing up, ‘bool’ object has no attribute ‘predict’. please help
Hi,
thanks a lot about your tutorials.
can we use this code on raspberry p3?
thanks
Roberto
Yes but ofcourse u have to install opencv first
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!,,,
use if conf < 55 :
Id =”Unkown”
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.
train the model once again… just run the trainer code again before using recognizer.
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
hi there. i have the same problem as you do. Have you solve the issue yet?
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
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?
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()
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).
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?
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
hey nice work there, plz can help me getting rid of this error
File “o.py”, line 19
if(conf<50):
^
SyntaxError: invalid syntax
i used if(conf<=50):
worked for me.
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
try recognizer.read(file path) instead, your file path should be something that looks like (“C:User/Desktop/Trainner/trainner.yml”)
it only recognized the last id with name i entered.
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?