0

I have a list containing 10000 images. I want to show the 1st 10 images. How do I write the for loop in Python ?

from PIL import Image
import glob
image_list = []
for filename in glob.glob('<my_directory>*.pgm'):
    im=Image.open(filename)
    image_list.append(im)


import matplotlib.pyplot as plt

for i in range(10):
    plt.figure()
    plt.imshow(image_list[i])

That's my code. I have tried image_list(3), image_list(1:3) but it all doesn't work.

halfer
  • 19,824
  • 17
  • 99
  • 186
Kong
  • 2,202
  • 8
  • 28
  • 56

2 Answers2

0

Slice the list

for ima in image_list[:10]:
    plt.figure()
    plt.imshow(ima)
Neo
  • 3,534
  • 2
  • 20
  • 32
0

I guess you are trying to show the first 10 images sorted by its name. If so try as below:

for ima in sorted(image_list)[:10]:
    plt.figure()
    plt.imshow(ima)

Sample Result:

>>> image_list = ['img1.jpg', 'img2.jpg', 'img0.jpg']
>>> image_list
['img1.jpg', 'img2.jpg', 'img0.jpg']
>>> sorted(image_list)
['img0.jpg', 'img1.jpg', 'img2.jpg']
>>> for img in sorted(image_list)[:1]:
...  print img
...
img0.jpg
Swadhikar
  • 2,152
  • 1
  • 19
  • 32