首页 > 解决方案 > 绘制文件夹中的每个图像

问题描述

我正在尝试将文件夹中的每张图像连同它们的文件名一起绘制为标题,但我似乎做不到。

我试过这段代码,但文件名都是一样的(由于迭代问题,它们是列表中最终图像的所有名称)。

# Put all images in the folder into a list (works)
images = []
for f in glob.iglob("/content/testing_data/Bad/*"):
    images.append(np.asarray(Image.open(f)))

# plot the images (works)
images = np.array(images)
fig, axs = plt.subplots(15, 5, figsize=(10, 50))
fig.subplots_adjust(hspace = .3, wspace=.3)
axs = axs.ravel()

# This is for displaying the names (works)
for filename in os.listdir('/content/testing_data/Bad/'):
  RatName = filename[:-4]

# show the filename (this bit doesn't work)
for i in range(len(images)):
  axs[i].imshow(images[i])
  axs[i].set_title(RatName)

我希望它将图像绘制为以文件名作为标题的子图...

文件名 1、文件名 2、文件名 3

但我明白了:

文件名 3,文件名 3,文件名 3

标签: pythonpython-3.xmatplotlib

解决方案


目前,您使用固定变量作为文件名。虽然您未能提供MCVE,但我相信这应该适合您。这个想法是使用索引i来动态设置文件名。i+1使用是因为在 python 中,range(len(images))默认会生成从 0 开始的数字

for i in range(len(images)):
  axs[i].imshow(images[i])
  axs[i].set_title('filename%s' %(i+1))

编辑尝试以下

i = 0
for filename in os.listdir('/content/testing_data/Bad/'):
  RatName = filename[:-4]
  axs[i].imshow(images[i])
  axs[i].set_title(RatName)
  i += 1

推荐阅读