Search code examples
pythonnumpypython-imaging-libraryglob

Opening an Image from a specific file?


import glob
import numpy as np
from PIL import Image

filename = glob.glob('/home/ns3/PycharmProjects/untitled1/stego.pgm')
im= Image.open(filename)
(x,y) = im.size
I = np.array(im.getdata()).reshape(y, x)

Keeps giving me this error:

im= Image.open(filename)

File "/home/ns3/.local/lib/python2.7/site-packages/PIL/Image.py", line 2416, in open fp = io.BytesIO(fp.read())

AttributeError: 'list' object has no attribute 'read

How can I open an image from that specific path and use the image as array I?


Solution

  • The issue is that glob.glob() returns a list (a possibly-empty list of path names that match pathname) and you want a string.

    so either insert a [0]

    import glob
    import numpy as np
    from PIL import Image
    
    filenames = glob.glob('/home/ns3/PycharmProjects/untitled1/stego.pgm')
    filename = filenames[0]
    im= Image.open(filename)
    (x,y) = im.size
    I = np.array(im.getdata()).reshape(y, x)
    

    or skip glob all together

    import numpy as np
    from PIL import Image
    
    filename = '/home/ns3/PycharmProjects/untitled1/stego.pgm'
    im= Image.open(filename)
    (x,y) = im.size
    I = np.array(im.getdata()).reshape(y, x)