How to use the ogr.Open 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 qgiscloud / qgis-cloud-plugin / qgiscloud / pyogr / ogr2ogr.py View on Github external
print("  ->  " + ogr.GetDriver(iDriver).GetName())

        return False

#/* -------------------------------------------------------------------- */
#/*      Try opening the output datasource as an existing, writable      */
#/* -------------------------------------------------------------------- */
    poODS = None
    poDriver = None

    if bUpdate:
        poODS = ogr.Open(pszDestDataSource, True)
        if poODS is None:

            if bOverwrite or bAppend:
                poODS = ogr.Open(pszDestDataSource, False)
                if poODS is None:
                    # /* ok the datasource doesn't exist at all */
                    bUpdate = False
                else:
                    poODS.delete()
                    poODS = None

            if bUpdate:
                print("FAILURE:\n" + 
                        "Unable to open existing output datasource `%s'." % pszDestDataSource)
                return False

        elif len(papszDSCO) > 0:
            print("WARNING: Datasource creation options ignored since an existing datasource\n" + \
                    "         being updated.")
github Kitware / Danesfield / contrib / test_clustering.py View on Github external
gt = sourceImage.GetGeoTransform() # captures origin and pixel size
print('Origin:', (gt[0], gt[3]))
print('Pixel size:', (gt[1], gt[5]))

left = gdal.ApplyGeoTransform(gt,0,0)[0]
top = gdal.ApplyGeoTransform(gt,0,0)[1]
right = gdal.ApplyGeoTransform(gt,sourceImage.RasterXSize,sourceImage.RasterYSize)[0]
bottom = gdal.ApplyGeoTransform(gt,sourceImage.RasterXSize,sourceImage.RasterYSize)[1]

model = {}
model['corners'] = [left, top, right, bottom]
model['project_model'] = gt 
model['scale'] = scale

ds = ogr.Open(args.input_osm)
layer = ds.GetLayerByIndex(3)
nameList = []

building_list = []
for feature in layer:
    if feature.GetField("building") != None:  # only buildings
        flag = True
        #print("haha")
        name = feature.GetField("name")
        geom = feature.GetGeometryRef()
        g = geom.GetGeometryRef(0)
        for shape_idx in range(g.GetGeometryCount()):
            polygon = g.GetGeometryRef(shape_idx)
            for i in range(0, polygon.GetPointCount()):
                pt = polygon.GetPoint(i)
                #print(pt[0],pt[1])
github iocast / featureserver / featureserver / datasource / OGR.py View on Github external
def __init__(self, name, writable = 0, lockfile = 0, 
                 dsn = None, layer = None, attribute_cols = '', **args):
        DataSource.__init__(self, name, **args)
        if int(writable) and lockfile: 
            self.lock = Lock(lockfile)
        else:
            self.lock = None
        self.ds     = ogr.Open( dsn, int(writable) )
        if layer:
            self.layer  = self.ds.GetLayerByName(layer)
        else:
            self.layer  = self.ds.GetLayer(0)
        self.defn   = self.layer.GetLayerDefn()
        self.fields = [self.defn.GetFieldDefn(i)
                        for i in range(self.defn.GetFieldCount())]
        if attribute_cols:
            self.attribute_cols = [x.lower() for x in attribute_cols.split(',')]
        else:
            self.attribute_cols = None
github openstreams / wflow / wflow-py / Scripts / wtools_py / CreateGrid.py View on Github external
if cellsize == None:
        print 'cell-size (-c) is not specified'
        Usage()
        sys.exit(1)
    
    ''' delete existing files '''
    if os.path.isdir('mask'):
        shutil.rmtree('mask')
    os.makedirs('mask')
    
    if not inputfile == None:
        fileext = os.path.splitext(os.path.basename(inputfile))[1]
        if fileext == '.shp':
            '''ds openen als shape-file'''
            file_att = os.path.splitext(os.path.basename(inputfile))[0]
            ds = ogr.Open(inputfile)
            '''read extent'''
            lyr = ds.GetLayerByName(file_att)
            extent = lyr.GetExtent()
            extent_in = [extent[0],extent[2],extent[1],extent[3]]
            spatialref = lyr.GetSpatialRef()
            if not spatialref == None:
                srs = osr.SpatialReference()
                srs.ImportFromWkt(spatialref.ExportToWkt())
                proj = spatialref.GetUTMZone()
                Projection = True
                zone = str(abs(proj))
                if str(proj)[0] == '-':
                    hemisphere = 'S'
                else: hemisphere = 'N'
                geodatum = 'UTM' + zone + hemisphere
                if proj == 0:
github andrewxhill / MOL / utilities / metadata / wdpa.py View on Github external
def newMetadata(f):
    wdpaid = f.replace('.shp','')
    out = NewProtectedArea()
    out.source = "IUCN and UNEP"
    out.type = "Protected Area"
    out.location = "/ftp/pa/shp/%s.shp" % wdpaid
    out.format = "Esri Shapefile"
    out.geoFormat = "vector"
    out.geoType = "multipolygon"
    out.newVariable('wdpaid', wdpaid)
    
    ds = ogr.Open ( f )
    lyr = ds.GetLayerByName( wdpaid )
    feat_def = lyr.GetLayerDefn()
    
    name, country, category, designation, govn_type, marine = None, None, None, None, None, None
    for feat in lyr:
        if name is None:
            name = feat.GetField('NAME_ENG')
        if country is None:
            country = feat.GetField('COUNTRY')
        if category is None:
            category = feat.GetField('IUCNCAT')
        if designation is None:
            designation = feat.GetField('DESIG_ENG')
        if govn_type is None:
            govn_type = feat.GetField('GOVN_TYPE')
        if marine is None:
github Martin-Jung / LecoS / lecos_sextantealgorithms.py View on Github external
v = Processing.getObject(point)
        cr1 = v.crs()
        cr2 = r.crs()
        if cr1!=cr2:
            raise GeoAlgorithmExecutionException("Make sure Point and Raster layer have the same projection")

        # Use GDAL to open the raster
        raster = gdal.Open(str(inputFilename))
        nodata = lcs.f_returnNoDataValue(str(inputFilename)) # Get Nodata-value
        geotransform = raster.GetGeoTransform() # Get geotransform
        rproj = raster.GetProjection()
        classes, array = lcs.f_landcover(str(inputFilename)) # Get array from band 1
        raster = None # close gdal
        
        # Vector loading
        ds = ogr.Open(point)
        lyr = ds.GetLayer()
        res = []
        for feat in lyr:
            geom = feat.GetGeometryRef()
            mx,my= geom.GetX(), geom.GetY()  #coord in map units                
            
            pp = self.mapToPixel(geotransform, mx,my)
            
            x = int(pp[0])
            y = int(pp[1])
        
            if x < 0 or y < 0 or x >= array.shape[1] or y >= array.shape[0]:
                raise GeoAlgorithmExecutionException("Point could not be queried or outside raster")

            res.append((feat.GetFID(),array[y, x]))
github UDST / spandex / spandex / io.py View on Github external
Uses OGR's ESRI Shapefile driver to read records from the file.

    Parameters
    ----------
    path : str
        File path to the dBase/xBase file.

    Returns
    -------
    df : pandas.DataFrame

    """
    import ogr

    # Open the file and collect information on fields.
    dbf = ogr.Open(path)
    table = dbf.GetLayer()
    header = table.GetLayerDefn()
    ncolumns = header.GetFieldCount()
    column_names = [header.GetFieldDefn(i).GetName() for i in range(ncolumns)]
    column_types = [header.GetFieldDefn(i).GetType() for i in range(ncolumns)]

    def read(row, i):
        """Return i-th field of a record."""
        # For performance, use the appropriate field type function.
        fld_type = column_types[i]
        if fld_type == ogr.OFTInteger:
            return row.GetFieldAsInteger(i)
        elif fld_type == ogr.OFTReal:
            return row.GetFieldAsDouble(i)
        elif fld_type == ogr.OFTStringList:
            return row.GetFieldAsStringList(i)
github OSGeo / gdal / pymod / samples / vec_tr.py View on Github external
elif layer_name is None:
        layer_name = arg

    else:
	Usage()

    i = i + 1

if outfile is None:
    Usage()

#############################################################################
# Open the datasource to operate on.

in_ds = ogr.Open( infile, update = 0 )

if layer_name is not None:
    in_layer = in_ds.GetLayerByName( layer_name )
else:
    in_layer = in_ds.GetLayer( 0 )

in_defn = in_layer.GetLayerDefn()

#############################################################################
#	Create output file with similar information.

shp_driver = ogr.GetDriverByName( 'ESRI Shapefile' )
shp_driver.DeleteDataSource( outfile )

shp_ds = shp_driver.CreateDataSource( outfile )
github mikeqfu / pydriosm / pydriosm / read_GeoFabrik.py View on Github external
'other_relations'   - 4: "relation" features that do not belong to the above 2 layers

    Note that this function can require fairly high amount of physical memory to read large files e.g. > 200MB

    Reference: http://www.gdal.org/drv_osm.html

    Example:
        path_to_osm_pbf = cd("test_read_GeoFabrik\\rutland-latest.osm.pbf")
        chunks_no       = 50
        parsed          = True
        fmt_other_tags  = True
        fmt_single_geom = True
        fmt_multi_geom  = True
        parse_osm_pbf(path_to_osm_pbf, chunks_no, parsed, fmt_other_tags, fmt_single_geom, fmt_multi_geom)
    """
    raw_osm_pbf = ogr.Open(path_to_osm_pbf)
    # Grab available layers in file: points, lines, multilinestrings, multipolygons, & other_relations
    layer_names, all_layer_data = [], []
    # Parse the data feature by feature
    layer_count = raw_osm_pbf.GetLayerCount()

    # Loop through all available layers
    for i in range(layer_count):
        # Get the data and name of the i-th layer
        layer = raw_osm_pbf.GetLayerByIndex(i)
        layer_name = layer.GetName()

        layer_names.append(layer_name)

        if chunks_no:
            features = [feature for _, feature in enumerate(layer)]
            # chunks_no = file_size_in_mb / file_size_limit; chunk_size = len(features) / chunks_no
github gltn / stdm / data / importexport / reader.py View on Github external
def __init__(self, source_file):
        self._ds = ogr.Open(source_file)
        self._targetGeomColSRID = -1
        self._geomType = ''
        self._dbSession = STDMDb.instance().session
        self._mapped_cls = None
        self._mapped_doc_cls = None
        self._current_profile = current_profile()
        self._source_doc_manager = None