从URL读取多波段tiff文件的简洁方法?

时间:2017-06-27 10:10:55

标签: python image tiff

我有一个Web服务,我希望在Python脚本中加载内存中的多波段图像(最终我会将图像转换为numpy数组)。据我所知,PILimageio等软件包不支持此功能。

这样做的首选方式是什么?我想避免将图像保存并读取到磁盘。

如果我将文件保存到磁盘然后加载为带有tifffile包的多波段tiff,那么工作正常(参见下面的代码);但是,正如我所说,我想避免从/向磁盘读/写。

import requests
import tifffile as tiff


TMP = 'tmp.tiff'


def save_img(url, outfilename):
    resp = requests.get(url)
    with open(outfilename, 'wb') as f:
        f.write(resp.content)


def read_img(url):
    save_img(url, TMP)
    return tiff.imread(TMP)

2 个答案:

答案 0 :(得分:1)

我不确定多波段图像 - 如果Pillow(néePIL)支持它们,那很好 - 但这是使用请求和枕头从内存中的URL加载图像的基本方法:

import requests
from PIL import Image
from io import BytesIO
resp = requests.get('https://i.imgur.com/ZPXIw.jpg')
resp.raise_for_status()
sio = BytesIO(resp.content)  # Create an in-memory stream of the content
img = Image.open(sio)  # And load it
print(img)

输出

<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=605x532>

答案 1 :(得分:0)

以下代码片段可以解决问题。 (注意,应该对响应对象进行一些额外的错误检查。)

import requests
import tifffile as tiff
import io


def read_image_from_url(url):
    resp = requests.get(url)
    # Check that request succeeded
    return tiff.imread(io.BytesIO(resp.content))