在线咨询
eetop公众号 创芯大讲堂 创芯人才网
切换到宽版

EETOP 创芯网论坛 (原名:电子顶级开发网)

手机号码,快捷登录

手机号码,快捷登录

找回密码

  登录   注册  

快捷导航
搜帖子
查看: 403|回复: 3

[讨论] 怎么用python将一个给定坐标的多边形切割成矩形

[复制链接]
发表于 2024-5-23 23:08:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?注册

x
本帖最后由 yyqg 于 2024-5-23 23:13 编辑

脚本大佬们, 如下图,怎么用python将一个给定坐标的直角多边形切割成矩形?


                               
登录/注册后可看大图


输入多边形顶点坐标依次为:
{{0 0} {100 0} {100 50} {50 50} {50 100} {0 100}}
处理完后变成多个矩形,要求输出每个矩形左下,右上两个点坐标,例如:
{{0 0} {50 100}}
{{50 0} {100 50}}
(也可以顺序列出每个矩形的四个点坐标)

(要求顶点很多的复杂的直角多边形也能正确处理)
发表于 2024-5-24 14:31:47 | 显示全部楼层
from shapely.geometry import Polygon, box
from shapely.ops import unary_union, polygonize
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon as MplPolygon

def plot_polygons(polygons, title):
    fig, ax = plt.subplots()
    for poly in polygons:
        if poly.is_empty:
            continue
        patch = MplPolygon(list(poly.exterior.coords), closed=True, edgecolor='black', facecolor='lightblue')
        ax.add_patch(patch)
    ax.set_title(title)
    ax.set_xlim(-1, 10)
    ax.set_ylim(-1, 10)
    plt.gca().set_aspect('equal', adjustable='box')
    plt.show()

def decompose_to_rectangles(polygon):
    minx, miny, maxx, maxy = polygon.bounds
    x_coords = sorted(set([minx, maxx] + [p[0] for p in polygon.exterior.coords]))
    y_coords = sorted(set([miny, maxy] + [p[1] for p in polygon.exterior.coords]))

    rectangles = []
    for i in range(len(x_coords) - 1):
        for j in range(len(y_coords) - 1):
            rect = box(x_coords[i], y_coords[j], x_coords[i + 1], y_coords[j + 1])
            if polygon.intersects(rect):
                intersection = polygon.intersection(rect)
                if intersection.is_empty:
                    continue
                if intersection.geom_type == 'Polygon':
                    rectangles.append(intersection)
                elif intersection.geom_type == 'MultiPolygon':
                    rectangles.extend(intersection.geoms)
    return rectangles

# 示例多边形
coords = [(1, 1), (1, 5), (3, 5), (3, 3), (5, 3), (5, 7), (7, 7), (7, 1), (1, 1)]
polygon = Polygon(coords)

# 分解多边形为矩形
rectangles = decompose_to_rectangles(polygon)

# 输出每个分割矩形的坐标
for i, rect in enumerate(rectangles):
    print(f"Rectangle {i+1}: {list(rect.exterior.coords)}")

# 绘制原始多边形
plot_polygons([polygon], "Original Polygon")

# 绘制分解后的矩形
plot_polygons(rectangles, "Decomposed Rectangles")
 楼主| 发表于 2024-5-24 22:22:28 | 显示全部楼层


1243731713 发表于 2024-5-24 14:31
from shapely.geometry import Polygon, box
from shapely.ops import unary_union, polygonize
import mat ...



                               
登录/注册后可看大图
不错,可以切割,不过有些可以不用切的地方也切了
发表于 2024-5-31 16:45:28 | 显示全部楼层
谢谢分享
您需要登录后才可以回帖 登录 | 注册

本版积分规则

关闭

站长推荐 上一条 /1 下一条

小黑屋| 手机版| 关于我们| 联系我们| 在线咨询| 隐私声明| EETOP 创芯网
( 京ICP备:10050787号 京公网安备:11010502037710 )

GMT+8, 2024-9-8 08:49 , Processed in 0.033826 second(s), 6 queries , Gzip On, Redis On.

eetop公众号 创芯大讲堂 创芯人才网
快速回复 返回顶部 返回列表