merge_shapefiles.py 2.72 KB
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import os.path as op
import ogr


def merge_shapefiles(in_shp_list, class_list, out_shp):
    ''' 
    Create a merged shapefile
    The class_list should be in the same order than the in_shp_list 
    '''

    for k in range(len(in_shp_list)):
        in_shp = in_shp_list[k]
        current_class = class_list[k]

        inDriver = ogr.GetDriverByName("ESRI Shapefile")
        inDataSource = inDriver.Open(in_shp, 0)
        inLayer = inDataSource.GetLayer()
        
        srs = inLayer.GetSpatialRef()
        
        if k==0:
            # Save extent to a new Shapefile
            outDriver = ogr.GetDriverByName("ESRI Shapefile")
            # Remove output shapefile if it already exists
            if os.path.exists(out_shp):
                outDriver.DeleteDataSource(out_shp)

            # Create the output shapefile
            outDataSource = outDriver.CreateDataSource(out_shp)
            outLayer = outDataSource.CreateLayer("buff_layer", srs, geom_type=ogr.wkbPoint)

            # Add a class field
            classField = ogr.FieldDefn("class", ogr.OFTInteger)
            outLayer.CreateField(classField)
        
        # Create the feature and set values
        for point in inLayer:
            ingeom = point.GetGeometryRef()
            
            featureDefn = outLayer.GetLayerDefn()
            feature = ogr.Feature(featureDefn)
            feature.SetGeometry(ingeom)
            feature.SetField("class", current_class)
            outLayer.CreateFeature(feature)

        # Close DataSource
        inDataSource.Destroy()
    outDataSource.Destroy()    
    
    return


#~ def merge_all_types(mask_dir, out_shp):
    #~ ''' Merge all the shapefiles contained in mask_dir, if they 
    #~ obey a certain nomencalture
    #~ DEPRECATED : not use anymore
    #~ '''
    
    #~ in_shp_list = []
    #~ class_list = []
    #~ names_list = []
    #~ names = ["background", "low_clouds", "high_clouds", "shadows", "land", "water", "snow"]
    #~ classes = [1,2,3,4,5,6,7]
    
    #~ for k in range(len(names)):
        #~ if op.exists(op.join(mask_dir, (names[k] + '.shp'))):
            #~ in_shp_list.append(op.join(mask_dir, (names[k] + '.shp')))
            #~ names_list.append(names[k])
            #~ class_list.append(classes[k])
        
    #~ print(in_shp_list)
    #~ print(class_list)
    
    #~ merge_shapefiles(in_shp_list, class_list, out_shp)
        
    

    
def main():
    mask_dir = '/mnt/data/home/baetensl/classification_clouds/Data/Full_orleans/In_data/Masks/'
    
    out_shp = '/mnt/data/home/baetensl/classification_clouds/Data/Full_orleans/In_data/Masks/merged.shp'

    merge_all_types(mask_dir, out_shp)
        
if __name__ == '__main__':
    main()