我目前正在开发一个项目,到目前为止我已经生成了一个图像文件夹(png 格式),我需要在其中迭代每个图像并使用 PIL 对其进行一些操作。
我通过手动将文件路径链接到脚本中来使操作正常工作。 为了迭代每个图像,我尝试使用以下内容
frames = glob.glob("*.png")
但这会产生一个字符串形式的文件名列表。
PIL 需要一个文件路径来加载图像并进一步使用
filename = input("file path:")
image = Image.open(filename)
callimage = image.load()
如何转换 glob.glob 列表中的字符串并将其用作 Image.open 方法的参数?
感谢您的反馈!
如果这有任何相关性的话,我正在使用 python 3.6.1。
最佳答案
使用os
包的解决方案:
import os
source_path = "my_path"
image_files = [os.path.join(base_path, f) for f in files for base_path, _, files in os.walk(source_path) if f.endswith(".png")]
for filepath in image_files:
callimage = Image.open(filepath).load()
# ...
使用glob
的解决方案:
import glob
source_path = "my_path"
image_files = [source_path + '/' + f for f in glob.glob('*.png')]
for filepath in image_files:
callimage = Image.open(filepath).load()
# ...
关于Python 全局图像目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51434091/