如何从目录中的许多图像中获取 face_recognition 编码并将它们存储在 CSV 文件中?

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

这是我的代码,适用于单张图片:

正在加载图像并应用编码

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)

面部编码存储在第一个数组中,在column_stack之后我们必须调整大小

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

将数组转换为 pandas 数据帧并写入 csv

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

如何遍历 'Folder' 中的图像并将编码提取到 csv 文件中?我必须对许多图像执行此操作并且不能手动执行。我尝试了几种方法,但 none 对我有用。可以使用 Cv2 代替 load_image_file?

试试这个

注意:我假设您不需要在命令中的文件名之前指定文件夹路径。此代码将向您展示如何遍历目录以列出文件并处理它们

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

然后您可以转换为 pandas 并导出为 csv。让我知道进展如何