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

read tiff file directly to numpy array without saving to disk

我经常下载 (geo) tiff 文件,将它们保存到临时磁盘 space,然后使用 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 数据集。有没有办法将 'stream' in tif 数据转换为 ndarray 对象?理想情况下,可以使用

with rasopen(url, 'r') as src:
    array = src.read()

作为 rasterio returns 一个很好的元数据对象以及 ndarray,尽管我还没有得到它来处理 url 资源。谢谢。

是的,您可以凭记忆阅读:

from rasterio.io import MemoryFile

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

或直接来自 URL:

with rasterio.open('https://pathto.tif') as dataset:
    print(dataset.profile)

我无法让后者与您的 URL 一起使用,所以您可能想尝试第一个。