从特定文件打开图像?

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)

一直给我这个错误:

im= Image.open(文件名)

文件“/home/ns3/.local/lib/python2.7/site-packages/PIL/Image.py”,第 2416 行,打开 fp = io.BytesIO(fp.read())

A​​ttributeError: 'list' 对象没有属性 'read

如何从该特定路径打开图像并将图像用作数组 I?

问题是 glob.glob() returns 一个列表 (a possibly-empty list of path names that match pathname) 而你想要一个字符串。

所以要么插入一个 [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)

或者一起跳过 glob

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)