我正在尝试扩展 odo 库,使其具有将 GDAL 数据集(具有空间信息的栅格)转换为 NetCDF 文件的功能。
读取 gdal 数据集很顺利。但是在 netcdf 的创建阶段,我需要一些 gdal 数据集的元数据(调用 odo.odo(source,target) 时还不知道的元数据)。我怎么能做到这一点?
到目前为止我的代码的简短版本:
import odo
from odo import resource, append
import gdal
import netCDF4 as nc4
import numpy as np
@resource.register('.+\.tif')
def resource_gdal(uri, **kwargs):
ds = gdal.Open(uri)
# metadata I need to transfer to netcdf
b = ds.GetGeoTransform() #bbox, interval
return ds
@resource.register('.+\.nc')
def resource_netcdf(uri, dshape=None, **kwargs):
ds = nc4.Dataset(uri,'w')
# create lat lon dimensions and variables
ds.createDimension(lat, dshape[0].val)
ds.createDimension(lon, dshape[1].val)
lat = ds.createVariable('lat','f4', ('lat',))
lon = ds.createVariable('lon','f4', ('lon',))
# create a range from the **gdal metadata**
lat_array = np.arange(dshape[0].val)*b[1]+b[0]
lon_array = np.arange(dshape[1].val)*b[5]+b[3]
# assign the range to the netcdf variable
lat[:] = lat_array
lon[:] = lon_array
# create the variable which will hold the gdal data
data = ds.createVariable('data', 'f4', ('lat', 'lon',))
return data
@append.register(nc4.Variable, gdal.Dataset)
def append_gdal_to_nc4(tgt, src, **kwargs):
arr = src.ReadAsArray()
tgt[:] = arr
return tgt
谢谢!