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

如何将GeoPandas/GeoPlot生成的绘图输出转换为GeoTiff格式文件

解决Geoplot输出转GeoTiff的实现方案

所需依赖

提前安装以下依赖库即可完成转换:

  • geopandas
  • geoplot
  • matplotlib
  • rasterio
  • numpy

核心逻辑

Geoplot基于Matplotlib实现绘图,因此我们可以先拿到绘图的地理元信息(GeoDataFrame的CRS、实际显示边界),再将Matplotlib画布渲染的光栅图像和地理元信息绑定,最终写入为标准GeoTiff格式。

完整实现代码

import geopandas as gpd
import geoplot as gplt
import matplotlib.pyplot as plt
import numpy as np
import rasterio
from rasterio.transform import from_bounds

# ---------------------- 1. 替换为你自己的绘图逻辑 ----------------------
# 加载你的矢量数据
gdf = gpd.read_file("你的矢量文件路径.shp")
# 新建画布,指定dpi控制输出分辨率
dpi = 300
fig, ax = plt.subplots(figsize=(10, 10), dpi=dpi)
# geoplot绘图必须绑定到上述新建的ax对象上
gplt.polyplot(gdf, ax=ax, edgecolor='gray', facecolor='lightblue')

# ---------------------- 2. 提取地理元信息 ----------------------
# 如果手动调整过轴的显示范围,替换为ax.get_xlim()、ax.get_ylim()获取实际边界
minx, miny, maxx, maxy = gdf.total_bounds
crs = gdf.crs

# ---------------------- 3. 画布转光栅数组 ----------------------
# 关闭坐标轴、去除冗余白边,避免导出图像带多余边框
ax.set_axis_off()
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
# 渲染画布为numpy数组
fig.canvas.draw()
img_array = np.array(fig.canvas.renderer.buffer_rgba())
# 调整数组维度为rasterio要求的 (波段数, 高度, 宽度) 格式
img_array = np.moveaxis(img_array, -1, 0)
height, width = img_array.shape[1], img_array.shape[2]

# ---------------------- 4. 生成地理变换参数 ----------------------
transform = from_bounds(
    west=minx,
    south=miny,
    east=maxx,
    north=maxy,
    width=width,
    height=height
)

# ---------------------- 5. 写入GeoTiff ----------------------
with rasterio.open(
    "output.tif",
    "w",
    driver="GTiff",
    height=height,
    width=width,
    count=4, # RGBA四通道,不需要透明可改为3,同时取img_array[:3,:,:]写入
    dtype=img_array.dtype,
    crs=crs,
    transform=transform
) as dst:
    dst.write(img_array)

plt.close(fig)

常见调整项

  • 不需要透明通道时,将count参数改为3,写入时取img_array[:3, :, :]即可丢弃Alpha通道
  • 导出图像坐标偏移时,优先检查是否手动调整过轴显示范围,此时需要用ax.get_xlim()、ax.get_ylim()的返回值替代gdf的total_bounds计算transform
  • 需要更高分辨率时,调高新建画布时的dpi参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:39:03