Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing images from a directory (Python) to list or dictionary [closed]

I am trying to import all the images inside a directory (the directory location is known).

path = /home/user/mydirectory 

I already know a way of finding out the length of the directory.

What I'm not sure about is how I can import the images (using PIL/Pillow) into either a list or a dictionary, so they can be properly manipulated.

like image 647
Charles Avatar asked Oct 15 '14 21:10

Charles


People also ask

How do I add an image to a list in Python?

The way to call it would be: x = room_list[random. randrange(len(room_list)) . Alternatively, and closer to your issue, you could use the choice function like so: x = random.


2 Answers

I'd start by using glob:

from PIL import Image import glob image_list = [] for filename in glob.glob('yourpath/*.gif'): #assuming gif     im=Image.open(filename)     image_list.append(im) 

then do what you need to do with your list of images (image_list).

like image 192
user1269942 Avatar answered Oct 09 '22 20:10

user1269942


from PIL import Image import os, os.path  imgs = [] path = "/home/tony/pictures" valid_images = [".jpg",".gif",".png",".tga"] for f in os.listdir(path):     ext = os.path.splitext(f)[1]     if ext.lower() not in valid_images:         continue     imgs.append(Image.open(os.path.join(path,f)))     
like image 44
Tony Suffolk 66 Avatar answered Oct 09 '22 20:10

Tony Suffolk 66