How to use the ogr.GetDriverByName function in ogr

To help you get started, we’ve selected a few ogr examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nvkelso / thematic-carto-tools / Thematic / ogrinfo.py View on Github external
def getData( filename ):
    #print 'data_source: ', data_source, ' num_features: ', num_features
    
    in_dir = os.path.dirname( os.path.abspath( filename ) )    
    in_file_name_part = os.path.basename( os.path.abspath( filename ) )
    os.chdir( in_dir )
    
    # get the shapefile driver
    driver = ogr.GetDriverByName('ESRI Shapefile')
        
    # Checking the parameters.
    if isinstance( filename, str ):
        data_source = driver.Open( in_file_name_part, 0 )
        #data_source = Dataset(data_source)
    elif isinstance(data_source, DataSource):
        pass
    else:
        raise Exception('Data source parameter must be a string or a DataSource object.')
        
    if data_source is None:
        print 'Could not open file'
        sys.exit(1)
        
    return data_source
github npolar / RemoteSensing / CryoClim / GlacierSurfaceType.py View on Github external
'''
    (infilepath, infilename) = os.path.split(infile)             #get path and filename seperately
    (infileshortname, extension) = os.path.splitext(infilename)
    outfile = infilepath + '/' + infileshortname + '.shp'    
    
    (inshapefilepath, inshapefilename) = os.path.split(inshapefile)             #get path and filename seperately
    (inshapefileshortname, inshapeextension) = os.path.splitext(inshapefilename)
    
    glaciername = inshapefileshortname[:-11]
    quality = 1 # Set 1 to 6 for quality
    
    print '\n Convert ', infile, ' to shapefile.'
    os.system('gdal_polygonize.py ' + infile + ' -f "ESRI Shapefile" ' + outfile + ' GST')    
    
    #Add glaciername
    driver = ogr.GetDriverByName('ESRI Shapefile')
    indataset = driver.Open(outfile, 1)
    if indataset is None:
        print ' Could not open file'
        sys.exit(1)
    inlayer = indataset.GetLayer()
    
    fieldDefn = ogr.FieldDefn( 'glacier', ogr.OFTString)
    fieldDefn.SetWidth(20)
    inlayer.CreateField(fieldDefn)
    
    fieldDefn2 = ogr.FieldDefn('quality', ogr.OFTInteger)
    inlayer.CreateField(fieldDefn2)
    
    feature = inlayer.GetNextFeature()
    while feature:
        feature.SetField('glacier', glaciername )
github npolar / RemoteSensing / MetIceCharts / IceChartProcessing.py View on Github external
#Individual Corner Coordinates
    upperleft_x = location[0]        
    upperleft_y = location[1]     
    lowerright_x =location[2]    
    lowerright_y =location[3]  

    #Calculate columns and rows of raster based on corners and resolution    
    x_cols = int((lowerright_x - upperleft_x) / x_resolution )
    y_rows = int((lowerright_y - upperleft_y) / y_resolution)

    #Create raster with values defined above
    driver = gdal.GetDriverByName('GTiff')
    outfile = driver.Create(outraster, x_cols, y_rows, 1, gdal.GDT_Float64)    
    
    #Get Projection from reprshapefile
    driver = ogr.GetDriverByName('ESRI Shapefile')    
    temp = driver.Open( reprshapefile, 0)
    layer = temp.GetLayer()
    reference = layer.GetSpatialRef()
    projection = reference.ExportToWkt()
    
    #Set Projection of raster file
    outfile.SetGeoTransform([upperleft_x, x_resolution, 0.0, upperleft_y, 0.0, y_resolution])
    outfile.SetProjection(projection)
    
    #Close reprshapefile
    temp.Destroy
    
    #Fill raster with zeros
    rows = outfile.RasterYSize
    cols = outfile.RasterXSize
    raster = numpy.zeros((rows, cols), numpy.float)
github clcr / pyeo / pyeo / validation.py View on Github external
def save_point_list_to_shapefile(class_sample_point_dict, out_path, geotransform, projection_wkt, produce_csv=False):
    """Saves a list of points to a shapefile at out_path. Need the gt and projection of the raster.
    GT is needed to move each point to the centre of the pixel. Can also produce a .csv file for CoolEarth"""
    log = logging.getLogger(__name__)
    log.info("Saving point list to shapefile")
    log.debug("GT: {}\nProjection: {}".format(geotransform, projection_wkt))
    driver = ogr.GetDriverByName("ESRI Shapefile")
    data_source = driver.CreateDataSource(out_path)
    srs = osr.SpatialReference()
    srs.ImportFromWkt(projection_wkt)
    layer = data_source.CreateLayer("validation_points", srs, ogr.wkbPoint)
    class_field = ogr.FieldDefn("class", ogr.OFTString)
    class_field.SetWidth(24)
    layer.CreateField(class_field)

    for map_class, point_list in class_sample_point_dict.items():
        for point in point_list:
            feature = ogr.Feature(layer.GetLayerDefn())
            coord = pyeo.coordinate_manipulation.pixel_to_point_coordinates(point, geotransform)
            offset = geotransform[1]/2   # Adds half a pixel offset so points end up in the center of pixels
            wkt = "POINT({} {})".format(coord[0]+offset, coord[1]-offset) # Never forget about negative y values in gts.
            new_point = ogr.CreateGeometryFromWkt(wkt)
            feature.SetGeometry(new_point)
github maxerickson / osm_ms_buildings / newbuildings.py View on Github external
parser = argparse.ArgumentParser(description='Add height tag to OSM buildings that overlap with Microsoft buildings.')
    parser.add_argument('osmxml', type=str,
                        help='OSM XML file containing buildings')
    parser.add_argument('shp', type=str,
                        help='Shapefile containing buildings')
    parser.add_argument('outfile', type=str,
                        help='Name for new buildings file')
    return parser

if __name__=="__main__":
    ap=make_parser()
    args=ap.parse_args()

    #open input layers
    shpdriver = ogr.GetDriverByName('ESRI Shapefile')
    osmdriver=ogr.GetDriverByName('OSM')

    osm=osmdriver.Open(args.osmxml)
    osmbuildings = osm.GetLayer('multipolygons')

    # copy osm layer to memory, to enable spatial filtering
    memdriver=ogr.GetDriverByName('MEMORY')
    memsource=memdriver.CreateDataSource('memData')
    tmp= memdriver.Open('memData',1)
    osmbuildings=memsource.CopyLayer(osmbuildings,'buildings',['OVERWRITE=YES'])

    print('OSM:',osmbuildings.GetFeatureCount())

    ms=shpdriver.Open(args.shp)
    msbuildings=ms.GetLayer()
    print('MS:',msbuildings.GetFeatureCount())
github plstcharles / thelper / thelper / data / geo / ogc.py View on Github external
if not intersection.is_empty:
            # subtract bbox region from feature if intersection found (leftovers at end will be 'rivers')
            hydro_feat["geometry"] = hydro_feat["geometry"].difference(detect_roi)
    logger.debug("running river cleanup loop...")
    for hydro_feat in tqdm.tqdm(hydro_geoms, desc="appending leftover geometries as rivers"):
        if not hydro_feat["geometry"].is_empty:
            # remark: hydro features outside the original ROI will appear as rivers despite never being processed
            hydro_feat["properties"]["TYPECE"] = TB15D104.TYPECE_RIVER
            append_poly(hydro_feat["geometry"], copy.deepcopy(hydro_feat["properties"]), srs_transform)
    logger.debug("exporting final geojson...")
    with open(output_file, "w") as fd:
        out_srs = final_srs if final_srs is not None else bboxes_srs
        fd.write(geo.utils.export_geojson_with_crs([o[0] for o in output_features], srs_target=out_srs))
    if write_shapefile_copy:
        logger.debug("exporting final shapefile...")
        driver = ogr.GetDriverByName("ESRI Shapefile")
        data_source = driver.CreateDataSource(output_file + ".shp")
        layer = data_source.CreateLayer("lakes", final_srs if final_srs is not None else bboxes_srs, ogr.wkbPolygon)
        for feat_tuple in output_features:
            feature = ogr.Feature(layer.GetLayerDefn())
            point = ogr.CreateGeometryFromWkt(feat_tuple[1].wkt)
            feature.SetGeometry(point)
            layer.CreateFeature(feature)
            feature = None  # noqa # flush
        data_source = None  # noqa # flush
github FloodRiskGroup / floodrisk / caricadati / CaricaGeodatiFloodRisk.py View on Github external
NameField, TypeField = CampiTabella(Tabella)
        # do not load OBJECTID field
        if 'OBJECTID' in NameField:
            indiceid=NameField.index('OBJECTID')
            NameField.remove('OBJECTID')
            TypeField.remove(TypeField[indiceid])

        NumFields=len(NameField)
        Null='Null'
        TipoGeom, ColGeom=GeomColumn(TypeField,NameField)
        try:
            CodTipoGeom=dic_type[TipoGeom]
        except:
            CodTipoGeom=0

        driver = ogr.GetDriverByName('ESRI Shapefile')

        # open input file
        inDS = driver.Open(fn, 0)
        if inDS is None:
            errMsg='Could not open ' + fn
            NotErr=bool()
            return NotErr, errMsg

        # open layer for reading
        Inlayer = inDS.GetLayer()
        numFeatures = Inlayer.GetFeatureCount()
        # looking for the code of the reference system
        spatialRef = Inlayer.GetSpatialRef()
        spatialRef.AutoIdentifyEPSG()
        NumEPSG= spatialRef.GetAuthorityCode(None)
        if NumEPSG==None:
github FloodRiskGroup / floodrisk / calcolorischiopopolazione / AssessConsequencesPopulation.py View on Github external
PAR2 = outband2.ReadAsArray(0, 0, cols, rows).astype(numpy.float32)
    n2=PAR2.sum()
    # resetting the indices of the cells not affected
    TotalPopulationatRisk1= numpy.choose(mask_not_wet,(PAR1,0))  # residential pop
    TotalPopulationatRisk2= numpy.choose(mask_not_wet,(PAR2,0))  # seasonal pop
    POP=[]
    POP.append(TotalPopulationatRisk1)
    POP.append(TotalPopulationatRisk2)

    outDS.Destroy()

    # ================================
    # creates the map of warning Time
    # ================================

    driver = ogr.GetDriverByName('ESRI Shapefile')

    # file input
    fn=NomeFileWornTime
    inDS = driver.Open(fn, 0)
    if inDS is None:
        errMsg ='Could not open ' + fn
        #exit with an error code
        NotErr=bool()
        return NotErr, errMsg
    # open the layer for reading
    Inlayer = inDS.GetLayer()
    numFeatures = Inlayer.GetFeatureCount()
    # Get reference system
    spatialRef = Inlayer.GetSpatialRef()
    spatialRef.AutoIdentifyEPSG()
    NumEPSG= spatialRef.GetAuthorityCode(None)
github sourcepole / ogrtools / ogrtools / pyogr / ogrds.py View on Github external
def open(self, format, ds):
        driver = ogr.GetDriverByName(format)
        self.ds = driver.CreateDataSource(ds)
        return self.ds
github GeoscienceAustralia / anuga_core / source / anuga / utilities / spatialInputUtil.py View on Github external
def readShpPtsAndAttributes(shapefile):
        """
            Read a point shapefile with an attribute table into a list
    
            INPUT: shapefile -- name of shapefile to read
            
            OUTPUT: List with 
            [ list_of_points, list_of_attributes, names_of_attributes]
        """
        
        driver=ogr.GetDriverByName("ESRI Shapefile")
        dataSrc=driver.Open(shapefile, 0)
        #dataSrc=ogr.Open(shapefile)
        layer=dataSrc.GetLayer()
    
        pts=[]
        attribute=[]
        for i, feature in enumerate(layer):
            if(i==0):
                attributeNames=feature.keys()
            pt=feature.GetGeometryRef().GetPoints()
            pt=[list(p) for p in pt]
            pts.extend(pt)
            att=[feature[i] for i in attributeNames]
            attribute.extend(att)
    
        return [pts, attribute, attributeNames]