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

在Jupyter Notebook中运行目标检测模型推理后如何批量导出所有结果图片

问题原因

你当前保存图片的路径写为固定的/home/desired_folder/*.jpg,路径中的通配符*不会自动识别替换为原始图片名,程序会将所有推理后的图片都保存为同名为*.jpg的文件,每次循环都会覆盖上一次保存的内容,最终只会保留最后一张图片的处理结果。

解决方法

  1. 首先提前创建目标保存目录,避免目录不存在导致的报错
  2. 循环中提取每张原始图片的文件名,拼接成唯一的目标保存路径,避免覆盖

修改后的代码示例

import os
# 先创建目标保存目录
save_dir = '/home/desired_folder/'
os.makedirs(save_dir, exist_ok=True)

for image_path in glob.glob('/home/test_images/*.jpg'):
  image_np = load_image_into_numpy_array(image_path)
  output_dict = run_inference_for_single_image(model, image_np)
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks_reframed', None),
      use_normalized_coordinates=True,
      line_thickness=8)
  display(Image.fromarray(image_np))
  # 提取原始文件名,拼接保存路径
  img_name = os.path.basename(image_path)
  save_path = os.path.join(save_dir, img_name)
  Image.fromarray(image_np).save(save_path)

如果需要给处理后的图片加标记和原图做区分,也可以在文件名里加前缀:

save_path = os.path.join(save_dir, f"detected_{img_name}")

注意事项

如果运行时报写入权限错误,可检查/home/desired_folder/的目录权限,或者修改为当前用户有权限写入的目录即可。

内容的提问来源于stack exchange,提问作者junzz_52

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:18:01