我正在尝试安排线段以使用 python 创建一个封闭的多边形。目前我已经设法解决了它但是当段数增加时真的很慢(它就像冒泡排序但对于段的终点)。我附上 sample file坐标(真实的坐标确实很复杂,但对于测试目的很有用)。该文件包含两个 separetes 封闭多边形的线段坐标。下图是我附加的坐标的结果。
这是我加入分割市场的代码。文件“Curve”在上面的保管箱链接中:
from ast import literal_eval as make_tuple
from random import shuffle
from Curve import Point, Curve, Segment
def loadFile():
print 'Loading File'
file = open('myFiles/coordinates.txt','r')
for line in file:
pairs.append(make_tuple(line))
file.close()
def sortSegment(segPairs):
polygons = []
segments = segPairs
while (len(segments) > 0):
counter = 0
closedCurve = Curve(Point(segments[0][0][0], segments[0][0][1]), Point(segments[0][1][0], segments[0][1][1]))
segments.remove(segments[0])
still = True
while (still):
startpnt = Point(segments[counter][0][0], segments[counter][0][1])
endpnt = Point(segments[counter][1][0], segments[counter][1][1])
seg = Segment(startpnt, endpnt)
val= closedCurve.isAppendable(seg)
if(closedCurve.isAppendable(seg)):
if(closedCurve.isClosed(seg)):
still =False
polygons.append(closedCurve.vertex)
segments.remove(segments[counter])
else:
closedCurve.appendSegment(Segment(Point(segments[counter][0][0], segments[counter][0][1]), Point(segments[counter][1][0], segments[counter][1][1])))
segments.remove(segments[counter])
counter = 0
else:
counter+=1
if(len(segments)<=counter):
counter = 0
return polygons
def toTupleList(list):
curveList = []
for curve in list:
pointList = []
for point in curve:
pointList.append((point.x,point.y))
curveList.append(pointList)
return curveList
def convertPolyToPath(polyList):
path = []
for curves in polyList:
curves.insert(1, 'L')
curves.insert(0, 'M')
curves.append('z')
path = path + curves
return path
if __name__ == '__main__':
pairs =[]
loadFile();
polygons = sortSegment(pairs)
polygons = toTupleList(polygons)
polygons = convertPolyToPath(polygons)
最佳答案
假设您只是在寻找方法而不是代码,这就是我尝试的方法。
当您从文件中读取线段坐标时,不断将坐标添加到字典中,线段的一个坐标(字符串形式)作为键,另一个坐标作为值。最后,它应该是这样的:
{
'5,-1': '5,-2',
'4,-2': '4,-3',
'5,-2': '4,-2',
...
}
现在从这个字典中选择任何键值对。接下来,从字典中选择键与前一个键值对中的值相同的键值对。因此,如果第一个键值对是 '5,-1': '5,-2'
,接下来查找键 '5,-2'
,您将获取 '5,-2': '4,-2'
。接下来寻找键 '4,-2'
等等。
继续从字典中删除键值对,这样一旦一个多边形完成,您就可以检查是否还有剩余的元素,这意味着可能还有更多的多边形。
如果您也需要代码,请告诉我。
关于python - 连续排列线段组成多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43702768/