gpt4 book ai didi

python - 从 URL 中读取图像并保存在内存中

转载 作者:行者123 更新时间:2023-11-28 22:18:57 25 4
gpt4 key购买 nike

我正在使用 Python 和请求库。例如,我只想将图像下载到一个 numpy 数组,并且有多个问题,您可以在其中找到不同的组合(使用 opencv、PIL、请求、urllib...)

它们都不适合我的情况。我基本上在尝试下载图像时收到此错误:

cannot identify image file <_io.BytesIO object at 0x7f6a9734da98>

我的代码的一个简单示例可以是:

import requests
from PIL import Image

response = requests.get(url, stream=True)
response.raw.decode_content = True
image = Image.open(response.raw)
image.show()

让我发疯的主要是,如果我将图像下载到文件(使用 urllib),整个过程运行没有任何问题!

import urllib
urllib.request.urlretrieve(garment.url, os.path.join(download_folder, garment.get_path()))

我做错了什么?

编辑:

我的错误最终与 URL 形成有关,而不是与请求有关或 PIL 库。如果 URL 正确,我之前的代码示例应该可以完美运行。

最佳答案

我认为您在将数据保存到 Image 之前以某种方式使用了来自 requests.raw 对象的数据,但是请求响应原始对象不可搜索,您只能从中读取一次:

>>> response.raw.seekable()
False

首次打开即可:

>>> response.raw.tell()
0
>>> image = Image.open(response.raw)

第二次打开抛出错误(流位置已经在文件末尾):

>>> response.raw.tell()
695 # this file length https://docs.python.org/3/_static/py.png

>>> image = Image.open(response.raw)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2295, in open
% (filename if filename else fp))
OSError: cannot identify image file <_io.BytesIO object at 0x7f11850074c0>

如果您想多次使用它们,您应该将来自请求响应的数据保存在类似文件的对象(或者当然是文件)中:

import io
image_data = io.BytesIO(response.raw.read())

现在您可以读取图像流并根据需要多次倒带:

>>> image_data.seekable()
True

image = Image.open(image_data)
image1 = Image.open(image_data)

关于python - 从 URL 中读取图像并保存在内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50173582/

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