如何将Rasterio栅格化Shapely多边形的结果保存为图像而非显示?
解决Rasterio栅格保存问题
两种保存方向:地理栅格文件 vs 可视化图像
你要分清楚需求:是保存可用于GIS分析的地理栅格数据,还是保存仅用于展示的可视化图像,两种方式完全不同:
1. 保存地理栅格文件(推荐用于批量生成)
这是生成栅格的核心目的,直接用Rasterio的文件写入API,不需要依赖matplotlib。步骤如下:
- 先定义栅格的元数据(CRS、分辨率、变换参数、数据类型等),可以从原GeoDataFrame或手动指定
- 用
rasterio.open()创建输出文件,写入栅格化后的数组
示例代码:
import rasterio from rasterio.features import rasterize from rasterio.transform import from_bounds import geopandas as gpd # 假设你的GeoDataFrame是gdf,里面有建筑多边形 gdf = gpd.read_file("your_buildings.shp") # 定义栅格参数:这里用数据的边界来设置变换和尺寸 xmin, ymin, xmax, ymax = gdf.total_bounds resolution = 1 # 1米分辨率,根据需求调整 width = int((xmax - xmin) / resolution) height = int((ymax - ymin) / resolution) transform = from_bounds(xmin, ymin, xmax, ymax, width, height) # 栅格化多边形 raster = rasterize( shapes=((geom, 1) for geom in gdf.geometry), out_shape=(height, width), transform=transform, fill=0, dtype=rasterio.uint8 ) # 保存为TIFF地理栅格 with rasterio.open( "buildings_raster.tif", "w", driver="GTiff", height=height, width=width, count=1, dtype=raster.dtype, crs=gdf.crs, transform=transform, ) as dst: dst.write(raster, 1)
2. 保存可视化图像(用于展示)
如果只是需要把栅格的可视化结果存成图片,直接用matplotlib就行——因为rasterio.plot.show()本质就是调用matplotlib渲染图像。
示例代码:
import matplotlib.pyplot as plt import rasterio.plot # 用rasterio.plot.show渲染图像 ax = rasterio.plot.show(raster, transform=transform, cmap="viridis") # 可以添加标题、颜色条等修饰 ax.set_title("建筑多边形栅格化结果") plt.colorbar(ax.images[0], ax=ax, label="建筑区域") # 保存图像 plt.savefig("buildings_raster_plot.png", dpi=300, bbox_inches="tight") plt.close()
是否该直接用matplotlib?
- 如果你的目标是批量生成可用于后续空间分析的栅格数据:绝对不要只依赖matplotlib,必须用Rasterio写入地理栅格文件(如TIFF),这类文件包含空间参考信息,能直接在GIS软件或其他空间分析工具中使用。
- 如果只是生成可视化截图用于报告、展示:用matplotlib完全没问题,操作简单灵活。
内容的提问来源于stack exchange,提问作者Don Mclachlan
相关产品推荐
相关产品推荐

