使用Rasterio官方示例代码创建TIFF文件时报array未定义错误如何解决
Rasterio写入TIFF变量未定义报错排查方案
name 'array' is not defined属于Python基础的变量未定义错误,将array替换为np.array无法解决问题的原因是:np.array是numpy创建数组的构造方法,不是你实际需要写入的目标数组数据。
排查步骤
- 确认目标数组已提前定义赋值:写入TIFF前需要先通过读取源文件、手动生成等方式得到对应维度的numpy数组,单波段写入场景下数组shape需要和profile中声明的
height、width完全匹配。 - 确认变量名一致:写入时调用的变量名需要和你提前定义的数组变量名完全相同,比如预先定义的数组变量为
processed_arr,写入时参数就要对应为processed_arr.astype(rasterio.uint8)。 - 确认依赖导入正常:代码开头需要提前导入numpy依赖,语句为
import numpy as np,避免数组类型转换时报错。
完整可运行示例
场景1:从已有TIFF读取数据处理后写入新文件
import rasterio import numpy as np # 读取源TIFF,同时获取目标处理数组 with rasterio.open("your_source_file.tif") as src: # 读取第一个波段的数组,此处arr即为后续要写入的目标数组 arr = src.read(1) # 此处可添加数组处理逻辑,如二值化、归一化、波段运算等 # 写入新TIFF文件 with rasterio.Env(): profile = src.profile profile.update( dtype=rasterio.uint8, count=1, compress='lzw' ) with rasterio.open('example.tif', 'w', **profile) as dst: dst.write(arr.astype(rasterio.uint8), 1)
场景2:手动生成数组直接写入
import rasterio import numpy as np # 手动生成256*256尺寸的单波段uint8数组 arr = np.random.randint(0, 255, size=(256, 256), dtype=np.uint8) # 手动定义写入所需的profile参数 profile = { 'driver': 'GTiff', 'width': 256, 'height': 256, 'count': 1, 'dtype': rasterio.uint8, 'crs': 'EPSG:4326', 'transform': rasterio.transform.from_origin(100, 30, 0.01, 0.01), 'compress': 'lzw' } with rasterio.open('example.tif', 'w', **profile) as dst: dst.write(arr, 1)
内容的提问来源于stack exchange,提问作者The_perks_of_being_on_mars
相关产品推荐
相关产品推荐

