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

如何压缩Python模块xarray中rio.to_raster的输出文件?

解决xarray rio.to_raster导出TIFF无压缩的问题

其实rio.to_raster支持通过关键字参数直接传递rasterio的TIFF压缩配置,只是没在表面选项里列出来,直接加参数就行:

方法一:直接给rio.to_raster加压缩参数

把原来的导出代码改成这样,比如用DEFLATE无损压缩(推荐):

# 替换成你的xarray对象和输出路径
xarray_obj.rio.to_raster(
    "output_compressed.tif",
    compress="DEFLATE",  # 指定压缩算法
    predictor=2,         # 整型数据用2,浮点型用3,能提升压缩率
    zlevel=6             # 压缩级别1-9,越高压缩率越高,速度越慢
)

可选的压缩算法还有这些:

  • LZW:无损压缩,兼容性强
  • JPEG:有损压缩,适合RGB影像,需搭配quality=80这类参数调整画质
  • PACKBITS:适合有大量重复值的整型栅格

方法二:用rasterio直接写入(更精细控制)

如果需要更复杂的配置,比如自定义块大小、添加元数据,可以直接用rasterio手动写入:

import rasterio

# 从xarray对象提取空间信息和数据
crs = xarray_obj.rio.crs
transform = xarray_obj.rio.transform
data = xarray_obj.values
height, width = data.shape[:2]
band_count = data.shape[0] if len(data.shape) > 2 else 1
dtype = data.dtype

# 打开文件并写入带压缩的TIFF
with rasterio.open(
    "output_compressed.tif",
    "w",
    driver="GTiff",
    height=height,
    width=width,
    count=band_count,
    dtype=dtype,
    crs=crs,
    transform=transform,
    compress="DEFLATE",
    predictor=2,
    zlevel=6,
    # 还可以加blockxsize=256, blockysize=256 这类分块参数
) as dst:
    dst.write(data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:19:56