在 Numpy 数组中转换 Python get request(jpg content) 的响应

Converting the response of Python get request(jpg content) in Numpy Array

我的函数的工作流程如下:

我这样做是为了省钱:

response = requests.get(urlstring, params=params)
      if response.status_code == 200:
            with open('PATH%d.png' % imagenumber, 'wb') as output:
                output.write(response.content)

这就是我将 png 加载并转换为 np.array

所做的
imagearray = im.imread('PATH%d.png' % imagenumber)

因为我不需要永久存储我下载的内容,所以我尝试修改我的函数以便直接将 response.content 转换为 Numpy 数组。不幸的是,每个 imageio 之类的库都以相同的方式从磁盘读取 uri 并将其转换为 np.array.

我试过了,但显然它没有用,因为它需要一个 uri 输入

response = requests.get(urlstring, params=params)
imagearray = im.imread(response.content))

有什么办法可以解决这个问题吗?如何将 response.content 转换为 np.array?

您可以使用 BytesIO 作为文件来跳过写入实际文件。

bites = BytesIO(base64.b64decode(response.content))

现在您拥有它作为 BytesIO,因此您可以像使用文件一样使用它:

img = Image.open(bites)
img_np = np.array(im)

imageio.imread 能够读取 urls:

import imageio

url = "https://example_url.com/image.jpg"

# image is going to be type <class 'imageio.core.util.Image'>
# that's just an extension of np.ndarray with a meta attribute

image = imageio.imread(url)

您可以在文档中查找更多信息,他们也有示例:https://imageio.readthedocs.io/en/stable/examples.html