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

如何用Python将谷歌地图截图轮廓转为Shapefile空间线条?

解决OpenCV轮廓转Shapefile的步骤与代码

核心前提(必须明确)

要完成像素坐标到地理坐标的转换,你必须先获取两个关键信息:

  • 谷歌地图截图的像素尺寸(宽width,高height,可通过cv2.imread读取图像后取img.shape获取)
  • 截图对应的地理边界:截图左上角的经纬度(lon_top, lat_top)和右下角的经纬度(lon_bottom, lat_bottom),可通过谷歌地图点击对应位置获取,或从截图时的地图链接参数中提取

步骤1:处理OpenCV轮廓格式

OpenCV返回的轮廓是三维数组([[[x1,y1]], [[x2,y2]], ...]),需要先扁平化为二维点列表:

import numpy as np
# 示例轮廓数据
contours = [np.array([[[271, 485]], [[271, 488]], [[272, 489]], [[272, 491]], [[273, 492]], [[274, 492]], [[273, 492]], [[272, 491]], [[272, 489]], [[271, 488]]], dtype=np.int32)]

# 扁平化每个轮廓的点,转为(n, 2)格式
flattened_contours = []
for cnt in contours:
    flattened = cnt.reshape(-1, 2)
    flattened_contours.append(flattened)

步骤2:像素坐标转地理坐标

注意:图像Y轴从上到下递增,而地理纬度从北到南递减,需反转Y轴后再做线性映射:

# 替换为你的截图实际参数
width = 800  # 截图像素宽度
height = 600 # 截图像素高度
lon_top = 116.3974  # 左上角经度
lat_top = 39.9087   # 左上角纬度
lon_bottom = 116.4074 # 右下角经度
lat_bottom = 39.8987  # 右下角纬度

def pixel_to_geo(x, y):
    # 经度:从左到右线性映射
    lon = lon_top + (lon_bottom - lon_top) * (x / width)
    # 纬度:反转Y轴后线性映射
    lat = lat_top + (lat_bottom - lat_top) * ((height - y) / height)
    return (lon, lat)

# 转换所有轮廓点为地理坐标
geo_contours = []
for cnt in flattened_contours:
    geo_points = [pixel_to_geo(x, y) for x, y in cnt]
    geo_contours.append(geo_points)

步骤3:生成Shapefile(使用GeoPandas)

根据轮廓类型(道路可用LineString或Polygon)创建地理数据,再保存为Shapefile:

import geopandas as gpd
from shapely.geometry import Polygon, LineString

# 生成几何对象(如果是道路线,替换为LineString)
geometries = []
for geo_points in geo_contours:
    # 确保轮廓闭合(OpenCV轮廓通常已闭合,此处做冗余处理)
    if geo_points[0] != geo_points[-1]:
        geo_points.append(geo_points[0])
    polygon = Polygon(geo_points)
    geometries.append(polygon)

# 创建GeoDataFrame并设置坐标系(EPSG:4326为经纬度坐标系)
gdf = gpd.GeoDataFrame({'geometry': geometries}, crs="EPSG:4326")

# 保存为Shapefile
gdf.to_file("road_contours.shp")

常见问题排查

  • 投影不生效:确认crs参数匹配你的地理坐标格式,谷歌地图原始坐标系为Web墨卡托(EPSG:3857),若地理边界用的是该坐标,转换后可通过gdf.to_crs("EPSG:4326")转成经纬度。
  • 轮廓位置颠倒:检查是否反转了Y轴,这是像素转地理坐标时最容易忽略的问题。
  • Fiona/GDAL报错:确保已安装依赖库(pip install geopandas fiona shapely),Windows系统需提前安装GDAL预编译包。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:56:01