You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将DeepFace.find()识别的相似图片保存至新文件夹?

将DeepFace识别的相似图片保存到新文件夹

你可以通过以下步骤实现把识别出的相似图片复制到指定文件夹:

  1. 导入文件操作相关库shutil和os,用于复制文件和创建文件夹
  2. 提前定义目标文件夹路径,若文件夹不存在则自动创建
  3. 获取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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 14:22:47