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

将NumPy数组转为GeoTiff时遇AttributeError错误求助

解决AttributeError: 'DatasetReader' object has no attribute 'open'问题

错误核心原因

你代码里的raster.open()是错误用法:raster是通过rasterio.open()打开文件后得到的DatasetReader对象,而open()是rasterio模块的顶层方法,不是这个对象的属性。创建新GeoTIFF文件必须调用rasterio.open(),而非已打开的文件对象的open方法。

代码里的其他问题及修正

除了上述核心错误,你的代码还有几处变量不匹配的问题:

  • 定义了nlines = raster.height、ncols = raster.width,但写入时误用了未定义的height、width;
  • 定义了data_type = "float32",但写入时用了未定义的dtype;
  • 写入数组时需确保维度符合rasterio要求:数组形状应为(波段数, 高度, 宽度),单波段数组需要额外添加波段维度。

修正后的完整代码

import rasterio
import numpy as np

# 假设这里是你之前的代码:打开原栅格、读取数组、计算得到raster_array
with rasterio.open("原文件路径.tif") as raster:
    # 读取并处理数组,示例:读取第1波段并计算
    raster_array = raster.read(1) * 2  # 替换成你的实际计算逻辑
    # 获取必要信息
    driver = "GTiff"
    height = raster.height
    width = raster.width
    count = raster.count
    dtype = "float32"
    crs = raster.crs
    transform = raster.transform
    file_name = "C:/file_path/file_name.tif"

# 写入GeoTiff
with rasterio.open(file_name, "w",
                   driver=driver,
                   height=height,
                   width=width,
                   count=count,
                   dtype=dtype,
                   crs=crs,
                   transform=transform) as dst:
    # 如果是单波段数组,添加波段维度
    if len(raster_array.shape) == 2:
        raster_array = raster_array[np.newaxis, :, :]
    dst.write(raster_array)

关键修改说明

  1. 将raster.open()改为rasterio.open(),调用模块的顶层方法创建新文件;
  2. 统一变量名,确保写入时使用的变量都已正确定义;
  3. 添加数组维度检查,确保符合rasterio的写入要求(单波段数组需转为(1, height, width)形状)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:45:41