gpt4 book ai didi

python - 如何以特定的行数和列数划分矩形?

转载 作者:行者123 更新时间:2023-12-03 09:28:09 25 4
gpt4 key购买 nike

我正在尝试将具有特定坐标的矩形划分为 8 个较小的矩形(两列四行),这可能吗?

例如,输入将是:

rec = [(0, 0), (0, 330), (200, 330), (200, 0)]

结果将是:
res = [[(0, 0), (0, 82), (100, 82), (100, 0)], [(0, 82), (0, 164), (100, 164), (100, 82)],.......]

这是我迄今为止尝试过的:
h = 330
w = 200

offsets = [(0, 0), (400, 0), (0, 500), (400, 500)]

blisters = []

for offset in offsets:
pol = [(offset), (offset[0], offset[1] + h), (offset[0] + w, offset[1] + h), (offset[0] + w, offset[1])]
blisters.append(pol)

pits = []

for offset in offsets:
pit = [(offset), (offset[0], int(offset[1] + a)), (int(offset[0] + b), int(offset[1] + a)), (int(offset[0] + b), offset[1]), ]
pits.append(pit)

这就是我需要的(有点:/):
starting point in upper left corner (eg.(0,0)) 
___________
I I I
I I I
-----------
I I I
I I I
-----------
I I I
I I I
-----------
I I I
I I I
-----------

最佳答案

如果您经常使用几何对象,您可能会考虑使用 Shapely图书馆。它有一些有用的功能,我们可以使用这些功能从给定的矩形构建一个由较小矩形组成的网格。

首先,构建一个 Polygon 从您的元组列表中:

from shapely.geometry import LineString, MultiPolygon, Polygon
from shapely.ops import split

rec = [(0, 0), (0, 330), (200, 330), (200, 0)]
nx, ny = 2, 4 # number of columns and rows

polygon = Polygon(rec)

这是你的多边形:
enter image description here

接下来,构建我们将用于 split 的行列表那个多边形:
minx, miny, maxx, maxy = polygon.bounds
dx = (maxx - minx) / nx # width of a small part
dy = (maxy - miny) / ny # height of a small part
horizontal_splitters = [LineString([(minx, miny + i*dy), (maxx, miny + i*dy)]) for i in range(ny)]
vertical_splitters = [LineString([(minx + i*dx, miny), (minx + i*dx, maxy)]) for i in range(nx)]
splitters = horizontal_splitters + vertical_splitters

应用每条线来分割多边形:
result = polygon
for splitter in splitters:
result = MultiPolygon(split(result, splitter))

这是您生成的矩形集合的样子:
enter image description here

如果你想要一个坐标列表,你可以像这样得到它们:
parts = [list(part.exterior.coords) for part in result.geoms]
print(parts)
# [[(0.0, 0.0), (0.0, 82.5), (100.0, 82.5), (100.0, 0.0), (0.0, 0.0)],
# [(100.0, 82.5), (200.0, 82.5), (200.0, 0.0), (100.0, 0.0), (100.0, 82.5)],
# [(0.0, 82.5), (0.0, 165.0), (100.0, 165.0), (100.0, 82.5), (0.0, 82.5)],
# [(100.0, 165.0), (200.0, 165.0), (200.0, 82.5), (100.0, 82.5), (100.0, 165.0)],
# [(0.0, 165.0), (0.0, 247.5), (100.0, 247.5), (100.0, 165.0), (0.0, 165.0)],
# [(100.0, 247.5), (200.0, 247.5), (200.0, 165.0), (100.0, 165.0), (100.0, 247.5)],
# [(0.0, 247.5), (0.0, 330.0), (100.0, 330.0), (100.0, 247.5), (0.0, 247.5)],
# [(100.0, 330.0), (200.0, 330.0), (200.0, 247.5), (100.0, 247.5), (100.0, 330.0)]]

关于python - 如何以特定的行数和列数划分矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58283684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com