[英]Python - Check if Shapely Polygon is a rectangle
在對多邊形進行拆分等操作后,我想驗證它是一個矩形。
我嘗試過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...
我怎樣才能檢查這個?
謝謝
如果多邊形的面積與其最小有界矩形的面積相匹配,則多邊形是一個矩形。 它是一種已知的形狀指標,稱為矩形度。
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 function 來確定兩個變量的相等性。 前面比較中的划分降低了比較的整體精度,我們在這里避免:
import math
if math.isclose(poly.minimum_rotated_rectangle.area, poly.area):
return True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.