如何将DeepFace.find()识别的相似图片保存至新文件夹?
将DeepFace识别的相似图片保存到新文件夹
你可以通过以下步骤实现把识别出的相似图片复制到指定文件夹:
- 导入文件操作相关库
shutil和os,用于复制文件和创建文件夹 - 提前定义目标文件夹路径,若文件夹不存在则自动创建
- 获取DeepFace的识别结果后,遍历结果中的图片路径,逐一复制到目标文件夹
完整代码如下:
from deepface import DeepFace import shutil import os # 配置路径 test_img = "test.jpeg" face_db_path = "faces" target_dir = "similar_faces" # 确保目标文件夹存在 if not os.path.isdir(target_dir): os.makedirs(target_dir) # 执行人脸检索并获取结果 search_results = DeepFace.find( img_path=test_img, db_path=face_db_path, enforce_detection=False )[0] # 复制相似图片到目标文件夹 for _, record in search_results.iterrows(): source_img = record["identity"] img_filename = os.path.basename(source_img) shutil.copy2(source_img, os.path.join(target_dir, img_filename)) print(f"已保存: {img_filename}")
关键点说明
os.makedirs(target_dir):自动创建目标文件夹,避免因文件夹不存在导致复制失败search_results.iterrows():遍历DeepFace返回的DataFrame结果,逐行读取图片路径shutil.copy2():相比shutil.copy,会保留文件的元数据(如创建时间),更适合复制图片文件
如果你之前想导出CSV结果,只需在获取search_results后添加一行代码:
search_results.to_csv("face_search_results.csv", index=False)
内容的提问来源于stack exchange,提问作者eitan
相关产品推荐
相关产品推荐

