Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permission Error: Using Image.open

I am using PIL for Image.open

The following is my Image path:

loc = "./data/Flicker8k_reshaped"

When I try to open an image file in this path, with the following usage it opens an image.

Image.open(loc + "/" + train_filenames[0]) # Opens an image 
np.array(Image.open(loc + "/" + train_filenames[0])) # converts that into numpy array

train_filenames is the list which contains the file names of the images which I need to vectorize using numpy array.

But when I try to run it in a loop and list comprehension,

train = np.array([np.array(Image.open(loc+"/"+fname)) for fname in train_filenames])

I get the following error.

---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
<ipython-input-35-90eaea1b75ca> in <module>()
----> 1 train = np.array([np.array(Image.open(loc+"/"+fname)) for fname in train_filenames])
      2 test = np.array([np.array(Image.open(loc+"/"+fname)) for fname in test_filenames])
      3 val = np.array([np.array(Image.open(loc+"/"+fname)) for fname in val_filenames])
      4 
      5 print(train.shape)

<ipython-input-35-90eaea1b75ca> in <listcomp>(.0)
----> 1 train = np.array([np.array(Image.open(loc+"/"+fname)) for fname in train_filenames])
      2 test = np.array([np.array(Image.open(loc+"/"+fname)) for fname in test_filenames])
      3 val = np.array([np.array(Image.open(loc+"/"+fname)) for fname in val_filenames])
      4 
      5 print(train.shape)

C:\Anaconda\envs\tensorflow-cpu\lib\site-packages\PIL\Image.py in open(fp, mode)
   2541 
   2542     if filename:
-> 2543         fp = builtins.open(filename, "rb")
   2544         exclusive_fp = True
   2545 

Looks like

builtins.open(filename, "rb")

I picked some 5 filenames and saved it in a different list and ran the above statement and ran the code over the loop. It worked too. I think the " error message here is misleading. "

like image 789
Kathiravan Natarajan Avatar asked Apr 20 '18 08:04

Kathiravan Natarajan


1 Answers

It could just be that one of the file names in train_filenames is invalid (even though train_filenames[0] obviously is valid). Just for debugging purposes (you can put it back later once it's working), unpack the list comprehension you're using to open your images into a for loop and add a print statement:

images = []
for fname in train_filenames:
    print(loc+"/"+fname)
    images.append(np.array(Image.open(loc+"/"+fname)))
train = np.array(images)

The last filename that prints out before you get an exception will be the problem one. Apparently one of the things that can cause PermissionError on Windows is if you try to open a directory as a file...

Alternatively, if the loop breaks after the first file, then you know you have a weirder/harder to fix problem on your hands.

like image 116
tel Avatar answered Sep 23 '22 23:09

tel