【问题标题】:Read image from URL and keep it in memory从 URL 读取图像并将其保存在内存中
【发布时间】:2018-05-04 11:12:29
【问题描述】:

我正在使用 Python 和请求库。例如,我只想将图像下载到 numpy 数组中,并且有多个问题可以在其中找到不同的组合(使用 opencv、PIL、requests、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.open前添加output.seek(0)
  • 我想你可能错了!我应该在哪里打电话寻求?在您提到的问题中,他们正在将图像写入文件,但这正是我试图避免的
  • 你的第一个代码块对我来说很好。你使用的是什么版本的 python/requests/PIL?我在 python 2.7 上使用过:Pillow==5.1.0 requests==2.18.4
  • 我正在使用:python:3.5,请求:2.18.4,PIL:5.1.0

标签: python python-requests python-imaging-library


【解决方案1】:

我认为您在将它们保存在 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)

【讨论】:

  • 这是一个很棒的观察!不幸的是,这与我遇到的问题无关。我正在使用一个 API 来从那里检索图像链接,因此我将尝试对此进行一些调查!
  • @m33n 我认为无论您从哪里获取文件网址都无关紧要 - 我正在使用此文件中的图像进行测试https://docs.python.org/3/_static/py.png
  • 是的,它现在确实可以使用外部链接,所以问题必须与我的网址有关
  • @m33n 无论如何,如果您正在处理内存中的文件,那么来自 io 模块的类似文件的对象是要走的路
  • 我试图避免编写过程来优化我的代码并直接处理图像
猜你喜欢
  • 1970-01-01
  • 2016-07-26
  • 1970-01-01
  • 1970-01-01
  • 2012-12-19
  • 2017-03-12
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
相关资源
最近更新 更多