【问题标题】:Python - Check if Shapely Polygon is a rectanglePython - 检查 Shapely Polygon 是否为矩形
【发布时间】:2020-06-19 10:01:43
【问题描述】:

在Polygon上进行分割等操作后,我想验证它是一个矩形。
我试过simplify,然后计算coords的数量是否为5...

>>> from shapely.geometry import Polygon
>>> from shapely.ops import split
>>> 
>>> poly1 = Polygon([(0, 0), (0, 1), (0, 3), (2, 3), (2, 2), (2, 0), (0, 0)])
>>> 
>>> poly_check=poly1.simplify(0)
>>> if len(poly_check.exterior.coords)==5:
>>>     print 'Yes, it is a rectangle...'
>>> else:
>>>     print 'No, it is not a rectangle...'
>>> 
Yes, it is a rectangle...

但是如果起点在边的中间就不行了。

>>> #poly2 is actually a rectangle
>>> poly2 = Polygon([(0, 1), (0, 3), (2, 3), (2, 2), (2, 0), (0, 0), (0, 1)])
>>> 
>>> poly_check=poly2.simplify(0)
>>> if len(poly_check.exterior.coords)==5:
>>>     print 'Yes, it is a rectangle...'
>>> else:
>>>     print 'No, it is not a rectangle...'
>>> 
No, it is not a rectangle...

如何检查?

谢谢

【问题讨论】:

    标签: python polygon rectangles shapely


    【解决方案1】:

    如果多边形的面积与其最小有界矩形的面积相匹配,则多边形是一个矩形。这是一个已知的形状指标,称为矩形度。

    if poly.area == poly.minimum_rotated_rectangle.area:
        return True
    

    编辑:考虑到下面关于浮点错误的评论,您可以直接测量矩形并将 > .99 的所有内容视为矩形或进行近似比较(例如舍入)。

    if (poly.area / poly.minimum_rotated_rectangle.area) > .99:
        return True
    

    编辑 2:最好只使用 math.isclose 函数来确定两个变量的相等性。前面比较中的除法降低了比较的整体精度,我们在这里避免:

    import math
    
    if math.isclose(poly.minimum_rotated_rectangle.area, poly.area):
        return True
    

    【讨论】:

    • 知道一点匀称和浮点运算,这可能大致有效,因此== 可能既是假阴性又是假阳性
    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多