Search code examples
pythonlistloopsglobface-recognition

How can I Dynamically call Known Faces names with face_recognition


I am using face_recognition as fr package in python. I am loading images from a folder using glob package.

all_images = glob.glob('images/*.jpg')

And here I am cutting it short to names only rather than the whole path.

for_images = ""

for images in all_images:
    images = images[7:-4]
    images = f'''"{images}",
'''
    for_images += images


for_images = for_images[:-2]
print(for_images)

Here I am loading images one by one with face_recogniton package as fr:

image           = fr.load_image_file("images/Asad.jpg")
face_encoding   = fr.face_encodings(image)[0]

asad_image = fr.load_image_file("images/Farhan.jpg")
asad_face_encoding = fr.face_encodings(asad_image)[0]

image_r           = fr.load_image_file("images/Kashif.jpg")
face_encoding_r   = fr.face_encodings(image_r)[0]

k_image = fr.load_image_file("images/Rameez.jpg")
k_face_encoding = fr.face_encodings(k_image)[0]

r_image           = fr.load_image_file("images/Rizwan.jpg")
r_face_encoding   = fr.face_encodings(r_image)[0]

# Create arrays of known face encodings and their names
known_face_encodings = [
    face_encoding,
    asad_face_encoding,
    face_encoding_r,
    k_face_encoding,
    r_face_encoding
]

I was giving them hard coded names like this:

known_face_names = [
    "Asad",
    "Farhan",
    "Kashif",
    "Rameez",
    "Rizwan"
]

But now I am passing it dynamically:

known_face_names = [
    for_images
]

but it is not working as before, what actually I am doing wrong here, please give me the correct answer please.


Solution

  • Where you are cutting it short to only the precise name of the file rather than whole path, You should do like this:

    for_names = ""
    
    for names in all_images:
        names = names[7:-4]
        names = f'{names},'
        for_names += names
    
    for_names = for_names.split(',')
    

    And since it is now the list item, and when it is dynamically defining to known_face_names, it should be done like this:

    known_face_names = for_names