You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行Dask Xarray的.compute()等操作时出现地理参考警告及文件读取错误

Stackstac导入数据后plot/compute报错:ValueError: Can't read closed raster file

问题描述

在Planetary Computer环境中,通过Stackstac加载遥感数据生成Xarray DataArray:

data = stackstac.stack(items, assets=['no2'], epsg=4326, resolution=0.01, bounds_latlon=bbox)
  • 可正常执行.mean()、.groupby()等延迟计算操作
  • 调用.plot()、.compute()或访问.values时,先弹出警告:

    NotGeoreferencedWarning: Dataset has no geotransform, gcps, or rpcs. The identity matrix will be returned.

  • 随后抛出冗长栈跟踪,最终报错:ValueError: Can't read closed raster file,推测是stackstac的rio_reader自动关闭文件所致

原因分析

  1. Stackstac默认通过rasterio.Env管理文件句柄,延迟计算阶段仅构建计算图,未实际读取文件;触发实际计算时,之前的文件句柄可能已被自动回收关闭
  2. 地理变换警告说明数据的空间元信息未正确加载,进一步导致rasterio读取文件时出现异常

解决方案

1. 禁用rio_reader自动关闭文件

在stackstac.stack()中添加rio_reader_kwargs={"close": False}参数,阻止文件句柄被自动关闭:

data = stackstac.stack(
    items, 
    assets=['no2'], 
    epsg=4326, 
    resolution=0.01, 
    bounds_latlon=bbox,
    rio_reader_kwargs={"close": False}
)

注意:数据使用完毕后建议手动清理资源,避免内存泄漏

2. 提前将数据加载到内存

若数据量较小,直接在stack后调用.compute()将数据加载到内存,后续操作不再依赖原文件句柄:

data = stackstac.stack(
    items, 
    assets=['no2'], 
    epsg=4326, 
    resolution=0.01, 
    bounds_latlon=bbox
).compute()

3. 补全数据地理元信息

针对地理变换警告,手动设置数据的空间参考和变换参数,确保rasterio能正确识别空间信息:

import rasterio.transform

# 根据输入的bbox和数据尺寸计算地理变换
transform = rasterio.transform.from_bounds(
    west=bbox[0], south=bbox[1], east=bbox[2], north=bbox[3],
    width=data.sizes['x'], height=data.sizes['y']
)
data.rio.set_transform(transform)
data.rio.set_crs("EPSG:4326")

补全后再执行.plot()或.compute()操作,可缓解文件读取异常

内容的提问来源于stack exchange,提问作者Seismoditya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 10:57:16