vendredi 20 août 2021

FileNotFoundError - Trouble opening an image from WindowsPath object

Iterating through this list and reading/opening the images gives no error,you can see that each item (index 0) in the tuple is a WindowsPath object of pathlib module. So, this works: Working

Iterating through this list does not work and the image is unable to be found, and you can see that each item(index 0) in the list is a WindowsPath that points to the WindowsPath object of pathlib module. I'd love to get this list to be the same as the list in the above image: Not Working

To me, it looks like it's trying to open a non-existent file called "[WindowsPath('dir1/img1.png')]" instead of the existing file called "dir1/img1.png". Which seems to stem from calling function random_list() and then appending the output of that function to a list.

See below code:

def random_list():
    #set empty list
    combo = []
    #mapping images to probabilities
    for d, p in zip(layers, probabilities):
        #random choice of image given the probability
        ch = choices(d, p)
        #add image path to list
        combo.append(ch)
    #return list in order to add more images, total of 7 loops
    return combo
           
'''
Main method
'''
#makes a list of all .png images in the given directories
layers = [list(Path(directory).glob("*.png")) for directory in ("dir1/", "dir2/", "dir3/", "dir4/", "dir5/", "dir6/", "dir7/")]

#list of probabilities for each image
probabilities =
                [ [0.17, 0.11, 0.15, 0.085, 0.05, 0.235, 0.2],
                 [0.075, 0.6, 0.3, 0.025],
                 [0.075, 0.3, 0.6, 0.025],
                 [0.3, 0.075, 0.6, 0.025],
                 [0.55, 0.35, 0.1],
                 [0.1, 0.55, 0.35],
                 [0.1, 0.35, 0.55] ]

#setting empty list
combinations = []
 
#while combinations is less than 1,111 items:
while len(combinations) < 1111:
    #get random list of traits
    a = random_list()
    #add to list if unique
    if a not in combinations:
        combinations.append(a)


#calling iterative function which layers images from directories and saves them
generate(layers)

ERROR:

 File "E:\myDir\subDir\imageGeneratorTest.py", line 22, in generate
        layer = Image.open(str(path), "r")
    
      File "C:\Program Files\pkgs\PIL\Image.py", line 2968, in open
        fp = builtins.open(filename, "rb")
    
    FileNotFoundError: [Errno 2] No such file or directory: "[WindowsPath('dir1/img1.png')]"



Aucun commentaire:

Enregistrer un commentaire