2012-11-22 241 views
3

首先,我很抱歉發佈這個簡單的問題。我需要計算一定數量的gemotrical屬性(area,perimeters,Roundess,主軸和副軸等)。我正在使用GDAL/OGR來讀取我的多邊形的shapefile格式。我想問的是:Python如何使用osgeo.ogr.Geometry對象計算多邊形的周長

  1. 有沒有一種方法來計算使用osgeo.ogr.Geometry的周長?
  2. 是否有一個模塊構建來計算多邊形上的度量?

在此先感謝

import osgeo.gdal, ogr 
    poly="C:\\\myshape.shp" 
    shp = osgeo.ogr.Open(poly) 
    layer = shp.GetLayer() 
    # For every polygon 
    for index in xrange(len(allFID)): 
     feature = layer.GetFeature(index) 
     # get "FID" (Feature ID) 
     FID = str(feature.GetFID()) 
     geometry = feature.GetGeometryRef() 
     # get the area 
     Area = geometry.GetArea() 
+0

你解決了這個問題嗎?我對這個解決方案也很感興趣。 (在我的情況下,我需要計算幾何的周長)。 – hbobenicio

+1

嘿hbobenicio。我使用幾何中的點來計算周長,從shapely.geometry import Polygon –

+1

@hbobenicio下你可以看到我的解決方案def「edges_index」。 –

回答

2
poly = [(0,10),(10,10),(10,0),(0,0)] 


def segments(poly): 
     """A sequence of (x,y) numeric coordinates pairs """ 
     return zip(poly, poly[1:] + [poly[0]]) 

def area(poly): 
    """A sequence of (x,y) numeric coordinates pairs """ 
    return 0.5 * abs(sum(x0*y1 - x1*y0 
     for ((x0, y0), (x1, y1)) in segments(poly))) 

def perimeter(poly): 
    """A sequence of (x,y) numeric coordinates pairs """ 
    return abs(sum(math.hypot(x0-x1,y0-y1) for ((x0, y0), (x1, y1)) in segments(poly))) 
3
 ref_geometry = ref_feature.GetGeometryRef() 
     pts = ref_geometry.GetGeometryRef(0) 
     points = [] 
     for p in xrange(pts.GetPointCount()): 
      points.append((pts.GetX(p), pts.GetY(p))) 

def edges_index(points): 
    """ 
    compute edges index for a given 2D point set 

    1- The number of edges which form the polygon 
    2- Perimeter 
    3- The length of the longest edge in a polygon 
    4- The length of the shortest edge in a polygon 
    5- The average length of all of edges in a polygon 
    6- The lengths of edges deviate from their mean value 
    """ 
    Nedges = len(points)-1 
    length = [] 
    for i in xrange(Nedges): 
     ax, ay = points[i] 
     bx, by = points[i+1] 
     length.append(math.hypot(bx-ax, by-ay)) 
    edges_perimeter = numpy.sum(length) 
    edges_max = numpy.amax(length) 
    edges_min = numpy.amin(length) 
    edges_average = numpy.average(length) 
    edges_std = numpy.std(length) 
    return (Nedges,edges_perimeter,edges_max,edges_min,edges_average,edges_std) 
2

我可能會晚點就這一個,但我一直在尋找一個解決同樣的問題,我正好在這一個已經偶然。我通過簡單地找到幾何的邊界然後找到邊界的長度來解決問題。下面的示例Python代碼:

perimeter = feat.GetGeometryRef().Boundary().Length()