【问题标题】:read tiff file directly to numpy array without saving to disk直接将 tiff 文件读取到 numpy 数组而不保存到磁盘
【发布时间】:2018-08-31 00:22:21
【问题描述】:

我经常下载 (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()

因为rasteriondarray 一起返回了一个不错的元数据对象,尽管我还没有将它与url 资源一起使用。谢谢。

【问题讨论】:

    标签: python image numpy xarray rasterio


    【解决方案1】:

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

    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 一起使用,因此您可能想尝试第一个。

    【讨论】:

      猜你喜欢
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 2022-01-25
      • 2010-10-26
      • 2017-04-11
      • 2018-05-14
      相关资源
      最近更新 更多