Почему мой идентификатор и мое имя не отображаются при распознавании моего лица, даже если conf меньше 50? - PullRequest
0 голосов
/ 08 февраля 2020
enter code here    
import tkinter as tk
from tkinter import Message,Text
import cv2,os
import numpy as np
from PIL import Image,ImageTk
import pandas as pd
import numpy as np
import datetime
import time
import tkinter.ttk as ttk
import tkinter.font as font
import csv

window=tk.Tk()
window.title("Face Recognizer")
window.geometry("1280x720")
dialog_title='QUIT'
dialog_text='Are you sure'
window.configure(background='grey')
window.grid_rowconfigure(0,weight=1)
window.grid_columnconfigure(0,weight=1)
message=tk.Label(window,text="FACE RECOGNITION BASED ATTENDENCE MANAGEMENT 
SYSTEM",bg='black',fg='white',width=100,height=5,font=('times',15))
message.place(x=230,y=20)
lbl=tk.Label(window,text='ENTER ID',width=30,height=3,bg='black',fg='white',font=('times',10))
lbl.place(x=100,y=200)
txt=tk.Entry(window,width=20,bg='black',fg='white',font=('times',10))
txt.place(x=350,y=220)
lbl2=tk.Label(window,text='ENTER NAME',width=30,height=3,bg='black',fg='white',font=('times',10))
lbl2.place(x=100,y=300)
txt2=tk.Entry(window,width=20,bg='black',fg='white',font=('times',10))
txt2.place(x=350,y=320)
lbl3=tk.Label(window,text='NOTIFICATION',width=30,height=3,bg='black',fg='white',font=('times',10))
lbl3.place(x=100,y=400)     
message=tk.Label(window,text='',width=30,height=3,bg='black',fg='white',activebackground='black'
,font='times',10))
message.place(x=350,y=400)
lbl4=tk.Label(window,text='ATTENDENCE',width=30,height=3,bg='black',fg='white',font=('times',10))
lbl4.place(x=100,y=600)
message2=tk.Label(window,text='',width=30,height=3,bg='black',fg='white',activebackground='black', 
font=('times',10))
message2.place(x=350,y=600)

def clear():
    txt.delete(0,'end')
    res=""
    message.configure(text=res)
def clear2():
    txt2.delete(0,'end')
    res=""
    message2.configure(text=res)
def is_number(s):
    try:
       float(s)
       return True
    except ValueError:
       pass
    try:
         import unicodedata
         unicodedata.numeric(s)
         return True
    except (TypeError,ValueError):
         pass
    return False

def TakeImages():
     Id=(txt.get())
     name=(txt2.get())
     if(is_number(Id)and name.isalpha()):
          cam=cv2.VideoCapture(0)
          detector=cv2.CascadeClassifier(r"C:\Users\KIIT\Desktop\Deep 
          Learning\haarcascades\haarcascade_frontalface_default.xml")
          samplenum=0
      while(True):
          ret,img=cam.read()
          gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
          faces=detector.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)
               samplenum=samplenum+1
               cv2.imwrite(r"C:\Users\KIIT\Desktop\Deep Learning\Face Detection Attendence\Training 
               Images\ "+name+" "+"."+str(samplenum)+".jpg",gray[y:y+h,x:x+w])
                cv2.imshow("Face",img);
                k=cv2.waitKey(100) & 0xff
                if k==27:
                break
                elif samplenum>=60:
                break
    cam.release()
    cv2.destroyAllWindows()
    res="Images saved for ID:"+Id+" Name:"+name
    row=[Id,name]
    with open(r"C:\Users\KIIT\Desktop\Deep Learning\Face Detection Attendence\Student Details\studentdetails.csv",'a+') as csvFile:
        writer=csv.writer(csvFile)
        writer.writerow(row)
    csvFile.close()
    message.configure(text=res)
else:
    if(is_number(Id)):
        res='Enter Alphabetical Name'
        message.configure(text=res)
    if(name.isalpha()):
        res='Enter Numeric Id'
        message.configure(text=res)

def TrainImages():
    recognizer =cv2.face.LBPHFaceRecognizer_create()
    faces,Id=getImagesAndLabels(r"C:\Users\KIIT\Desktop\Deep Learning\Face Detection Attendence\Training Images")
    recognizer.train(faces,np.array(Id))
    recognizer.write(r'C:\Users\KIIT\Desktop\Deep Learning\Face Detection Attendence\Training\\trainer.yml')
    res="Image Trained"#+",".join(str(f) for f in Id)
    message.configure(text=res)

def getImagesAndLabels(path):

    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]     
    faces=[]
    Ids= []

    for imagePath in imagePaths:

        PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
        img_numpy = np.array(PIL_img,'uint8')

        Id = int(os.path.split(imagePath)[-1].split(".")[1])
        faces.append(img_numpy)
        Ids.append(Id)
    return faces,Ids

def TrackImages():
    recognizer=cv2.face.LBPHFaceRecognizer_create()
    recognizer.read(r"C:\Users\KIIT\Desktop\Deep Learning\Face Detection Attendence\Training\trainer.yml")
    detector=cv2.CascadeClassifier(r"C:\Users\KIIT\Desktop\Deep Learning\haarcascades\haarcascade_frontalface_default.xml")
    df=pd.read_csv(r"C:\Users\KIIT\Desktop\Deep Learning\Face Detection Attendence\Student Details\studentdetails.csv")
    fontt=cv2.FONT_HERSHEY_SIMPLEX
    cam=cv2.VideoCapture(0)
    col_names=['Id','Name','Date','Time']
    attendence=pd.DataFrame(columns=col_names)
    while True:
        ret,img=cam.read()
        gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        faces=detector.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])
            if (conf < 50):
                ts=time.time()
                date=datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
                timestamp=datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
                aa=df.loc[df['Id']==Id]['Name'].values
                tt=str(Id)+"-"+aa
                attendence.loc[len(attendence)]=[Id,aa,date,timestamp]
            else:
                Id='Unknown'
                tt=str(Id)
            if conf > 75:
                noOfile=len(os.listdir(r"C:\Users\KIIT\Desktop\Deep Learning\Face Detection Attendence\ImagesUnknown"))+1
                cv2.imwrite(r"C:\Users\KIIT\Desktop\Deep Learning\Face Detection Attendence\ImagesUnknown\Image"+str(noOfile)+'.jpg',img[y:y+h,x:x+w])
            conf = "  {0}%".format(round(100 - conf))
            cv2.putText(img,str(tt),(x,x+h),fontt,1,(255,255,0),2)
            cv2.putText(img,str(conf), (x+5,y+h-5),fontt, 1, (255,255,0), 1)
        attendence=attendence.drop_duplicates(subset=['Id'],keep='first')
        cv2.imshow('img',img)
        if(cv2.waitKey(1) & 0xFF==ord('q')):
            break
    ts=time.time()
    date=datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
    timestamp=datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
    Hour,Minute,Second=timestamp.split(":")
    filename=r"C:\Users\KIIT\Desktop\Deep Learning\Face Detection Attendence\Attendence\Attendence_"+date+"_"+Hour+"-"+Minute+"-"+Second+".csv"
    attendence.to_csv(filename,index=False)
    cam.release()
    cv2.destroyAllWindows()
    res=attendence
    message2.configure(text=res)

clbutton=tk.Button(window,text='CLEAR',command=clear,width=20,height=3,bg='black',fg='white',activebackground='black',font=('times',10))
clbutton.place(x=500,y=200)
clbutton2=tk.Button(window,text='CLEAR',command=clear2,width=20,height=3,bg='black',fg='white',activebackground='black',font=('times',10))
clbutton2.place(x=500,y=300)
tkimage=tk.Button(window,text='TAKE IMAGES',command=TakeImages,width=20,height=3,bg='black',fg='white',activebackground='black',font=('times',10))
tkimage.place(x=140,y=500)
trainimage=tk.Button(window,text='TRAIN IMAGES',command=TrainImages,width=20,height=3,bg='black',fg='white',activebackground='black',font=('times',10))
trainimage.place(x=350,y=500)
trackimage=tk.Button(window,text='TRACK IMAGES',command=TrackImages,width=20,height=3,bg='black',fg='white',activebackground='black',font=('times',10))
trackimage.place(x=550,y=500)
quitwindow=tk.Button(window,text='QUIT',command=window.destroy,width=20,height=3,bg='black',fg='white',activebackground='black',font=('times',10))
quitwindow.place(x=750,y=500)
window.mainloop()

В файле CSV появилось несколько идентификаторов, и имя не отображается, а также при распознавании моего лица, когда conf меньше 50, оно не показывает мое имя и идентификатор, оно показывает неизвестное, я думаю, что это может из-за того, что условие if в функции TrackImages не выполняется. См. оба изображения, приведенные ниже, по следующим ссылкам: -

введите описание изображения здесь

введите описание изображения здесь

...