python - Shapely的 `almost_equals`函数如何处理起点和错误?

标签 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)])

问题 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 中实现。

最佳答案

是的,这是预期的行为。 the documentation中没有明确说明但你可以在 docstring 中找到它功能:

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))

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

  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
    
  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
    

关于python - Shapely的 `almost_equals`函数如何处理起点和错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63402333/

相关文章:

python - 如何确定 Shapely LineString 是否复杂(即自相交)

python - 如何从模板中访问 Django 模型的 Enum?

python - 为每个列表项调用不同的函数

Python数组/矩阵维度

geolocation - 雪花查询以获取多边形内的数据

python - 找不到库 geos_c 或加载其任何变体

python - Pandas DataFrame.add() -- 忽略缺失的列

javascript - 多边形每边的中心

algorithm - 多边形裁剪 : Only "viewable" area

python - 如何在python中使用shapely计算重心?