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

如何在裁剪后以内存方式打开rasterio数据集?

无需写入磁盘,直接从裁剪结果创建Rasterio数据集

你可以用rasterio内置的MemoryFile类实现这个需求,它能在内存中模拟文件IO操作,彻底跳过磁盘写入步骤。

修改后的代码片段

from rasterio.io import MemoryFile

out_image, out_transform = msk.mask(raster, [clip_shape_polygon], invert=True)

# 保留元数据更新逻辑,无需修改
out_meta = raster.meta.copy()
out_meta.update({
    "driver": "GTiff",
    "height": out_image.shape[1],
    "width": out_image.shape[2],
    "transform": out_transform
})

# 替换磁盘写入+重新读取的逻辑,改用内存文件
with MemoryFile() as memfile:
    with memfile.open(**out_meta) as dest:
        dest.write(out_image)
    # 直接从内存中读取得到目标raster数据集对象
    raster = memfile.open()

关键说明

  • MemoryFile会在内存中创建虚拟文件对象,操作逻辑和真实磁盘文件完全一致,但不会生成磁盘文件
  • 最终得到的raster对象,和你之前从masked.tif读取的对象功能完全相同,可正常调用Rasterio的所有数据集方法
  • 注意要提前导入MemoryFile类,否则会触发导入错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:37:08