简体   繁体   English

Python - 检查 Shapely Polygon 是否为矩形

[英]Python - Check if Shapely Polygon is a rectangle

After operations like splitting on Polygon, I would like to verify that it is a rectangle.在对多边形进行拆分等操作后,我想验证它是一个矩形。
I have tried simplify and then counting if number of coords is 5...我尝试过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...

But it does not work if the starting point is in the middle of an edge.但是如果起点在边缘的中间,它就不起作用。

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

How can I check this?我怎样才能检查这个?

Thanks谢谢

Polygon is a rectangle if its area matches the area of its minimum bounded rectangle.如果多边形的面积与其最小有界矩形的面积相匹配,则多边形是一个矩形。 It is a known shape index called rectangularity.它是一种已知的形状指标,称为矩形度。

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

EDIT: Taking into account the comment about floating point error below, you can either measure rectangularity directly and consider everything >.99 as rectangle or make the approximate comparison (eg rounding).编辑:考虑到下面关于浮点错误的评论,您可以直接测量矩形并将 >.99 的所有内容视为矩形或进行近似比较(例如舍入)。

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

EDIT 2: It is better to just use math.isclose function to determine the equality of the two variables.编辑 2:最好只使用 math.isclose function 来确定两个变量的相等性。 The division in the previous comparison reduces the overall precision of the comparison, we avoid that here:前面比较中的划分降低了比较的整体精度,我们在这里避免:

import math

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM