Shapely的almost_equals函数如何处理起点和误差?

ZL-*_*tic 3 python polygon shapely

以下是具有相同点集但起点/舍入误差不同但方向仍然相同的多边形。

poly1 = Polygon([(0,0),(0,1),(1,1),(1,0)])
poly2 = Polygon([(0,1),(1,1),(1,0),(0,0)])
poly3 = Polygon([(0,1),(1,1.00000001),(1,0),(0,0)])
poly4 = Polygon([(0,0),(0,1),(1,1.00000001),(1,0)])
Run Code Online (Sandbox Code Playgroud)

问题1:poly1.almost_equals(poly2)返回Falsepoly1.equals(poly2)返回True。所以equals可以处理不同的起点但almost_equals不能。

问题2:poly1.almost_equals(poly3)返回Falsepoly1.almost_equals(poly4)返回True。因此almost_equals可以处理舍入误差,但起点仍然不同。

这是almost_equals函数应该表现的方式吗?我认为具有不同起点的多边形仍然是相同的多边形,应该如此对待。有方便的方法来解决这个问题吗?我有一个复杂的自定义解决方案,但我想知道这样的操作是否已在 Shapely 中实现。

Geo*_*rgy 5

是的,这是预期的行为。文档中没有明确说明,但您可以在函数的文档字符串中找到它:

def almost_equals(self, other, decimal=6):
    """Returns True if geometries are equal at all coordinates to a
    specified decimal place

    Refers to approximate coordinate equality, which requires coordinates be
    approximately equal and in the same order for all components of a geometry.
    """
    return self.equals_exact(other, 0.5 * 10**(-decimal))
Run Code Online (Sandbox Code Playgroud)

目前,没有任何其他功能可以用来解决您的问题。GitHub 上有一个未解决的问题almost_equals,其中讨论了的未来。因此,可能很快就会推出新的便捷功能。同时,您可以使用多种解决方法:

  1. 计算symmetric_difference两个多边形并将结果面积与某个最小阈值进行比较。
    例如:
    def almost_equals(polygon, other, threshold):
        # or (polygon ^ other).area < threshold
        return polygon.symmetric_difference(other).area < threshold
    
    almost_equals(poly1, poly3, 1e-6)  # True
    
    Run Code Online (Sandbox Code Playgroud)
  2. 首先对两个多边形进行标准化,然后使用almost_equals. 例如,要对它们进行标准化,您可以orient逆时针排列边界的顶点,然后对顶点进行排序,以便与其他顶点相比,每个多边形的第一个顶点将是最低且最左边的。
    例如:
    from shapely.geometry.polygon import orient
    
    
    def normalize(polygon):
    
        def normalize_ring(ring):
            coords = ring.coords[:-1]
            start_index = min(range(len(coords)), key=coords.__getitem__)
            return coords[start_index:] + coords[:start_index]
    
        polygon = orient(polygon)
        normalized_exterior = normalize_ring(polygon.exterior)
        normalized_interiors = list(map(normalize_ring, polygon.interiors))
        return Polygon(normalized_exterior, normalized_interiors)
    
    
    normalize(poly1).almost_equals(normalize(poly3))  # True
    
    Run Code Online (Sandbox Code Playgroud)