Nik*_*day 2 python optimization numpy scipy python-requests
我正在尝试从Web上获取JPEG图像资源,将其转换为NumPy数组图像表示形式,类似于由返回的数组scipy.misc.imread。而不是将映像保存到磁盘,如以下示例所示:
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
Run Code Online (Sandbox Code Playgroud)
我想将图像直接加载到内存中。有办法吗?
既然您提到过scipy.misc.imread,我们可以用它来隐藏的一部分Image.open。因此,实现看起来像这样-
from scipy import misc
res = requests.get(url)
img_arr = misc.imread(BytesIO(res.content))
Run Code Online (Sandbox Code Playgroud)
在性能方面,这似乎可以与另一篇文章中列出的四个转换阶段相媲美。