【问题标题】:Convert raster time series of multiple GeoTIFF images to NetCDF将多个 GeoTIFF 图像的栅格时间序列转换为 NetCDF
【发布时间】:2018-04-04 14:10:27
【问题描述】:

我有一个栅格时间序列存储在多个 GeoTIFF 文件 (*.tif) 中,我想将其转换为单个 NetCDF 文件。数据为uint16

我可能会使用gdal_translate 将每个图像转换为 netcdf 使用:

 gdal_translate -of netcdf -co FORMAT=NC4 20150520_0164.tif foo.nc

然后使用NCO 编写一些脚本以从文件名中提取日期然后连接,但我想知道我是否可以使用xarray 在Python 中更有效地执行此操作,它是新的rasterio 后端。

我可以轻松读取文件:

import glob
import xarray as xr
f = glob.glob('*.tif')
da = xr.open_rasterio(f[0]) 
da

返回

<xarray.DataArray (band: 1, y: 5490, x: 5490)>
[30140100 values with dtype=uint16]
Coordinates:
  * band     (band) int64 1
  * y        (y) float64 5e+05 5e+05 5e+05 5e+05 5e+05 4.999e+05 4.999e+05 ...
  * x        (x) float64 8e+05 8e+05 8e+05 8e+05 8.001e+05 8.001e+05 ...
Attributes:
    crs:      +init=epsg:32620

我可以将其中一个写入 NetCDF:

ds.to_netcdf('foo.nc')

但理想情况下,我可以使用 xr.open_mfdataset 之类的东西,写入时间值(从文件名中提取),然后将整个聚合写入 netCDF。并让dask 处理核外内存问题。 :-)

xarraydask 可以做到这样的事情吗?

【问题讨论】:

    标签: python dask python-xarray rasterio


    【解决方案1】:

    Xarray 应该能够为您完成 concat 步骤。我在下面修改了你的例子。您可以将文件名解析为有用的内容。

    import glob
    import pandas as pd
    import xarray as xr
    
    def time_index_from_filenames(filenames):
        '''helper function to create a pandas DatetimeIndex
           Filename example: 20150520_0164.tif'''
        return pd.DatetimeIndex([pd.Timestamp(f[:8]) for f in filenames])
    
    filenames = glob.glob('*.tif')
    time = xr.Variable('time', time_index_from_filenames(filenames))
    chunks = {'x': 5490, 'y': 5490, 'band': 1}
    da = xr.concat([xr.open_rasterio(f, chunks=chunks) for f in filenames], dim=time)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-02
    • 2021-06-25
    • 2012-02-10
    • 2012-10-23
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    相关资源
    最近更新 更多