2012/08/22

geometry and python tips: How to load shapefile correctly using python?

Shapely provides an easy way to operate geometrical objects. However, shapely does not have good functionality for loading ESRI shapefile directly and formatting topologically complex geometry for making shapely's method arguments is tired work. Below code will solve this issue: combination of shapely.wkb.loads and osgeo library. To write this code, I referred here.
#!/usr/bin/env python
#coding: utf-8

import sys
import cPickle as pickle
import collections

from osgeo import ogr
from shapely.wkb import loads

def main():
    path_to_shp = argvs[1]
    path_to_out = argvs[2]

    d_fid2pol = get_d_fid2pol(path_to_shp)
    dump_object_to_file(d_fid2pol, path_to_out)

def get_d_fid2pol(path_to_shp):
    """
    :param path_to_shp: path to *.shp
    :type path_to_shp: string

    :returns: {fid: MultiPolygon(), ...}
    :rtype: dictionary
    """
    data = ogr.Open(path_to_shp)
    elements = data.GetLayer()
    return dict([get_fid_and_poly(element) for element in elements])

def get_fid_and_poly(element):
    """
    :param element: element of shapefile
    :type element: object

    :returns: {fid: MultiPolygon()}
    :rtype: element of dictionary
    """
    fid = element.GetField(0)
    poly = loads(element.GetGeometryRef().ExportToWkb())
    return (fid, poly)
    
def dump_object_to_file(obj, path_to_out):
    with open(path_to_out, 'wb') as F:
        pickle.dump(obj, F, -1)

if __name__ == "__main__":
    main()

No comments:

Post a Comment

100