1

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?

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
DataBach
  • 1,330
  • 2
  • 16
  • 31
  • Are you asking how to write a for loop, or how to find all JPG files in a folder, or ...? Please show what you have tried and explain in what way it didn't work as expected, then someone might be able to help you. – mkrieger1 Jun 04 '18 at 11:57

1 Answers1

0

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

Sagar Dawda
  • 1,126
  • 9
  • 17
  • Hi Sagar, thank you for your help! I still have an error. It seems like I can open the folder, but then it still won't read my images. This is the error: FileNotFoundError: [Errno 2] No such file or directory: 'BrigitteBardot1-Copy1.jpg' I changed line 5 to the following: for i in os.listdir('Folder'): – DataBach Jun 08 '18 at 14:46
  • Hi Horbaje, thanks for pointing out that mistake on line 5. I think you need an absolute path for reading the file. So I've added another line of code for that. All the changes have been made in the above solution. Let me know if it works. – Sagar Dawda Jun 11 '18 at 07:00