Python如何使用osgeo.ogr.Geometry对象计算多边形周长

时间:2012-11-22 16:59:57

标签: python geometry computational-geometry

首先,我很抱歉发布这个简单的问题。我需要计算一定数量的宝石学属性(面积,周长,Roundess,长轴和短轴等)。我正在使用GDAL/OGR来读取多边形的shapefile格式。我想问的是:

  1. 是否有使用osgeo.ogr.Geometry计算周长的方法?
  2. 是否有用于计算多边形度量的模块构建?
  3. 提前致谢

        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()
    

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:3)

我可能会迟到这一点,但我正在寻找同一个问题的解决方案,我碰巧偶然发现了这个问题。我通过简单地找到几何的边界然后找到边界的长度来解决这个问题。示例Python代码如下:

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

答案 2 :(得分: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)))