Python中如何正确使用Rasterio的transform.from_bounds设置边界?
解决Rasterio设置Transform不生效的问题
首先明确两个核心问题:
- 你调用
rasterio.transform.from_bounds时参数错误,最后两个参数是像素列数(width)和行数(height),不是分辨率; - 生成Transform后没有将其关联到栅格的元数据(profile)或文件中,导致原元数据仍为默认值。
正确步骤示例
1. 计算行列数(从边界和分辨率)
先根据你的边界和目标分辨率,计算栅格的像素行列数:
x_min, y_min = 你的左边界, 你的下边界 x_max, y_max = 你的右边界, 你的上边界 resolution = 0.00028 # 你的目标分辨率 # 计算行列数(取整,根据需求调整取整方式) width = int((x_max - x_min) / resolution) height = int((y_max - y_min) / resolution)
2. 生成正确的Transform
用计算好的行列数调用from_bounds:
from rasterio.transform import from_bounds transform = from_bounds(x_min, y_min, x_max, y_max, width, height)
3. 将Transform应用到栅格
场景1:创建新栅格文件
构建包含Transform的元数据Profile,写入文件时传入:
import rasterio import numpy as np # 构建元数据 profile = { 'driver': 'GTiff', 'height': height, 'width': width, 'count': 1, # 波段数 'dtype': 'float32', # 数据类型 'crs': 'EPSG:4326', # 坐标系,根据你的数据调整 'transform': transform, 'nodata': -9999.0 # 无数据值 } # 写入栅格 with rasterio.open('new_raster.tif', 'w', **profile) as dst: # 示例:写入全0数组,替换成你的实际数据 dst.write(np.zeros((1, height, width), dtype='float32'))
场景2:修改已有栅格的Transform
以读写模式打开文件,直接更新Transform属性:
with rasterio.open('existing_raster.tif', 'r+') as src: # 若已有栅格的行列数和你的边界/分辨率匹配,直接用src.width和src.height transform = from_bounds(x_min, y_min, x_max, y_max, src.width, src.height) src.transform = transform # Rasterio会自动根据Transform更新bounds,无需手动设置
验证结果
打开栅格文件查看Transform和边界:
with rasterio.open('your_raster.tif') as src: print("Transform:", src.transform) print("Bounds:", src.bounds)
内容的提问来源于stack exchange,提问作者Johs
相关产品推荐
相关产品推荐

