Home » Python » python – randomly select images using PIL-Exceptionshub

python – randomly select images using PIL-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a folder with over 100k images, I am wondering how do I use PIL to randomly select 5 images to display?

The code below will return me all codes which is not feasible though.

from PIL import Image

path = '/Users/Desktop/folder'
image_list = []
for x in (path): 
    im = Image.open(image_filename)
    image_list.append(im)
images = np.array(images)

Thanks

How to&Answers:

Assuming that your path only consists of only image files, in this case we can randomly select five different image files in a given directory and then open each of the image file using PIL.Image thereby appending them to the image_list.
Here is the code snippet which you might want to try,

import os
import random
from PIL import Image

path = '/Users/Desktop/folder'
image_list = []

names = random.choices(os.listdir(path), k=5) #----> Randomly select 5 images
for filename in names: 
    full_path = os.path.join(path, filename)
    if os.path.isfile(full_path):
        img = Image.open(full_path)
        image_list.append(img)

Hope this helps!

Answer:

You don’t show a minimal example.

If image_list is all of your picture list,
then this maybe could solve your problem:

import random

RandomIndexList = [random.randint(0,range(len(image_list))) for i in range(5)] # 5 is the number of picture.
for i in RandomIndexList:
    image_list[i].show()