我有一组 1x1 的多边形,每个都由其边界(一组四个点)定义,我在我的代码示例中使用以下函数 area() 来创建这些。我希望将相邻的正方形合并为单个多边形,该多边形也以其边界点的形式定义。
我希望通过粗暴的方法来实现这一目标,即首先添加两个相邻的 1x1 正方形,使用下面的函数 join() 来创建一个更大的多边形,并按照此方式继续增加多边形的大小。因此,join 的第一个参数是迄今为止的多边形,第二个参数是要添加到多边形中的相邻的 1x1 正方形。返回值是新多边形的边界,current 与新的 1x1 合并。
这是我目前的想法:
这给我带来了以下多边形(数字表示组成它的正方形添加顺序):
上面代码的输出结果是:
我希望通过粗暴的方法来实现这一目标,即首先添加两个相邻的 1x1 正方形,使用下面的函数 join() 来创建一个更大的多边形,并按照此方式继续增加多边形的大小。因此,join 的第一个参数是迄今为止的多边形,第二个参数是要添加到多边形中的相邻的 1x1 正方形。返回值是新多边形的边界,current 与新的 1x1 合并。
这是我目前的想法:
def join(current, new):
""" current is the polygon, new the 1*1 square being added to it"""
return get_non_touching_part_of_boundary(current, new) + get_non_touching_part_of_boundary(new, current)
def get_non_touching_part_of_boundary(this, other):
for i,point in enumerate(this):
if point not in other and this[i-1] in other:
break # start of non touching boundary from a clockwise perspective
non_touching_part_of_boundary = []
for point in this[i:] + this[:i]:
if not point in other:
non_touching_part_of_boundary.append(point)
return non_touching_part_of_boundary
def area(point):
""" boundary defined in a clockwise fashion """
return [point,(point[0],point[1]+1),(point[0]+1,point[1]+1),(point[0]+1,point[1])]
a = area((0,1)) # a assigned a 1*1 polygon
a = join(a, area((0,2))) # a assigned a 2*1 polygon
a = join(a, area((1,2)))
a = join(a, area((2,2)))
a = join(a, area((2,1)))
a = join(a, area((2,0)))
print(a)
这给我带来了以下多边形(数字表示组成它的正方形添加顺序):
234
1 5
6
上面代码的输出结果是:
[(2, 2), (1, 2), (1, 1), (0, 1), (0, 3), (3, 3), (3, 0), (2, 0)]
这是定义多边形边界所需的最小点数。
但是,如果我通过 a = join(a, area((1,0))) 添加一个正方形来创建一个洞,我的算法就会失败:
234
1 5
76
这是另一个我的算法无法处理的多边形:
123
64
5
有人能帮我吗?我希望将多边形中的孔单独列在一个列表中。
谢谢!