我正在尝试将具有特定坐标的矩形划分为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
-----------
如果使用numpy
库,则使用linspace
函数会生成等距点,大大简化了问题。
import numpy as np
h = 330
n_rows = 4
w = 200
n_cols = 2
offset_x = w / n_cols
offset_y = h / n_rows
rectangles = []
for x in np.linspace(0, w, n_cols+1).tolist()[:-1]:
for y in np.linspace(0, h, n_rows+1).tolist()[:-1]:
x1 = int(round(x))
x2 = int(round(x + offset_x))
y1 = int(round(y))
y2 = int(round(y + offset_y))
rectangles.append([(x1, y1), (x1, y2), (x2, y2), (x2, y1)])
print(rectangles)
欢迎使用StackOverflow!
首先,您应该获取max_x
和max_y
值以了解应使用的边界。然后,您只需将这些界限划分为您的
def get_bounds(rec):
if len(rec) == 0:
return 0, 0
_max_x = rec[0][0]
_max_y = rec[0][1]
for x, y in rec:
if x > _max_x:
_max_x = x
if y > _max_y:
_max_y = y
return _max_x, _max_y
if __name__ == '__main__':
rec = [(0, 0), (0, 330), (200, 330), (200, 0)]
cols = 2
rows = 4
bounds = get_bounds(rec)
width_of_each_rect = bounds[0] / cols
height_of_each_rect = bounds[1] / rows
# define result array
result = [(0, 0)] * ((cols + 1) * (rows + 1))
i = 0
for c in range(cols + 1):
for r in range(rows + 1):
result[i] = (c * width_of_each_rect, r * height_of_each_rect)
i += 1
print result