python - 绘制文件夹中的每个图像
问题描述
我正在尝试将文件夹中的每张图像连同它们的文件名一起绘制为标题,但我似乎做不到。
我试过这段代码,但文件名都是一样的(由于迭代问题,它们是列表中最终图像的所有名称)。
# 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
解决方案
目前,您使用固定变量作为文件名。虽然您未能提供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
推荐阅读
- python - Python HTTP 服务器模块目录位置 psycopg2
- c# - 如何在C#中获取下一个特定日期的日期
- excel - 通过 Excel VBA 在 Powerpoint 中删除形状
- c# - 如何为 C# 类分配内存?
- python - 如何在调整窗口大小时使按钮移动?(PyQt4)
- python - 如何使用张量板监控 keras 中的梯度消失和爆炸?
- html - 封面视频背景无法正常工作
- python - 使用 re.sub 时,Python 正则表达式会忽略标点符号
- javascript - javascript中的水果忍者类型游戏
- unit-testing - 无法在 Groovy 测试中设置只读属性