Search code examples
pythonopencvfacial-identification

I am working on a facial recognition and attendance system which writes the name and time in a CSV file, but the same person is logged multiple times


I am working on a facial recognition and attendance system which writes the name and time in a CSV file.In order to avoid logging the same person for multiple 'in' times i am writtng a logic which checks if the name is present in the attendance log already,if not then the attendance is looged.But the same name is logged over and over inspite of it being already logged once,i am unable to understand the problem.

this is the code snippet:

Draw a label with a name below the face

    cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
    font = cv2.FONT_HERSHEY_DUPLEX
    cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
    #markAttendance(name)
    with open('ATTLOG.csv', "r+") as g:
        myDatalist = g.readlines()
        nameList=[]
        for line in myDatalist:
            entry = line.split(',')
            nameList.append(entry[0])
            if name not in nameList:
                now=datetime.now()
                dtString = now.strftime('%H:%M:%S')
                g.writelines(f'\n{name},{dtString}')

Solution

  • You have a logic bug: you read the whole file into nameList, then you check if the current name is in the first item of nameList. If not you write it into the file: If your current name comes later in nameList, you will write it although you should not.

    You need to read the whole file, then check if it is anywhere in your nameList and then decide if you write or not.

    For checking you should use a set() - checking for "is in" is way faster then with a list.

    already_in_file = set()
    with open('ATTLOG.csv', "r") as g:       # just read
        for line in g:
            already_in_file.add(line.split(",")[0])
    
    # process your current entry:
    if name not in already_in_file:
        with open('ATTLOG.csv', "a") as g:   # append
            now = datetime.now()
            dtString = now.strftime('%H:%M:%S')
            g.writelines(f'\n{name},{dtString}')