This is the code I have and it works for single images:
Loading images and apply the encoding
JavaScript
x
7
1
from face_recognition.face_recognition_cli import image_files_in_folder
2
3
Image1 = face_recognition.load_image_file("Folder/Image1.jpg")
4
Image_encoding1 = face_recognition.face_encodings(Image1)
5
Image2 = face_recognition.load_image_file("Folder/Image2.jpg")
6
Image_encoding2 = face_recognition.face_encodings(Image2)
7
Face encodings are stored in the first array, after column_stack we have to resize
JavaScript
1
4
1
Encodings_For_File = np.column_stack(([Image_encoding1[0]],
2
[Image_encoding2[0]]))
3
Encodings_For_File.resize((2, 128))
4
Convert array to pandas dataframe and write to csv
JavaScript
1
3
1
Encodings_For_File_Panda = pd.DataFrame(Encodings_For_File)
2
Encodings_For_File_Panda.to_csv("Celebrity_Face_Encoding.csv")
3
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
JavaScript
1
12
12
1
import os
2
from face_recognition.face_recognition_cli import image_files_in_folder
3
my_dir = 'folder/path/' # Folder where all your image files reside. Ensure it ends with '/
4
encoding_for_file = [] # Create an empty list for saving encoded files
5
for i in os.listdir(my_dir): # Loop over the folder to list individual files
6
image = my_dir + i
7
image = face_recognition.load_image_file(image) # Run your load command
8
image_encoding = face_recognition.face_encodings(image) # Run your encoding command
9
encoding_for_file.append(image_encoding[0]) # Append the results to encoding_for_file list
10
11
encoding_for_file.resize((2, 128)) # Resize using your command
12
You can then convert to pandas and export to csv. Let me know how it goes