que*_*tin 1 python polygon rectangles shapely
在对多边形进行分割等操作之后,我想验证它是否是一个矩形。
我试过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...
Run Code Online (Sandbox Code Playgroud)
但如果起点位于边缘的中间,则该方法不起作用。
>>> #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...
Run Code Online (Sandbox Code Playgroud)
我怎样才能检查这个?
谢谢
如果多边形的面积与其最小有界矩形的面积相匹配,则该多边形是矩形。它是称为矩形度的已知形状指标。
if poly.area == poly.minimum_rotated_rectangle.area:
return True
Run Code Online (Sandbox Code Playgroud)
编辑:考虑到下面有关浮点误差的评论,您可以直接测量矩形并将所有> .99 视为矩形或进行近似比较(例如舍入)。
if (poly.area / poly.minimum_rotated_rectangle.area) > .99:
return True
Run Code Online (Sandbox Code Playgroud)
编辑2:最好只使用 math.isclose 函数来确定两个变量的相等性。前面比较中的除法降低了比较的整体精度,我们在这里避免这种情况:
import math
if math.isclose(poly.minimum_rotated_rectangle.area, poly.area):
return True
Run Code Online (Sandbox Code Playgroud)