简体   繁体   中英

how to import images by using Pil library in python?

Hope you all are good. I'm facing this problem while importing images from a directory inside my project directory. I don't what's the problem. I did this while putting the images in the main directory. It's worked perfectly fine but I want to now import images from my folder images. Here is the screenshot. I hope you all can understand what i'm trying to do The only problem is in that "if items.endswith("images.jpg") .

Try this:

for items in os.listdir('images'):
    if items.endswith('.jpg'):
        image = Image.open(f'images/{items}')

Explanation:
os.listdir returns the files inside the directory which doesn't include the full path. ie. images/images.jpg .
So when using PIL you should add the master path at the beginning.

I can see there are two main problems, the first one is that you are checking the file extension with endswith('images/.jpg') , this should be endswith('.jpg') , the second one is that you are using os.listdir , which returns a list with the file names in the folder and not the full path, that means that you are trying to load the image from im_name.jpg and not images/im_name.jpg .

The solution to both of these problems would be to use the glob package, which lets you search for all files matching an extension, and returns the full path for each file. For example:

import glob

print(glob.glob('images/*.jpg'))

should print:

images/image1.jpg
images/image2.jpg
...

And these are enough to load them using PIL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM