Ask Your Question
0

Face Prediction is invalid in Opencv Python

asked 2018-05-01 05:02:18 -0600

khalid gravatar image

updated 2018-05-01 05:28:04 -0600

berak gravatar image

faces are showing Wrong Information in cv2.putText

Following is my code

 def start_webcam(self):
        try:
            face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml');
            capture = cv2.VideoCapture(1);
            while(True):
                ret, img = capture.read();
                gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                faces = face_cascade.detectMultiScale(gray, 1.3, 5);
                for (x, y, w, h) in faces:
                    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
                    cv2.waitKey(10)
                cv2.imshow('img', img);
                #cv2.waitKey(100)
            #self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT,480)
            #self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
            #self.timer=QTimer(self)
            #self.timer.timeout.connect(self.update_frame)
            #self.timer.start(5)
            capture.release()
            cv2.destroyAllWindows()
        except Exception:
            logging.exception("Connection issue")

 def stop_webcam(self):
        try:
            if self.studentid==0:
                self.displayMessageBox("Enter Student Information first")
                return;
            while(True):
                capture = cv2.VideoCapture(1);
                return_value, img=capture.read()
                gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                for i in range(5):
                 cv2.imwrite("dataSet/User." + str(self.studentid) + "." + str(i) + '.jpg',gray)
                 cv2.waitKey(100)
            del (capture)
            cv2.imshow("face",img)
            capture.release()

  def Traniner_Button(self):
        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)
                cv2.imshow("training", faceNp)
                cv2.waitKey(10)
            return np.array(IDs), faces

        def train():
            Ids, faces=getImagesWithID(path)
            recognizer.train(faces, Ids)
            recognizer.save('recognizer/trainingData.yml')
            cv2.destroyAllWindows()
        try:
            train()
        except Exception:
            logging.exception("Trainer Issue")

recognizer=cv2.face.LBPHFaceRecognizer_create()
        recognizer.read('recognizer/trainingData.yml')
        cascadePath=('haarcascade_frontalface_default.xml')
        faceCascade=cv2.CascadeClassifier(cascadePath);
        font=cv2.FONT_HERSHEY_SIMPLEX
        cam=cv2.VideoCapture(1)
        studentProf=None
        try:
            while True:
                ret, img=cam.read();
                gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                faces=faceCascade.detectMultiScale(gray, 1.2, 5)
                for (x, y, w, h) in faces:
                    cv2.rectangle(img, (x, y), (x + w, y + h), (225, 0, 0), 2)
                    imgId, confidence=recognizer.predict(gray[y:y + h, x:x + w])
                    studentProf = self.getStudentProfile(str(imgId))
                    if (studentProf != None):
                        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
                        cv2.putText(img, str(studentProf), (x, y + h), font, 1, (255, 255, 255), 3)
                    cv2.waitKey(10)
                cv2.imshow('img', img)
edit retag flag offensive close merge delete

Comments

are showing Wrong Information

what do you mean, exactly ?

what does getStudentProfile() do ?

berak gravatar imageberak ( 2018-05-01 05:29:35 -0600 )edit

this function just return studentName from database. i am storing ids of each image in database. But when i m trying to detect face using webcam it always shows the last entered record on each face

khalid gravatar imagekhalid ( 2018-05-01 06:30:56 -0600 )edit

Ic, Actually this is my first time, i am using opencv. StudentID is defined in the same class, but now i got it. yml file should be updated on second call. i will check and will update here.

khalid gravatar imagekhalid ( 2018-05-01 06:51:03 -0600 )edit

if you call Traniner_Button() repeatedly, you should load the existing xml file, and call recognizer.update() instead of train().

and if your studentid != 0 ? there will be no prompt, and it will just take the last id

berak gravatar imageberak ( 2018-05-01 07:00:58 -0600 )edit

def train(): Ids, faces=getImagesWithID(path) my_file = Path("recognizer/trainingData.yml") if my_file.is_file(): recognizer.load("recognizer/trainingData.yml") recognizer.update(faces,Ids) else: recognizer.train(faces, Ids) recognizer.save('recognizer/trainingData.yml') cv2.destroyAllWindows() try: train() except Exception: logging.exception("Trainer Issue")

AttributeError: 'cv2.face_LBPHFaceRecognizer' object has no attribute 'load'

khalid gravatar imagekhalid ( 2018-05-01 07:42:52 -0600 )edit

i printed the Ids in Train loop, it shows Id 66 and 67 which means its correctly getting the Ids, now the only issue is Updating the existing yml file.i used .read() method instead of load() and updated the file but still showing same ids profile

khalid gravatar imagekhalid ( 2018-05-01 07:45:24 -0600 )edit

use read() and write() then

berak gravatar imageberak ( 2018-05-01 08:34:27 -0600 )edit

dear berak, still same issue :(

def train(): Ids, faces=getImagesWithID(path) my_file = Path('recognizer/trainingData.yml') if my_file.is_file(): recognizer.read('recognizer/trainingData.yml') recognizer.train(faces, Ids) recognizer.write('recognizer/trainingData.yml') else: recognizer.train(faces, Ids) recognizer.save('recognizer/trainingData.yml') cv2.destroyAllWindows() try: train() except Exception: logging.exception("Trainer Issue")

In YML file i can see the follow in Data: data: [ 81, 81, 81, 81, 81, 82, 82, 82, 82, 82 ] which means Ids are appending but still same Ids are showing when i predict

khalid gravatar imagekhalid ( 2018-05-01 13:01:38 -0600 )edit

if i predict both images its showing the Last Ids only 82

khalid gravatar imagekhalid ( 2018-05-01 13:03:57 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
0

answered 2018-05-01 15:48:18 -0600

khalid gravatar image

Hello Berak, finally i fixed the issues. Thank you very much :)

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2018-05-01 05:02:18 -0600

Seen: 512 times

Last updated: May 01 '18