使用PIL从文件夹加载所有图片

10
import glob
from PIL import Image 


marked = glob.iglob("D:/Users/username/Desktop/cells/Marked")

img = Image.open(marked)
img.show()

我正在尝试使用标记文件夹中包含的图像数据集创建神经网络。运行代码时我遇到了以下错误:

 File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PIL/Image.py", line 2547, in open
    fp.seek(0)
AttributeError: 'generator' object has no attribute 'seek'

我不明白这个错误是什么意思,它似乎是错位的?


Image.open() 接受一个文件字符串/路径/对象作为参数。 - wwii
2个回答

8

您需要在路径末尾指定通配符并进行迭代:

images = []
for f in glob.iglob("D:/Users/username/Desktop/cells/Marked/*"):
    images.append(np.asarray(Image.open(f)))

images = np.array(images)

3
Downvoter,您能否给我一些反馈来改进这个答案? - cs95
如果图像具有不同的形状,np.array(images)会失败。 - Nandesh

4
请参考这个答案,使用PIL.Image和glob来查找文件夹中的所有图片并加载到数组中。
from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
    im=Image.open(filename)
    image_list.append(im)

请问这个回答相较于@coldspeed已经被接受的回答有什么优势? - Mark Setchell
只是指出已经有一个同样有效的答案(还包括导入语句)。 - generic_stackoverflow_user

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接