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

Python中任意多边形的正方形网格剖分实现方案咨询

任意多边形等大小正方形剖分的无地理依赖实现方案

核心思路

完全脱离地理坐标系,基于平面几何运算实现:先计算多边形的外接矩形,生成覆盖该矩形的等大小正方形网格,再筛选出与原多边形有交集(或完全包含)的正方形,得到近似剖分结果。

具体实现步骤(基于Python + Shapely)

Shapely是专注平面几何处理的库,完全不依赖地理信息,能满足你的需求。

1. 安装依赖

pip install shapely

2. 核心实现代码

from shapely.geometry import Polygon, box
from math import ceil

def polygon_to_square_grid(polygon, cell_size):
    # 获取多边形的外接矩形边界
    env = polygon.envelope
    x_min, y_min, x_max, y_max = env.bounds
    
    # 计算网格的行列数
    cols = ceil((x_max - x_min) / cell_size)
    rows = ceil((y_max - y_min) / cell_size)
    
    valid_cells = []
    for i in range(cols):
        for j in range(rows):
            # 计算当前正方形的坐标范围
            cell_x_left = x_min + i * cell_size
            cell_y_top = y_max - j * cell_size
            # 创建正方形几何对象(Shapely的box格式:minx, miny, maxx, maxy)
            cell = box(cell_x_left, cell_y_top - cell_size, cell_x_left + cell_size, cell_y_top)
            # 筛选与原多边形相交的正方形(可根据需求换成within保留完全内部的)
            if polygon.intersects(cell):
                # 若需要保留多边形与正方形的重叠区域,替换为cell.intersection(polygon)
                valid_cells.append(cell)
    return valid_cells

# 示例:测试不规则多边形
sample_polygon = Polygon([(0,0), (5,2), (3,6), (1,4)])
# 生成边长为1的正方形网格
square_grid = polygon_to_square_grid(sample_polygon, cell_size=1)

# 可视化验证(可选)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# 绘制原多边形
x, y = sample_polygon.exterior.xy
ax.plot(x, y, color='blue', linewidth=2)
# 绘制网格
for cell in square_grid:
    x_cell, y_cell = cell.exterior.xy
    ax.plot(x_cell, y_cell, color='gray', linewidth=0.5)
plt.show()

3. 性能优化(针对复杂多边形/大网格)

如果多边形复杂且网格数量大,用空间索引加速相交判断:

from shapely.strtree import STRtree

def optimized_polygon_to_grid(polygon, cell_size):
    env = polygon.envelope
    x_min, y_min, x_max, y_max = env.bounds
    cols = ceil((x_max - x_min)/cell_size)
    rows = ceil((y_max - y_min)/cell_size)
    
    all_cells = []
    for i in range(cols):
        for j in range(rows):
            cell_x_left = x_min + i*cell_size
            cell_y_top = y_max - j*cell_size
            cell = box(cell_x_left, cell_y_top - cell_size, cell_x_left + cell_size, cell_y_top)
            all_cells.append(cell)
    
    # 构建空间索引,快速查询相交单元格
    tree = STRtree(all_cells)
    valid_cells = tree.query(polygon)
    return valid_cells

关键说明

  • 替代Tesspy的原因:Tesspy依赖Mercantile是为地理瓦片设计,而Shapely处理纯平面笛卡尔坐标,完全脱离地理体系,输出效果和你需要的正方形网格一致。
  • 近似度调整:可通过修改判断条件(intersects/within)或保留重叠区域(intersection),适配不同的近似剖分需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:55:28