Python Matplotlib显示每个文件夹中的第一个{n}图像

Python Matplotlib显示每个文件夹中的第一个{n}图像,python,matplotlib,Python,Matplotlib,我有一个主文件夹,主文件夹下有3个子文件夹。我想把每个子文件夹中的前几个图像打印在一个单独的绘图中。我该怎么做 到目前为止,我能够分别执行这两项任务: 打印每个文件夹中的前5个图像 directory=os.listdir('main_folder') for each in directory: currentFolder = 'main_folder/' + each for file in os.listdir(currentFolder)[0:5]: fu

我有一个主文件夹,主文件夹下有3个子文件夹。我想把每个子文件夹中的前几个图像打印在一个单独的绘图中。我该怎么做

到目前为止,我能够分别执行这两项任务:

  • 打印每个文件夹中的前5个图像

    directory=os.listdir('main_folder')
    for each in directory:
        currentFolder = 'main_folder/' + each
        for file in os.listdir(currentFolder)[0:5]:
            fullpath = main_folder+ "/" + file
            print(fullpath)
            img=mpimg.imread(fullpath)
            plt.imshow(img)
            #this seems to be plotting the last image
    
  • 在一个图上绘制多个子图

    for i in range(1, 7):
        plt.subplot(2, 3, i)
    

  • 如何将两者结合起来,以便绘制每个文件夹中的前几个图像?

    您可以使用
    枚举
    将第二部分直接集成到循环中

    directory=os.listdir('main_folder')
    for each in directory:
        plt.figure()
        currentFolder = 'main_folder/' + each
        for i, file in enumerate(os.listdir(currentFolder)[0:5]):
            fullpath = main_folder+ "/" + file
            print(fullpath)
            img=mpimg.imread(fullpath)
            plt.subplot(2, 3, i)
            plt.imshow(img)
    

    非常感谢。这张照片似乎更进一步了——它正在绘制最后一个子文件夹中的前5张图像。我怎样才能从每个子文件夹中绘制5幅图像,而不仅仅是最后一个子文件夹?我更新了答案。这将给出3个数字,每个数字有5个子图。这就是你的意思吗?太好了。那很有魅力!仅供参考,“fullpath=main_folder+”/“+file”应为“fullpath=currentFolder+”/“+file”。非常感谢你的帮助!