我正在研究一种算法,该算法可以在一张简单的黑白地图中分析大洲的形状,然后返回其周长的轮廓线。
一个例子如下:
[(1,0),(2,0),(2,1),(2,2),(3,2)...]
到目前为止,该算法产生了正确的列表,但是如您所见,它产生了冗余点。
在此示例中,第一个点之后的3个点形成一条直线,从2,0到2,2。 (2,1),冗余点,应该消除,但是我不确定如何。
仅供参考:我正在使用纯python应用程序,我使用的唯一库是pygame。我没有运气就调查了类似的问题。
最佳答案
如果我正确理解了您的信息,则如果前一个点与下一个点之间的距离与该点与其相邻点之间的距离之和相同,则该点为“冗余”。
代码(未经测试):
def diffVector(pointA, pointB):
# returns a vector representing the path to get from A to B
return (pointB[0] - pointA[0], pointB[1] - pointA[1])
def distSq(pointA, pointB):
# returns the square of the distance between two points
# (more efficient than actual distance, and works for our purposes)
diff = diffVector(pointA, pointB)
return diff[0] * diff[0] + diff[1] * diff[1]
def findRedundancy(points):
# returns a list of redundant point indexes to remove
redundant = []
# store the distance in a variable to avoid recalculating
prevSegmentDist = distSq(points[0], points[1])
for i, point in enumerate(points[1:-2]):
prev = points[i-1]
next = points[i+1]
nextSegmentDist = distSq(point, next)
# check if the combined distance is the same
# as the straight-line distance between prev and next
if distSq(prev, next) == prevSegmentDist + nextSegmentDist:
redundant.append(i)
prevSegmentDist = nextSegmentDist
return redundant
此算法将容易出现浮点错误,因此您应换出严格的
==
检查,而应检查数字是否彼此足够接近以致被视为“相同”。关于python - 删除一行中的多余点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59959454/