gpt4 book ai didi

python - “图像”对象没有属性 'read'

转载 作者:行者123 更新时间:2023-12-04 12:10:43 25 4
gpt4 key购买 nike

我想使用存储在字典中的图像将其转换为 GIF。字典里的图片是这样的:

people={
1: <PIL.Image.Image image mode=RGBA size=16x16 at 0x10962C510>,
2: <PIL.Image.Image image mode=RGBA size=16x16 at 0x1098D7F90>,
3: <PIL.Image.Image image mode=RGBA size=16x16 at 0x1098D7F50>}

我认为是枕头图像。但是为什么我总是收到这个错误:

'Image' object has no attribute 'read'



这是什么意思?

完整的错误:
File "/***view.py", line 266, in convert_gif
new_frame = Image.open(imgs[count])
File "/***/python3.7/site-packages/PIL/Image.py", line 2775, in open
prefix = fp.read(16)
AttributeError: 'Image' object has no attribute 'read' –

编码:
self._images = { 
people: {
1: <PIL.Image.Image image mode=RGBA size=16x16 at 0x10962C510>,
2: <PIL.Image.Image image mode=RGBA size=16x16 at 0x1098D7F90>,
3: <PIL.Image.Image image mode=RGBA size=16x16 at 0x1098D7F50>
}
}

def convert_gif(self):

imgs = self._images["people"]
number = len(imgs)
count=1

while count <= number:
new_frame = Image.open(imgs[count])
self._frames.append(new_frame)
count += 1

self._frames[0].save('png_to_gif.gif', format='GIF', append_images=self._frames[1:], save_all=True, duration=300, loop=0)

最佳答案

正如其他人在评论中指出的那样,问题是这样的:

imgs = self._images["people"]
...
new_frame = Image.open(imgs[count])
错误来自 Image.open ,它希望你传递一个文件名,一个 file object ,或 pathlib.Path 对象作为第一个位置参数:

PIL.Image.open(fp, mode='r', formats=None)

Parameters

fp – A filename (string), pathlib.Path object or a file object.The file object must implement file.read, file.seek, and file.tell methods, and be opened in binary mode.


在 Python 中,文件对象有一个 read method , 和 Image.open只需调用 read传递的文件对象上的方法。它读取图像文件并将其转换为 Image目的。
但是如果你检查 imgs[count]的类型,它已经是 Image目的。
curr_img = imgs[count]
print(curr_img)
# <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=240x160 at 0x7F5C00B74588>
Image objects没有 read 方法,他们不应该有一个,因为图像数据已经加载到内存中。您现在可以使用 Image -对象上的相关函数,例如将它们附加到列表以创建 GIF。
所以只需删除 Image.open调用它会按预期工作。
while count <= number:
new_frame = imgs[count]
self._frames.append(new_frame)
count += 1

关于python - “图像”对象没有属性 'read',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58468944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com