简体   繁体   English

使用for循环在PIL上打开多个图像

[英]Opening multiple images on PIL with a for loop

I have to open a couple of images with PIL. 我必须使用PIL打开几个图像。 Right now, i only have 3 images, so I've been doing opening them like so, not within a for-loop: 现在,我只有3张图片,所以我一直在像这样打开它们,而不是在for循环中:

self.redpic = Image.open("red.png")
self.redpic = self.redpic.resize((100,100), Image.ANTIALIAS)
self.img1 = ImageTk.PhotoImage(self.redpic)

But in the future, I will be opening at least 20 images, so I tried a for-loop implementation: 但是将来,我将至少打开20张图像,因此我尝试了for循环实现:

def process_image(self):
    for valx in range(5):
        self.numbering = "image" + str(valx);
        self.numbpng = numbering + ".png";
        self.numbering = Image.open(numbpng);
        self.numbering = self.numbering.resize((100,100), Image.ANTIALIAS)
        self.numbering= ImageTk.PhotoImage(self.numbering)

But with this, I do not get access to the images that I just created. 但是,与此同时,我无法访问我刚刚创建的图像。 I've been reading about dynamically creating variables and how it is not recommended, so I was wondering what would be the best way for me to get access to self.imagex where x is an number to an image. 我一直在阅读有关动态创建变量的方法以及不建议使用的方法,因此我想知道什么是最好的方式来访问self.imagex ,其中x是图像的数字。 I know the number of images ahead of time. 我知道图像的数量提前。

One common way to avoid dynamically creating variables is to store the items in a some sort of variably-sized container, like a tuple , list , dict , etc. 避免动态创建变量的一种常见方法是将项目存储在某种大小可变的容器中,例如tuplelistdict等。

Below is an example of storing them in an class instance attribute which is a list and is named self.images : 下面是将它们存储在类实例属性中的示例,该类实例属性是一个list ,名为self.images

from PIL import Image, ImageTk

class Class:
    def process_images(self, num_images):
        self.images = []
        for i in range(num_images):
            image_filename = "image%s.png" % i
            number_img = Image.open(image_filename).resize((100, 100), Image.ANTIALIAS)
            number_img = ImageTk.PhotoImage(number_img)
            self.images.append(number_img)

c = Class()
c.process_images(5)

After calling the method, you can reference individual images like this: 调用该方法后,您可以像这样引用单个图像:

c.images[2]  # Third image.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM