Home Community Blog Buy Now

Misty Community Forum

Face Recognition Code

I wanted my face recognition code to add unrecognized faces on the frame to the directory after asking a user input question “Who is this?”. It crops out the area inside the rectangle drawn around faces and stores these images under a folder named from given user input.
So I coded for that and I got the requirement fulfilled.(Code 1)

I realized that the code had another problem:
It does not store unrecognized images of known faces. So, if the user input to the question “Who is this?” matches with the already existing folder names in the directory, It shows an error:

FileExistsError: [WinError 183] Cannot create a file when that file already exists: "Directory\\User_input"

Code 1: (The below code must be modified)

# check to see if we have found a match
        if True in matches:
            # Find positions at which we get True and store them
            matchedIdxs = [i for (i, b) in enumerate(matches) if b]
            counts = {}
            # loop over the matched indexes and maintain a count for
            # each recognized face face
            for i in matchedIdxs:
                #Check the names at respective indexes we stored in matchedIdxs
                name = data["names"][i]
                #increase count for the name we got
                counts[name] = counts.get(name, 0) + 1
            #set name which has highest count
            name = max(counts, key=counts.get)
        else: # To store the unknown new face with name
            new_name = input("Who is this?")
            path_2 = os.path.join('Images',new_name)
            print("Directory '% s' created" % new_name)
            for (x, y, w, h) in faces:
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0,0,255),
                thickness = 2)
                cv2.putText(frame, new_name, (x, y), cv2.FONT_HERSHEY_SIMPLEX,
                0.75, (0, 255, 0), 2)
                sub_face = frame[y:y+h, x:x+w]
                FaceFileName = new_name + str(y+x) + ".jpg"
            #if cv2.waitKey(1) & 0xFF == ord('q'):
            #    break

what is your question?