简体   繁体   English

Python PIL从特定文件打开图像

[英]Python PIL open image from specific file

I'm getting to grips with the Pillow library from Python. 我正在使用Python的Pillow库。 I have a folder (folder 1) where the code is stored and within that folder another folder (folder 2) where all the pictures I would like to edit/manipulate are. 我有一个存储代码的文件夹(文件夹1),在该文件夹中还有另一个文件夹(文件夹2),我要编辑/处理的所有图片都在其中。

However, I have only been able to access the images when they are saved in folder 1, but not when they are only saved in folder 2. 但是,我只能在将图像保存在文件夹1中时访问它们,而不能仅在将它们保存在文件夹2中时访问它们。

I have used the code: 我使用了代码:

from PIL import Image
import os

for k in os.listdir('.'):
    if k.endswith('.jpg'):
        i = Image.open(k)
        kn, kext = os.path.splitext(k)
        print(kn)

Which prints the names of all the file names minus the '.jpg' extension: 它将显示所有文件名的名称减去“ .jpg”扩展名:

MeisJeMetDeParel
StarryNight
TheSonOfMan

I have then tried to do the same, only accessing the images from inside their own specific folder: 然后,我试图做同样的事情,只从它们自己的特定文件夹中访问图像:

for k in os.listdir('testPictures'):
    if k.endswith('.jpg'):
        i = Image.open(k)
        kn, kext = os.path.splitext(k)
        print(kn)

by changing the directory to the name of the folder they are stored in (testPictures). 通过将目录更改为它们存储在其中的文件夹的名称(testPictures)。 However, I get the error: 但是,我得到了错误:

FileNotFoundError: [Errno 2] No such file or directory: 'MeisJeMetDeParel.jpg'

So it seems that the image within the folder is being accessed, as it has been able to identify the name of the first image in the folder, yet the code is unable to print the names of the images as it was able to do so when both the code and the images were saved together. 因此,似乎已在访问该文件夹中的图像,因为它能够识别该文件夹中的第一个图像的名称,但是代码无法打印图像的名称,因为它可以在以下情况下进行打印:代码和图像都保存在一起。 What adjustments can I make to my code so that the pictures in the testPictures folder can be printed? 我可以对代码进行哪些调整,以便可以打印testPictures文件夹中的图片? Thanks 谢谢

The os.listdir function returns a path relative to the directory you specified so you have to os.path.join the directory to the name you got: os.listdir函数返回相对于您指定目录的路径,因此您必须将目录os.path.join加入您得到的名称中:

for k in os.listdir('testPictures'):
    if k.endswith('.jpg'):
        i = Image.open(os.path.join('testPictures', k))
        kn, kext = os.path.splitext(k)
        print(kn)

I might suggest that instead of calling os.listdir and checking the extension manually you could use the glob module instead and also avoid having to os.path.join the directory name: 我可能建议您代替使用os.listdir并手动检查扩展名,而可以使用glob模块,并且还避免os.path.join目录名称:

import glob
for k in glob.glob('testPictures/*.jpg'):
    i = Image.open(k)
    kn, kext = os.path.splitext(k)
    print(kn)

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

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