【问题标题】:Plotting every image from a folder绘制文件夹中的每个图像
【发布时间】:2019-05-03 13:51:28
【问题描述】:

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

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

# 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

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    目前您使用固定变量作为文件名。虽然您未能提供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
    

    【讨论】:

    • 非常感谢,这行得通。不清楚是我的错。我希望它显示文件夹中图像的实际文件名。
    • @MichaelManfield:你必须向我解释filename[:-4] 中包含的内容。它是否包含您要显示的文件名?如果你解释不好,就很难提供帮助。 filename[:-4] 的长度是否等于 len(images) 的长度?
    • 对不起。是的,你是对的,filename[:-4] 是文件名(缩短为前 4 个字符)。我在想也许可以创建一个以图像为值、文件名为键的字典......这会更容易吗?
    • @MichaelManfield: len(images) 是否等于您目录中的文件数?
    猜你喜欢
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多