Python 全局图像目录

标签 python glob pathlib

我目前正在开发一个项目,到目前为止我已经生成了一个图像文件夹(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/

相关文章:

python - 为目录中的每个文件运行 pytest

python - 将 WindowsPath 转换为 PosixPath

python - Pandas 数据框创建不返回

regex - 通配符的行为是否有所不同?

python - 查找列表中包含字符串的元素的索引

bash - 为什么 zsh 会尝试扩展 * 而 bash 不会?

python - 如何使用Python检查是否存在具有不同扩展名的同名文件

python - Pathlib 'normalizes' 带有 "$"的 UNC 路径

python - 使用PythonKit快速调用Python

python - 在 Python 中将列表初始化为已知数量的元素