将tiff文件直接读取到numpy数组而不保存到磁盘

时间:2018-03-21 18:15:41

标签: python image numpy xarray rasterio

我经常下载(geo)tiff文件,将它们保存到临时磁盘空间,然后使用rasterio读取数据以获得我可以分析的numpy.ndarray

例如,使用this url for NAIP imagery

import os
from requests import get
from rasterio import open as rasopen

req = get(url, verify=False, stream=True)
if req.status_code != 200:
    raise ValueError('Bad response from NAIP API request.')
temp = os.path.join(os.getcwd(), 'temp', 'tile.tif')
with open(temp, 'wb') as f:
    f.write(req.content)
with rasopen(temp, 'r') as src:
    array = src.read()
    profile = src.profile
os.remove(temp)    

对于其他(netcdf)地理网格化数据,我可能会使用xarray来获取数据 来自this url to get Gridmet data

from xarray import open_dataset

xray = open_dataset(url)
variable = 'pr' # precipitation
subset = xray.loc[dict(lat=slice(north, south),
                       lon=slice(west,east))]
arr = subset.variable.values

因此,让xarray对象作为流工作并且很容易进入ndarray,但我只知道这对netcdf数据集起作用。有没有办法来流式传输'在tif数据到ndarray对象?理想情况下,人们可以用

来做到这一点
with rasopen(url, 'r') as src:
    array = src.read()

因为rasterio会返回一个不错的元数据对象以及ndarray,但我还没有得到它来处理url资源。感谢。

1 个答案:

答案 0 :(得分:1)

是的,您可以从内存中读取它:

SELECT * FROM user_source WHERE line = 1;

或直接来自网址:

from rasterio.io import MemoryFile

with MemoryFile(data) as memfile:
    with memfile.open() as dataset:
        data_array = dataset.read()

我无法让后者使用你的网址,所以你可能想尝试第一次。