Skip to content
Advertisement

How do I get the face_recognition encoding from many images in a directory and store them in a CSV File?

This is the code I have and it works for single images:

Loading images and apply the encoding

from face_recognition.face_recognition_cli import image_files_in_folder

Image1 = face_recognition.load_image_file("Folder/Image1.jpg")
Image_encoding1 = face_recognition.face_encodings(Image1)
Image2 = face_recognition.load_image_file("Folder/Image2.jpg")
Image_encoding2 = face_recognition.face_encodings(Image2)

Face encodings are stored in the first array, after column_stack we have to resize

Encodings_For_File = np.column_stack(([Image_encoding1[0]], 
[Image_encoding2[0]]))
Encodings_For_File.resize((2, 128))

Convert array to pandas dataframe and write to csv

Encodings_For_File_Panda = pd.DataFrame(Encodings_For_File)
Encodings_For_File_Panda.to_csv("Celebrity_Face_Encoding.csv")

How do I loop over the images in ‘Folder’ and extract the encoding into a csv file? I have to do this with many images and cannot do it manually. I tried several approaches, but none a working for me. Cv2 can be used instead of load_image_file?

Advertisement

Answer

Try this

Note: I am assuming you dont need to specify folder path before file name in your command. This code will show you how to iterate over the directory to list files and process them

import os
from face_recognition.face_recognition_cli import image_files_in_folder
my_dir = 'folder/path/' # Folder where all your image files reside. Ensure it ends with '/
encoding_for_file = [] # Create an empty list for saving encoded files
for i in os.listdir(my_dir): # Loop over the folder to list individual files
    image = my_dir + i
    image = face_recognition.load_image_file(image) # Run your load command
    image_encoding = face_recognition.face_encodings(image) # Run your encoding command
    encoding_for_file.append(image_encoding[0]) # Append the results to encoding_for_file list

encoding_for_file.resize((2, 128)) # Resize using your command

You can then convert to pandas and export to csv. Let me know how it goes

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement