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

jtw3ybtb  于 12个月前  发布在  Python
关注(0)|答案(3)|浏览(100)

我试图从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

我想把图像直接载入内存。有办法吗?

qgzx9mmu

qgzx9mmu1#

既然你提到了scipy.misc.imread,我们可以用它来隐藏Image.open的部分。因此,实现看起来像这样-

from scipy import misc

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

从性能上看,它似乎可以与另一篇文章中列出的四个转换阶段相媲美。

6ioyuze2

6ioyuze22#

我发现了一个解决方案,可以绕过写入磁盘:

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
有没有更有效的方法呢?

1u4esq0p

1u4esq0p3#

由于scipy.misc.imread()已被弃用,更好的方法是使用cv2:

import cv2,requests
import numpy as np
from fake_useragent import UserAgent

ua = UserAgent()
img_data = requests.get(YOUR_URL_HERE,verify=False,timeout=1,
        headers={"Content-Type":ua.random}).content
img = cv2.imdecode(np.frombuffer(img_data,np.uint8),-1)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

相关问题