如何使用GDAL检索netcdf中的所有变量名



我正在努力寻找一种方法来检索元数据信息从一个文件使用GDAL。具体来说,我想检索乐队名称以及它们在给定文件(可能是GEOTIFF或NETCDF)中存储的顺序。

例如,如果我们遵循GDAL文档中的描述,我们有"getmetadata";方法。数据集(参见这里和这里)。尽管此方法返回关于数据集的一整套信息,但它不提供乐队名称和它们在给定文件中存储的顺序。事实上,这似乎是一个老问题(从2015年开始),似乎还没有解决(更多信息在这里)。看起来,"R"语言已经解决了这个问题(见这里),尽管Python还没有。

这里只是为了彻底,我知道还有其他Python包可以帮助完成这项工作(例如,xarray, rasterio等);尽管如此,在单个脚本中应该使用的包集要简洁,这一点很重要。因此,我想知道一种明确的方法来查找带(也就是变量)名称以及它们在使用gdal的单个文件中存储的顺序。

请让我知道你在这方面的想法。

下面,我提出了一个解决这个问题的起点,其中一个文件被GDAL打开(创建一个数据集对象)。

from gdal import Dataset
from osgeo import gdal
OpeneddatasetFile = gdal.Open(f'NETCDF:{input}/{file_name}.nc:' + var)
if isinstance(OpeneddatasetFile , Dataset):
print("File opened successfully")

# here is where one should be capable of fetching the variable (a.k.a., band) names
# of the OpeneddatasetFile.
# Ideally, it would be most welcome some kind of method that could return a dictionary 
# with this information
# something like:
# VariablesWithinFile = OpeneddatasetFile.getVariablesWithinFileAsDictionary()

我终于找到了一种使用GDAL从NETCDF文件中检索变量名的方法,这要感谢上面Robert Davy给出的评论。

我将代码组织成一组函数以帮助其可视化。请注意,还有一个从NETCDF读取元数据的函数,它以字典格式返回这些信息(参见readInfo"函数).

from gdal import Dataset, InfoOptions
from osgeo import gdal
import numpy as np

def read_data(filename):
dataset = gdal.Open(filename)
if not isinstance(dataset, Dataset):
raise FileNotFoundError("Impossible to open the netcdf file")
return dataset

def readInfo(ds, infoFormat="json"):
"how to: https://gdal.org/python/"
info = gdal.Info(ds, options=InfoOptions(format=infoFormat))
return info

def listAllSubDataSets(infoDict: dict):
subDatasetVariableKeys = [x for x in infoDict["metadata"]["SUBDATASETS"].keys()
if "_NAME" in x]
subDatasetVariableNames = [infoDict["metadata"]["SUBDATASETS"][x]
for x in subDatasetVariableKeys]
formatedsubDatasetVariableNames = []
for x in subDatasetVariableNames:
s = x.replace('"', '').split(":")[-1]
s = ''.join(s)
formatedsubDatasetVariableNames.append(s)
return formatedsubDatasetVariableNames

if "__main__" == __name__:
filename = "netcdfFile.nc"
ds = read_data(filename)
infoDict = readInfo(ds)
infoDict["VariableNames"] = listAllSubDataSets(infoDict)

您还可以获得可用子数据集或"变量名称"的概述。在netcdf中执行:

ds = gdal.Open(filename)
subdatasets = ds.GetSubDatasets()

subdatasets将是包含;(1)对应变量的路径,格式为"NETCDF:filename:var"和;(2)关于变量的一些信息,如维度大小和数据类型。

之后,你可以打开一个特定的变量(例如列表中的第一个),像这样:

sub_ds = gdal.Open(subdatasets[0][0])

最新更新