Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib display the first {n} images from each folder

I have one main folder, and there are 3 sub folders under the main folder. I want to plot the first few images from each sub folder in one single plot. How can I do that?

So far, I am able to perform the two tasks separately:

  1. Print the first 5 images from each folder

    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
    
  2. Plot several subplot on one plot

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

How can I combine the two, so I can plot the first few images from each folder?

like image 996
caramelslice Avatar asked Mar 17 '26 02:03

caramelslice


1 Answers

You may directly integrate the second part into the loop, using enumerate.

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)
like image 95
ImportanceOfBeingErnest Avatar answered Mar 24 '26 10:03

ImportanceOfBeingErnest