将图像从网页链接直接加载到NumPy数组(Python)

将图像从网页链接直接加载到NumPy数组(Python),python,numpy,optimization,scipy,python-requests,Python,Numpy,Optimization,Scipy,Python Requests,我正在尝试将一个JPEG图像资源从web获取到一个NumPy数组图像表示形式,类似于返回的数组。而不是将映像保存到磁盘,如下例所示: import requests from scipy import misc def load_image(url): res = requests.get(url) if res == 200 and 'jpeg' in res.headers['content-type']: with open('image.jpg', '

我正在尝试将一个JPEG图像资源从web获取到一个NumPy数组图像表示形式,类似于返回的数组。而不是将映像保存到磁盘,如下例所示:

import requests
from scipy import misc
def load_image(url):
    res = requests.get(url) 
    if res == 200 and 'jpeg' in res.headers['content-type']: 
        with open('image.jpg', 'wb') as fp: 
            for chunk in res: 
                fp.write(chunk)
        img_arr = misc.imread('image.jpg') 
        return img_arr
    else: 
        return None

我想把图像直接载入内存。有没有办法做到这一点

我找到了一种绕过磁盘写入的解决方案:

from io import BytesIO
import requests
import numpy as np 
from PIL import Image
def load_image(url): 
    res = requests.get(url)
    if res == 200 and 'jpeg' in res.headers['content-type']:
        img_arr = np.array(Image.open(BytesIO(res.content)))
        return img_arr
    else: 
        return None
据我所知,我正在三种不同的表示法之间转换:
bytes->BytesIO->PIL.Image->np.array

有没有更有效的方法

既然你提到了,我们可以用它来隐藏
图像的部分。打开
。因此,实现将如下所示-

from scipy import misc

res = requests.get(url)
img_arr = misc.imread(BytesIO(res.content))

就性能而言,它似乎与另一篇文章中列出的四个转换阶段相当。

misc.imread
采用的字符串是文件名,而不是字节stream@NikhilShinday那么,发布的解决方案对您不起作用?对我来说很好。您的Scipy版本是什么?模块“Scipy.misc”没有属性“imread”