借助Xee从GEE导出的NetCDF文件无法在QGIS正常打开
问题描述
我尝试通过Google Earth Engine(GEE)结合Xee(Xarray + GEE)工具,从ImageCollection生成NetCDF文件。代码运行正常,生成的nc文件可在Colab中用Xarray重新打开,也能在Panoply中打开,但无法在QGIS 3.22.4-Białowieża中正常加载。
相关代码如下:
# capture if 'google.colab' in str(get_ipython()): !pip install xee rioxarray netCDF4 import ee import geemap import xee import xarray as xr ee.Authenticate() ee.Initialize(project='ee-my-xavierac', opt_url='https://earthengine-highvolume.googleapis.com') """ROI""" # Create a geodesic polygon. roi = ee.Geometry.Polygon([ [[-46.757813, -23.337212], [-46.757813, -1.158979], [-33.398438, -1.158979], [-33.398438, -23.337212], [-46.757813, -23.337212]], ]); """Data from: BR-DWGD""" name_var = 'PR' # Define a scaling factor offset = 225 scale = 0.006866665 # Function to apply the scaling factor to a specific band def scaleBand(image): scaledImage = image.select("b1").rename([name_var]) \ .multiply(scale).add(offset) \ .set({'date': image.date().format('yyyy-MM-dd')}) return scaledImage.copyProperties(image, image.propertyNames()) # cmap color_pal = ['000066', '001199', '0044BB', '0077DD', '33AAEE', '66CCFF', 'FFDDCC', 'FFBB99', 'FF9966', 'FF6644'] collection = ee.ImageCollection(f"projects/sat-io/open-datasets/BR-DWGD/{name_var}") \ .filterDate('2019-01-01', '2019-01-15') \ .map(scaleBand) """Load ImageCollection to Xarray Dataset""" ds = xr.open_dataset( collection, engine='ee', scale=.1, projection=collection.first().select(0).projection() ) ds # Clip dataset to ROI clipped_ds = ds \ .rename({'lon': 'x', 'lat':'y'}) \ .rio.clip([roi.getInfo()]) clipped_ds export_ds = clipped_ds.transpose() export_ds[name_var].isel(time=0).plot() """Export to NetCDF""" # Enable compression encoding = {name_var: {'zlib': True}} export_ds.to_netcdf('test.nc', encoding=encoding) """Open file to check""" data_test = xr.open_mfdataset('test.nc') data_test data_test[name_var].isel(time=0).plot()
QGIS中的异常显示:
请问我遗漏了什么配置或步骤?
解决方案
针对QGIS加载NetCDF异常的问题,可从以下几个方向修复:
- 补全坐标系元数据
QGIS对NetCDF的坐标系信息要求严格,当前代码未显式将投影信息写入数据集属性。导出前添加以下代码:
import numpy as np # 从原始影像获取标准CRS信息 crs_info = collection.first().select(0).projection().getInfo() clipped_ds = clipped_ds.rio.set_crs(crs_info['crs'])
- 固定维度顺序
QGIS默认识别(time, y, x)或(y, x, time)的维度顺序,修改转置代码为明确的顺序:
export_ds = clipped_ds.transpose('time', 'y', 'x')
- 完善变量属性
给变量添加QGIS可识别的标准元数据,包括单位、描述和填充值:
export_ds[name_var].attrs = { 'units': 'mm', # 根据PR变量实际单位调整 'long_name': 'Daily Precipitation', '_FillValue': np.nan }
- 测试关闭压缩
旧版本QGIS对zlib压缩的支持可能存在兼容性问题,暂时关闭压缩验证:
encoding = {name_var: {'zlib': False}}
- 调整QGIS加载方式
在QGIS中选择「添加栅格图层」加载NetCDF,在数据源窗口中手动指定PR变量和时间维度,避免默认加载错误的维度组合。
内容的提问来源于stack exchange,提问作者Alexandre
相关产品推荐
相关产品推荐

