[英]Python Globbing a directory of images
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.我目前正在做一个项目,到目前为止,我已经生成了一个图像文件夹(png 格式),我需要在其中迭代每个图像并使用 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 requires a filepath for the image to be loaded and thus further used PIL 需要一个文件路径来加载图像并因此进一步使用
filename = input("file path:")
image = Image.open(filename)
callimage = image.load()
How can I convert the strings from the glob.glob list and have it used as an argument for the Image.open method?如何转换 glob.glob 列表中的字符串并将其用作 Image.open 方法的参数?
Thanks for your feedback!感谢您的反馈意见!
I am on python 3.6.1 if that holds any relevance.如果有任何相关性,我在 python 3.6.1 上。
Solution with os
package:使用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()
# ...
Solution using glob
:使用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()
# ...
Use the pathlib
library instead of glob.glob()
so that you don't have to worry about building the file's path.使用pathlib
库而不是glob.glob()
,这样您就不必担心构建文件的路径。 The Image.open()
method also takes a pathlib.Path
object as the first argument. Image.open()
方法还将pathlib.Path
对象作为第一个参数。
from pathlib import Path
frames = Path('path_to_folder')
for file in frames.glob('*.png'):
callimage = Image.open(file).load()
The builtin map()<\/code> is a general way to do something, in this case
load<\/code> , for a list of things:
内置
map()<\/code>是做某事的一般方法,在本例中为
load<\/code> ,用于列表:
map( func, [a, b, c ...] )<\/code> is roughly
map( func, [a, b, c ...] )<\/code>大致是
[func(a), func(b), func(c) ...]<\/code> .
[func(a), func(b), func(c) ...]<\/code> 。
So所以
def loadit( png ):
return Image.open( png ).load()
images = map( loadit, glob( "*.png" ))
for image in images: ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.