如何使用Shapely提取内部多边形坐标?

时间:2014-02-17 08:32:48

标签: python graph gis shapely fiona

我是Shapely的新手(但对此充满热情),最近我发现了一点路障。

我有一个我通过Fiona阅读的多边形shapefile。这个shapefile包含BOTH多边形和多边形项目,我需要为其中的所有坐标(即外部和/或内部)的每个特征构建一个数组。值得注意的是,两个多边形项目具有内环(并且它们是有效的)。

我似乎没有问题访问多边形/多边形的外部坐标......但是我没有为内部坐标拉动任何东西。

我需要在这里采用一种新方法(即LinearRings)......?

def convert_polygons(inFile):

    for polys in fiona.open(inFile):
        myShape = shape(polys['geometry'])
        exterior_poly = 0
        interior_poly = 0
        if isinstance(myShape, Polygon):
            print "yes, I am a polygon"
            # count how many points for each interior polygon
            try:
                interior_poly += len(myShape.interior.coords)
            except:
                pass
            # count how many points for each exterior polygon
            exterior_poly += len(myShape.exterior.coords)
            geomArray = asarray(myShape.exterior)
            print geomArray
            print "number of interior points in polygon " + str(interior_poly)
            print "number of exterior points in polygon " + str(exterior_poly)
        elif isinstance(myShape, MultiPolygon):
            print "yes, I am a MultiPolygon"
            # count how many points for each interior polygon
            try:
                interior_poly += len(myShape.interior.coords)
            except:
                pass
            try:
                # count how many points for each exterior polygon
                exterior_poly += len(myShape.exterior.coords)
            except:
                pass
            try:
                geomArray = asarray(myShape.interior)
            except:
                pass
            try:
                geomArray = asarray(myShape.exterior)
            except:
                pass
            print geomArray
            print "number of interior points in polygon " + str(interior_poly)
            print "number of exterior points in polygon " + str(exterior_poly)

1 个答案:

答案 0 :(得分:8)

内部和外部环的结构不同。对于任何多边形,总有1个外圈,内圈为零或更多。

因此,在查看几何体的结构时,exteriorLinearRing个对象,而interiors列表为零或更多{{1}对象。任何LinearRing对象都会有LinearRing,您可以将其切片以查看coords的坐标列表。

以下是一个函数,它返回外部和内部坐标列表的字典:

coords[:]

E.g:

def extract_poly_coords(geom):
    if geom.type == 'Polygon':
        exterior_coords = geom.exterior.coords[:]
        interior_coords = []
        for interior in geom.interiors:
            interior_coords += interior.coords[:]
    elif geom.type == 'MultiPolygon':
        exterior_coords = []
        interior_coords = []
        for part in geom:
            epc = extract_poly_coords(part)  # Recursive call
            exterior_coords += epc['exterior_coords']
            interior_coords += epc['interior_coords']
    else:
        raise ValueError('Unhandled geometry type: ' + repr(geom.type))
    return {'exterior_coords': exterior_coords,
            'interior_coords': interior_coords}