|
发表于 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") |
|