您可以使用Python的PIL库(Pillow)来遍历图片文件夹,并将每个图片存储为列表项。以下是一个示例代码:
from PIL import Image
import os
def create_image_list(folder):
image_list = []
for filename in os.listdir(folder):
if filename.endswith(".jpg") or filename.endswith(".png"):
image_path = os.path.join(folder, filename)
try:
image = Image.open(image_path)
image_list.append(image)
except IOError:
print("Error opening image: " + image_path)
return image_list
# 调用函数来遍历图片文件夹并存储为列表项
image_folder = "path/to/your/image/folder"
images = create_image_list(image_folder)
# 打印列表项
for image in images:
print(image)
在上述代码中,您需要将"path/to/your/image/folder"
替换为您实际的图片文件夹路径。代码首先定义了一个create_image_list
函数,该函数接受一个文件夹路径作为参数,并返回一个包含图片列表项的列表。然后,使用os.listdir
遍历文件夹中的每个文件名,判断文件扩展名是否为.jpg
或.png
,如果是,则使用Image.open
打开图片,并将其添加到image_list
列表中。最后,通过循环遍历images
列表,打印每个图片对象。