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

如何从每个文件夹中绘制子图?附图片路径遍历代码示例

多文件夹图片子图绘制实现方案

先把遍历到的有效图片路径收集起来,再用matplotlib实现子图绘制,具体代码和步骤如下:

1. 导入依赖库并收集图片路径

先将所有存在的图片路径存入列表,避免因路径无效报错:

import os
import matplotlib.pyplot as plt
from PIL import Image

# 替换为你的实际训练集目录路径
train_dir = "Fish/train"
folder_list = os.listdir(train_dir)
img_paths = []

for folder in folder_list:
    img_path = os.path.join(train_dir, folder, "00001.png")
    if os.path.exists(img_path):
        img_paths.append(img_path)

2. 绘制3×3子图布局

你有9张图片,刚好适配3行3列的布局,代码如下:

# 设置子图行列数
rows, cols = 3, 3
# 创建画布,figsize可根据需求调整尺寸
fig, axes = plt.subplots(rows, cols, figsize=(12, 10))

# 遍历图片路径和对应子图位置
for idx, img_path in enumerate(img_paths):
    # 用PIL读取图片
    img = Image.open(img_path)
    # 计算当前子图的行、列索引
    row_idx = idx // cols
    col_idx = idx % cols
    # 在对应子图上显示图片
    axes[row_idx, col_idx].imshow(img)
    # 设置子图标题为对应文件夹名称
    folder_name = os.path.basename(os.path.dirname(img_path))
    axes[row_idx, col_idx].set_title(folder_name)
    # 隐藏坐标轴,让画面更整洁
    axes[row_idx, col_idx].axis('off')

# 自动调整子图间距,避免标题与图片重叠
plt.tight_layout()
# 显示最终子图
plt.show()

可选:OpenCV读取图片的适配方案

如果习惯用OpenCV读取图片,需要转换颜色通道(OpenCV默认BGR格式,matplotlib需RGB格式):

import cv2

# 替换上述代码中读取图片的部分
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:30:12