您进行的测试(即比较每个顶点的顶点)有一个非常重要的约束:两个 LineString 中的顶点数量必须完全相同,这不太可能发生。
由于您显然想要一个非常基本、广泛的相似性检查,我将从比较您的线条的主要特征开始。您可以通过使用shapely
的几何属性来实现这一点,如以下不言自明的示例中所示:
def are_geometries_similar(geom1,geom2,MAX_ALLOWED_DISTANCE = 100,MAX_ALLOWED_DIFFERENCE_RATIO = 0.1):
"""
Function compares two linestrings' number of vertices, length and basic position.
If they pass all 3 tests within the specified margin of error, it returns true, otherwise it returns false.
"""
# 1. Compare length:
l1 = geom1.length
l2 = geom2.length
if not abs(float(l1) - l2)/max([l1,l2]) < MAX_ALLOWED_DIFFERENCE_RATIO:
return False
# 2. Compare number of vertices:
vert_num1 = len(geom1.coords)
vert_num2 = len(geom2.coords)
if not abs(float(vert_num1) - vert_num2)/max([vert_num1,vert_num2]) < MAX_ALLOWED_DIFFERENCE_RATIO:
return False
# 3. Compare position by calculating the representative point
rp1 = geom1.representative_point()
rp2 = geom2.representative_point()
if rp1.distance(rp2) > MAX_ALLOWED_DISTANCE:
return False
# If all tests passed, return True
return True