如何在Python中从bbox数据创建Polygon?解决shapely报错问题
问题描述
我之前在R中通过以下代码从点列表提取bbox后,用st_as_sfc创建Polygon:
print(st_as_sfc(st_bbox(sgrid)))
输出结果:
Geometry set for 1 feature Geometry type: POLYGON Dimension: XY Bounding box: xmin: -9574057 ymin: 3590448 xmax: -9494057 ymax: 3670448 Projected CRS: WGS 84 / Pseudo-Mercator POLYGON ((-9574057 3590448, -9494057 3590448, -...
现在想在Python中实现相同功能,已经从点数据获取了bbox的xmin、ymin、xmax、ymax坐标,但尝试用shapely创建Polygon时触发错误:
ValueError: A linearring requires at least 4 coordinates.
我的Python代码:
from shapely import geometry print(df) x y geometry 0 3.418932e+06 -2.088506e+07 POINT (-20885056.99629 3418931.63321) 1 3.478932e+06 -2.082506e+07 POINT (-20825056.99629 3478931.63321) poly = geometry.Polygon([[p.x, p.y] for p in gdf_p['geometry'].tolist()]) print(poly.wkt)
解决方案
错误原因
用两个点直接创建Polygon会报错,因为shapely的Polygon要求构成边界的LinearRing必须是闭合的、至少包含4个坐标点的序列(即矩形的四个角点,最后回到起始点形成闭合环)。
方法1:手动构造矩形坐标点
从bbox的xmin、ymin、xmax、ymax生成四个角点,按顺序排列后闭合:
from shapely import geometry # 假设你已经获取到bbox的四个值 xmin = -20885056.99629 ymin = 3418931.63321 xmax = -20825056.99629 ymax = 3478931.63321 # 构造矩形的四个角点,最后回到起始点闭合 coords = [ (xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax), (xmin, ymin) # 闭合环,必须回到第一个点 ] poly = geometry.Polygon(coords) print(poly.wkt)
方法2:使用shapely内置的box函数(推荐,对应R的st_as_sfc(st_bbox))
shapely提供了box函数,可以直接从bbox的四个值生成Polygon,无需手动构造坐标点,和R中的st_as_sfc(st_bbox)逻辑完全一致:
from shapely.geometry import box # 传入xmin, ymin, xmax, ymax四个参数 poly = box(xmin, ymin, xmax, ymax) print(poly.wkt)
如果你的数据是GeoDataFrame,也可以直接对整个GeoDataFrame的bbox生成Polygon:
from shapely.geometry import box import geopandas as gpd # 假设gdf_p是你的GeoDataFrame bbox = gdf_p.total_bounds # 获取整个数据框的bbox,返回[xmin, ymin, xmax, ymax] poly = box(*bbox) print(poly.wkt)
内容的提问来源于stack exchange,提问作者data en
相关产品推荐
相关产品推荐

