如何从 python 中的循环外部访问循环中的多个图像对象?

How to access multiple image objects in a loop, from outside of the loop in python?

from PIl import Image, ImageFilter
import os

img_path = "some_location"

for image in os.listdir(img_path):
    img = Image.open(image)
    new_img = img.filter(ImageFilter.BLUR)

在for循环中有很多new_img的实例。有没有办法临时保存它们或从内存中使用它们来迭代另一个循环。我不想将它们保存在存储中。

只需将它们添加到列表中即可。类似于:

images = []
for image in os.listdir(img_path):
    img = Image.open(image)
    new_img = img.filter(ImageFilter.BLUR)
    images.append(new_img)

for new_img in images:
    # Loop over and use them here

您还可以将第一个循环设为推导式:

images = [Image.open(image).filter(ImageFilter.BLUR)
          for image in os.listdir(img_path)]

虽然第一行有点吵。


如果您不想一次将所有 images 存入内存,您可以使用生成器进行惰性处理。我会使用生成器函数:

def produced_images():
    for image in os.listdir(img_path):
        img = Image.open(image)
        yield img.filter(ImageFilter.BLUR)  # yield images as they're needed

for new_img in produced_images():
    # Use here

或者,只是一个生成器表达式:

images = (Image.open(image).filter(ImageFilter.BLUR)
          for image in os.listdir(img_path))

for new_img in images:
    # Use here