Python globbing图片目录 [英] Python Globbing a directory of images

查看:51
本文介绍了Python globbing图片目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在一个项目上,到目前为止,我已经生成了一个图像文件夹(png格式),在其中需要遍历每个图像并使用PIL对它进行一些操作.

I am working on a project currently and so far I have generated a folder of images (png format) where I need to iterate through each image and do some operation on it using PIL.

通过手动将文件路径链接到脚本中,我可以正确执行该操作.要遍历我尝试使用以下内容的每张图片

I have the operation correctly working by manually linking the file path into the script. To iterate through each image I tried using the following

frames = glob.glob("*.png")

但是这会产生一个字符串形式的文件名列表.

But this yields a list of the filenames as strings.

PIL要求文件路径用于加载图像并因此进一步使用

PIL requires a filepath for the image to be loaded and thus further used

filename = input("file path:")
image = Image.open(filename)
callimage = image.load()

如何转换glob.glob列表中的字符串并将其用作Image.open方法的参数?

How can I convert the strings from the glob.glob list and have it used as an argument for the Image.open method?

感谢您的反馈!

我在python 3.6.1上是否具有任何相关性.

I am on python 3.6.1 if that holds any relevance.

推荐答案

使用 os 软件包的解决方案:

Solution with os package:

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 globbing图片目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆