Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从URL读取多波段tiff文件的干净方法?_Python_Image_Tiff - Fatal编程技术网

Python 从URL读取多波段tiff文件的干净方法?

Python 从URL读取多波段tiff文件的干净方法?,python,image,tiff,Python,Image,Tiff,我有一个web服务,我想从中在Python脚本中加载内存中的多波段图像(最终我将把图像转换成numpy数组)。据我所知,PIL和imageio等软件包不支持此功能 这样做的首选方式是什么?我希望避免将图像保存和读取到磁盘 如果我将文件保存到磁盘,然后使用tiffilepackage作为多波段tiff加载,则一切正常(请参见下面的代码);但是,正如我所说的,我希望避免从磁盘读/写 import requests import tifffile as tiff TMP = 'tmp.tiff'

我有一个web服务,我想从中在Python脚本中加载内存中的多波段图像(最终我将把图像转换成numpy数组)。据我所知,
PIL
imageio
等软件包不支持此功能

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

如果我将文件保存到磁盘,然后使用
tiffile
package作为多波段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)

我不确定多波段图像——如果Pillow(née PIL)支持它们,好吧——但这是使用请求和Pillow从内存中的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>

下面的代码片段就是这样做的。(注意,应该对响应对象执行一些额外的错误检查。)


我使用的URL的一个具体示例:。代码在此特定URL.Hmm上失败。直接下载,然后使用Imagemagick将其转换为PNG(带有一些警告)。我想PIL不支持这种格式,是吗?(macOS的预览版也是如此,值得一提的是…)是的,似乎PIL在多波段TIFF方面普遍存在问题。由于ImageMagick可以读取文件,您可以查看ImageMagick(或Wand)Python绑定。啊,好吧!阅读
tiffile
的源代码,看起来您可以将字节传递给
imload
:--因此,如果您以我的示例替换
图像。使用
tiffile.imload
打开
,事情应该会正常。
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))