从随机列出的边缘检测多边形

时间:2013-03-14 14:49:14

标签: algorithm geometry 2d computational-geometry

我有一个包含许多多边形边缘的矢量图。每个边缘由起点和终点表示。边缘之间的连接未明确指出。我需要从这些数据中提取多边形。显而易见的方法是获取每个边的一个顶点,搜索所有其他边以寻找匹配的顶点,并使用边的下一个顶点重复此操作,直到我有一个闭环。但这效率非常低。

有哪些好的算法可以提取多边形,只给出边缘的起点和终点,没有特定的顺序?

2 个答案:

答案 0 :(得分:2)

尝试类似这样的东西(python-pseudocode):

vertices = {} #map (x, y) coords to a list of all edges containing that vertex

for edge in edges:
    #add start & end vertices
    if edge.start not in vertices:
        vertices[edge.start] = []
    if edge.end not in vertices:
        vertices[edge.end] = []
    vertices[edge.start].append(edge)
    vertices[edge.end].append(edge)

现在你拥有了每个顶点的所有顶点和所有边。您现在可以为您的算法做最初的想法,但不必搜索匹配顶点的所有边,该查找是即时的。

答案 1 :(得分:1)

一种简单的方法是:

Sort the list of edges by end point. Call that array edges
Create a new array, polygon, size is num_edges 
edgeIndex = 0
copy edge from edges[0] to polygon[0]
count = 1
while (count < number_of_edges)
{
    starting_point = edges[edgeIndex].endpoint
    // do a binary search to find the segment that starts
    // at this edge's end point
    newIndex = binary_search(edges, starting_point)
    copy edge[newIndex] to polygon[count]
    ++count
    edgeIndex = newIndex
}

完成此操作后,polygon数组应按顺序包含边。

以上假设边缘点是合理输出的。也就是说,给定一个顶点为[(0,0),(10,10),(10,0)]'的三角形,边缘给出为:

{(0, 0), (10, 10)}
{(10, 10), (10, 0)}
{(10, 0), (0, 0)}

虽然不一定按顺序排列。如果给出第二条边是{(10, 0), (10, 10)}(即开始和结束相反),那么问题就更难了。

您可以使用哈希映射和直接查找执行相同的操作,这将比二进制搜索更快。

另请注意,这假设您不会有超过两条边连接到任何一个点。