Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over a list of images and assign them as variables in python

I am trying to write a function that iterates over a list of images in python so that they are accessible for Pillow image processing.

ImTestA = Image.open("A.png")
ImTestB = Image.open("B.png")
ImTestC = Image.open("C.png")
ImTest1 = Image.open("1.png")
ImTest2 = Image.open("2.png")
ImTest3 = Image.open("3.png")
ImTest4 = Image.open("4.png")
ImTest5 = Image.open("5.png")
ImTest6 = Image.open("6.png")

I currently have the above but am trying to refactor it into something I can assign different length to (use a list with A-K or J-Z).

from PIL import Image

AtoC = ["A.png", "B.png", "C.png"]

def OpenAns(quest):
    AtoCImages = []
    for image in quest:
        AtoCImages.append(Image.open(image))
        return AtoCImages

OpenAns(AtoC)

ImTestA = AtoCImages[0]
ImTestB = AtoCImages[1]
ImTestC = AtoCImages[2]

Fixed earlier error, and went back to same problem as before. I am just trying to clean up my code and have it nice and DRY. Any help is appreciated.

Traceback (most recent call last):
  File "C:\ImageTest.py", line 13, in <module>
    ImTestA = AtoCImages[0]
NameError: name 'AtoCImages' is not defined

Maybe I will just have separate files with a list in each. If I cant shorten this up.

like image 432
Frank Castle Avatar asked Mar 15 '23 20:03

Frank Castle


1 Answers

Change:

for image in AtoC:
    AtoCIm = []
    AtoCIm.append(Image.open(image))

to

AtoCIm = []
for image in AtoC:
    AtoCIm.append(Image.open(image))

will do it.

You are creating a new list every iteration, rather than creating a list once and appending new items to it. Therefore, your list always has only 1 item. Attempting to get the 2nd item, AtoCIm[1], will raise exception.

like image 179
CT Zhu Avatar answered Mar 24 '23 04:03

CT Zhu