我试图从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
我想把图像直接载入内存。有办法吗?
3条答案
按热度按时间qgzx9mmu1#
既然你提到了
scipy.misc.imread
,我们可以用它来隐藏Image.open
的部分。因此,实现看起来像这样-从性能上看,它似乎可以与另一篇文章中列出的四个转换阶段相媲美。
6ioyuze22#
我发现了一个解决方案,可以绕过写入磁盘:
据我所知,我在三种不同的表示之间转换:
bytes -> BytesIO -> PIL.Image -> np.array
有没有更有效的方法呢?
1u4esq0p3#
由于
scipy.misc.imread()
已被弃用,更好的方法是使用cv2: