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.
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
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?
Thanks for your feedback!
I am on python 3.6.1 if that holds any relevance.
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()
# ...
Solution using 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()
# ...