简体   繁体   English

如何使用 python 中的 Pil 库导入图像?

[英]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") .我希望你们都能理解我在做什么唯一的问题是 "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. os.listdir返回目录中不包含完整路径的文件。 ie. IE。 images/images.jpg . images/images.jpg
So when using PIL you should add the master path at the beginning.因此,在使用PIL时,您应该在开头添加主路径。

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 .我可以看到有两个主要问题,第一个是您正在检查文件扩展名endswith('images/.jpg') ,这应该是endswith('.jpg') ,第二个是您正在使用os.listdir ,它返回一个包含文件夹中文件名而不是完整路径的列表,这意味着您正在尝试从im_name.jpg而不是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.这两个问题的解决方案是使用glob package,它允许您搜索与扩展名匹配的所有文件,并返回每个文件的完整路径。 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.这些足以使用 PIL 加载它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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