def __init__(self, fname):
ds = ogr.Open(fname)
assert ds is not None, "Couldn't open %s" % fname
layer = ds.GetLayer()
assert layer is not None
WGS84_SR = osr.SpatialReference()
WGS84_SR.ImportFromEPSG(4326)
shape_sr = osr.SpatialReference()
shape_sr.ImportFromWkt(layer.GetSpatialRef().ExportToWkt())
transform = osr.CoordinateTransformation(shape_sr, WGS84_SR)
# http://geoinformaticstutorial.blogspot.ch/2012/10/accessing-vertices-from-polygon-with.html
polygons = {}
for feature in layer:
attr = feature.items()
newattr = {}
# some attributes contains unicode character. ASCIIfy everything
# TODO: A bit brutal, but easy...
for k, v in attr.items():
newk = k.decode('ascii', errors='ignore')
newattr[newk] = v
attr = newattr
geometry = feature.GetGeometryRef()
assert geometry.GetGeometryName() == 'POLYGON'
# A ring is a polygon in shapefiles
ring = geometry.GetGeometryRef(0)
assert ring.GetGeometryName() == 'LINEARRING'
# The ring duplicates the last point, so for the polygon to be
# closed, last point should equal first point
npoints = ring.GetPointCount()
points = [ring.GetPoint(i) for i in xrange(npoints)]
points = [transform.TransformPoint(*p) for p in points]
# third column is elevation - discard
points = np.array(points)[:, :2]
# swap (lng, lat) to (lat, lng)
points = points[:, ::-1]
assert np.allclose(points[-1], points[0])
name = attr['name']
polygons[name] = points
self.polygons = polygons
评论列表
文章目录