Python osgeo.ogr.Feature() Examples
The following are 21
code examples of osgeo.ogr.Feature().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
osgeo.ogr
, or try the search function
.
Example #1
Source File: lsma.py From unmixing with MIT License | 6 votes |
def get_idx_as_shp(self, path, gt, wkt): ''' Exports a Shapefile containing the locations of the extracted endmembers. Assumes the coordinates are in decimal degrees. ''' coords = pixel_to_xy(self.get_idx(), gt=gt, wkt=wkt, dd=True) driver = ogr.GetDriverByName('ESRI Shapefile') ds = driver.CreateDataSource(path) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) layer = ds.CreateLayer(path.split('.')[0], srs, ogr.wkbPoint) for pair in coords: feature = ogr.Feature(layer.GetLayerDefn()) # Create the point from the Well Known Text point = ogr.CreateGeometryFromWkt('POINT(%f %f)' % pair) feature.SetGeometry(point) # Set the feature geometry layer.CreateFeature(feature) # Create the feature in the layer feature.Destroy() # Destroy the feature to free resources # Destroy the data source to free resources ds.Destroy()
Example #2
Source File: shapefileDb.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def insertFrame(self, scale, mi, inom, frame): self.checkAndOpenDb() srid = self.findEPSG() geoSrid = QgsCoordinateReferenceSystem(int(srid)).geographicCRSAuthId().split(':')[-1] ogr.UseExceptions() outputDS = self.buildOgrDatabase() outputLayer=outputDS.GetLayerByName(self.getFrameLayerName()) newFeat=ogr.Feature(outputLayer.GetLayerDefn()) auxGeom = ogr.CreateGeometryFromWkb(frame) #set geographic srid from frame geoSrs = ogr.osr.SpatialReference() geoSrs.ImportFromEPSG(int(geoSrid)) auxGeom.AssignSpatialReference(geoSrs) #reproject geom outSpatialRef = outputLayer.GetSpatialRef() coordTrans = osr.CoordinateTransformation(geoSrs, outSpatialRef) auxGeom.Transform(coordTrans) newFeat.SetGeometry(auxGeom) newFeat.SetField('mi', mi) newFeat.SetField('inom', inom) newFeat.SetField('escala', str(scale)) out=outputLayer.CreateFeature(newFeat) outputDS.Destroy()
Example #3
Source File: spatialiteDb.py From DsgTools with GNU General Public License v2.0 | 6 votes |
def insertFrame(self, scale, mi, inom, frame): self.checkAndOpenDb() srid = self.findEPSG() geoSrid = QgsCoordinateReferenceSystem(int(srid)).geographicCRSAuthId().split(':')[-1] ogr.UseExceptions() outputDS = self.buildOgrDatabase() outputLayer=outputDS.GetLayerByName('public_aux_moldura_a') newFeat=ogr.Feature(outputLayer.GetLayerDefn()) auxGeom = ogr.CreateGeometryFromWkb(frame) #set geographic srid from frame geoSrs = ogr.osr.SpatialReference() geoSrs.ImportFromEPSG(int(geoSrid)) auxGeom.AssignSpatialReference(geoSrs) #reproject geom outSpatialRef = outputLayer.GetSpatialRef() coordTrans = osr.CoordinateTransformation(geoSrs, outSpatialRef) auxGeom.Transform(coordTrans) newFeat.SetGeometry(auxGeom) newFeat.SetField('mi', mi) newFeat.SetField('inom', inom) newFeat.SetField('escala', str(scale)) out=outputLayer.CreateFeature(newFeat) outputDS.Destroy()
Example #4
Source File: vector.py From wradlib with MIT License | 6 votes |
def ogr_add_geometry(layer, geom, attrs): """ Copies single OGR.Geometry object to an OGR.Layer object. Given OGR.Geometry is copied to new OGR.Feature and written to given OGR.Layer by given index. Attributes are attached. Parameters ---------- layer : OGR.Layer object geom : OGR.Geometry object attrs : list attributes referring to layer fields """ defn = layer.GetLayerDefn() feat = ogr.Feature(defn) for i, item in enumerate(attrs): feat.SetField(i, item) feat.SetGeometry(geom) layer.CreateFeature(feat)
Example #5
Source File: vector.py From wradlib with MIT License | 5 votes |
def ogr_add_feature(ds, src, name=None): """ Creates OGR.Feature objects in OGR.Layer object. OGR.Features are built from numpy src points or polygons. OGR.Features 'FID' and 'index' corresponds to source data element Parameters ---------- ds : gdal.Dataset object src : :func:`numpy:numpy.array` source data name : string name of wanted Layer """ if name is not None: lyr = ds.GetLayerByName(name) else: lyr = ds.GetLayer() defn = lyr.GetLayerDefn() geom_name = ogr.GeometryTypeToName(lyr.GetGeomType()) fields = [defn.GetFieldDefn(i).GetName() for i in range(defn.GetFieldCount())] feat = ogr.Feature(defn) for index, src_item in enumerate(src): geom = numpy_to_ogr(src_item, geom_name) if "index" in fields: feat.SetField("index", index) feat.SetGeometry(geom) lyr.CreateFeature(feat)
Example #6
Source File: test_shp.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def create_shapedir(self): drv = ogr.GetDriverByName("ESRI Shapefile") shp = drv.CreateDataSource(self.path) lyr = shp.CreateLayer("nodes", None, ogr.wkbPoint) feature = ogr.Feature(lyr.GetLayerDefn()) feature.SetGeometry(None) lyr.CreateFeature(feature) feature.Destroy()
Example #7
Source File: test_shp.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def setUp(self): def createlayer(driver): lyr = shp.CreateLayer("edges", None, ogr.wkbLineString) namedef = ogr.FieldDefn("Name", ogr.OFTString) namedef.SetWidth(32) lyr.CreateField(namedef) return lyr drv = ogr.GetDriverByName("ESRI Shapefile") testdir = os.path.join(tempfile.gettempdir(), 'shpdir') shppath = os.path.join(tempfile.gettempdir(), 'tmpshp.shp') self.deletetmp(drv, testdir, shppath) os.mkdir(testdir) shp = drv.CreateDataSource(shppath) lyr = createlayer(shp) self.names = ['a', 'b', 'c', 'c'] # edgenames self.paths = ([(1.0, 1.0), (2.0, 2.0)], [(2.0, 2.0), (3.0, 3.0)], [(0.9, 0.9), (4.0, 0.9), (4.0, 2.0)]) self.simplified_names = ['a', 'b', 'c'] # edgenames self.simplified_paths = ([(1.0, 1.0), (2.0, 2.0)], [(2.0, 2.0), (3.0, 3.0)], [(0.9, 0.9), (4.0, 2.0)]) for path, name in zip(self.paths, self.names): feat = ogr.Feature(lyr.GetLayerDefn()) g = ogr.Geometry(ogr.wkbLineString) for p in path: g.AddPoint_2D(*p) feat.SetGeometry(g) feat.SetField("Name", name) lyr.CreateFeature(feat) self.shppath = shppath self.testdir = testdir self.drv = drv
Example #8
Source File: abstractDb.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def writeErrorLog(self,errorDict): """ Writes conversion error log """ errorClasses = list(errorDict.keys()) if len(errorClasses)>0: self.signals.updateLog.emit('\n'+'{:-^60}'.format(self.tr('Features not converted'))) self.signals.updateLog.emit('\n\n'+'{:<50}'.format(self.tr('Class'))+self.tr('Feature id')+'\n\n') for cl in errorClasses: for id in errorDict[cl]: self.signals.updateLog.emit('\n\n'+'{:<50}'.format(cl+str(id)))
Example #9
Source File: gdal2cesium.py From gdal2cesium with GNU General Public License v2.0 | 5 votes |
def write_fake_tile(self,tz,tx,ty,NB_FLAGS): tilefilename = os.path.join(self.tmpoutput, str(tz), str(tx), "%s.%s" % (ty, self.tileext)) # Create directories for the tile if not os.path.exists(os.path.dirname(tilefilename)): os.makedirs(os.path.dirname(tilefilename)) if self.options.createtileindexshp and self.tilelayer is not None: self.ti_cum += 1 tilelayerdefn = self.tilelayer.GetLayerDefn() feat = ogr.Feature(tilelayerdefn) feat.SetField('id', self.ti_cum) feat.SetField('zoom', tz) feat.SetField('tile', "%s_%s_%s" % (tz, tx, ty)) feat.SetField('children', NB_FLAGS) b = self.geodetic.TileBounds(tx, ty, tz) geom = ogr.CreateGeometryFromWkb(makeline(b[0], b[3], b[2], b[1]).wkb) feat.SetGeometry(geom) self.tilelayer.CreateFeature(feat) feat = geom = None # convert to integer representation of heightmap accordind to Cesium format and append children flags byte tilearrayint = (numpy.zeros(4096,numpy.dtype('int16')) + 1000) * 5 tilearrayint.tofile(tilefilename) child_water_bytes = struct.pack('<BB',NB_FLAGS,0x00) with open(tilefilename,'ab') as outfile: outfile.write(child_water_bytes)
Example #10
Source File: reader.py From stdm with GNU General Public License v2.0 | 5 votes |
def _map_column_values(self, feature, feature_defn, source_cols): """ Retrieves values for specific columns from the specified feature. :param feature: Input feature. :type feature: ogr.Feature :param feature_defn: Feature definition for the layer. :type feature_defn: ogr.FeatureDefn :param source_cols: List of columns whose respective values will be retrieved. :type source_cols: list :return: Collection containing pairs of column names and corresponding values. :rtype: dict """ col_values = {} if len(source_cols) == 0: return col_values for f in range(feature_defn.GetFieldCount()): field_defn = feature_defn.GetFieldDefn(f) field_name = field_defn.GetNameRef() match_idx = getIndex(source_cols, field_name) if match_idx != -1: field_value = feature.GetField(f) col_values[field_name] = field_value return col_values
Example #11
Source File: _a_gdal_vector.py From buzzard with Apache License 2.0 | 5 votes |
def iter_features_driver(slicing, mask_poly, mask_rect, lyr): with contextlib.ExitStack() as stack: stack.push(lambda *args, **kwargs: lyr.ResetReading()) if mask_poly is not None: lyr.SetSpatialFilter(mask_poly) stack.push(lambda *args, **kwargs: lyr.SetSpatialFilter(None)) elif mask_rect is not None: lyr.SetSpatialFilterRect(*mask_rect) stack.push(lambda *args, **kwargs: lyr.SetSpatialFilter(None)) start, stop, step = slicing.indices(len(lyr)) indices = range(start, stop, step) ftr = None # Necessary to prevent the old swig bug if step == 1: lyr.SetNextByIndex(start) for i in indices: ftr = lyr.GetNextFeature() if ftr is None: # pragma: no cover raise IndexError('Feature #{} not found'.format(i)) yield ftr else: for i in indices: lyr.SetNextByIndex(i) ftr = lyr.GetNextFeature() if ftr is None: # pragma: no cover raise IndexError('Feature #{} not found'.format(i)) yield ftr # Necessary to prevent the old swig bug # https://trac.osgeo.org/gdal/ticket/6749 del slicing, mask_poly, mask_rect, ftr # insert_data implementation **************************************************************** **
Example #12
Source File: test_fields.py From django-spillway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_feature_to_python(self): feature = Feature(geometry=_geom) self.fp.write(str(feature).encode('ascii')) self.fp.seek(0) v = self.field.to_python(self.fp) self.assertIsInstance(v, OGRGeometry)
Example #13
Source File: test_fields.py From django-spillway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_feature_srid(self): srid = 3857 feature = Feature(geometry=_geom, crs=NamedCRS(srid)) geom = self.field.to_python(str(feature)) self.assertEqual(geom.srid, srid)
Example #14
Source File: test_fields.py From django-spillway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_feature(self): feature = Feature(geometry=_geom) geojson = str(feature) geom = self.field.to_python(geojson) self.assertEqual(json.loads(geom.geojson), feature['geometry']) geom = self.field.to_python(feature) self.assertEqual(json.loads(geom.geojson), feature['geometry'])
Example #15
Source File: test_fields.py From django-spillway with BSD 3-Clause "New" or "Revised" License | 5 votes |
def write_shp(path, gjson): proj = osr.SpatialReference(osr.SRS_WKT_WGS84) g = ogr.CreateGeometryFromJson(json.dumps(gjson)) vdriver = ogr.GetDriverByName('ESRI Shapefile') ds = vdriver.CreateDataSource(path) layer = ds.CreateLayer('', proj, g.GetGeometryType()) featdef = layer.GetLayerDefn() feature = ogr.Feature(featdef) feature.SetGeometry(g) layer.CreateFeature(feature) feature.Destroy() ds.Destroy()
Example #16
Source File: shape.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def write_shp_layer(self, loc_data): if loc_data['geometry.wkt'] == '': return geom = ogr.CreateGeometryFromWkt(loc_data['geometry.wkt']) layer_type = geom.GetGeometryName().lower() layer = self.shp_layers.get(layer_type, None) if layer is None: layer = self.create_shp_layer(layer_type) self.shp_layers[layer_type] = layer if layer: feature = ogr.Feature(layer.GetLayerDefn()) feature.SetGeometry(geom) feature.SetField('id', loc_data['id']) layer.CreateFeature(feature) feature.Destroy()
Example #17
Source File: jqvmap.py From bitcoin-arbitrage-trading-bot with MIT License | 5 votes |
def output_ogr(self, output): driver = ogr.GetDriverByName( 'ESRI Shapefile' ) if os.path.exists( output['file_name'] ): driver.DeleteDataSource( output['file_name'] ) source = driver.CreateDataSource( output['file_name'] ) layer = source.CreateLayer( self.layer_dfn.GetName(), geom_type = self.layer_dfn.GetGeomType(), srs = self.layer.GetSpatialRef() ) for field in self.fields: fd = ogr.FieldDefn( str(field['name']), field['type'] ) fd.SetWidth( field['width'] ) if 'precision' in field: fd.SetPrecision( field['precision'] ) layer.CreateField( fd ) for geometry in self.geometries: if geometry.geom is not None: feature = ogr.Feature( feature_def = layer.GetLayerDefn() ) for index, field in enumerate(self.fields): if field['name'] in geometry.properties: feature.SetField( index, geometry.properties[field['name']].encode('utf-8') ) else: feature.SetField( index, '' ) feature.SetGeometryDirectly( ogr.CreateGeometryFromWkb( shapely.wkb.dumps( geometry.geom ) ) ) layer.CreateFeature( feature ) feature.Destroy() source.Destroy()
Example #18
Source File: coordinate_manipulation.py From pyeo with GNU General Public License v3.0 | 5 votes |
def write_geometry(geometry, out_path, srs_id=4326): """ Saves the geometry in an ogr.Geometry object to a shapefile. Parameters ---------- geometry An ogr.Geometry object out_path The location to save the output shapefile srs_id The projection of the output shapefile. Can be an EPSG number or a WKT string. Notes ----- The shapefile consists of one layer named 'geometry'. """ # TODO: Fix this needing an extra filepath on the end driver = ogr.GetDriverByName("ESRI Shapefile") data_source = driver.CreateDataSource(out_path) srs = osr.SpatialReference() if type(srs_id) is int: srs.ImportFromEPSG(srs_id) if type(srs_id) is str: srs.ImportFromWkt(srs_id) layer = data_source.CreateLayer( "geometry", srs, geom_type=geometry.GetGeometryType()) feature_def = layer.GetLayerDefn() feature = ogr.Feature(feature_def) feature.SetGeometry(geometry) layer.CreateFeature(feature) data_source.FlushCache() data_source = None
Example #19
Source File: _a_gdal_vector.py From buzzard with Apache License 2.0 | 5 votes |
def insert_data(self, geom, geom_type, fields, index): geom = self._ogr_of_geom(geom, geom_type) with self.acquire_driver_object() as (_, lyr): ftr = ogr.Feature(lyr.GetLayerDefn()) if geom is not None: err = ftr.SetGeometry(geom) if err: # pragma: no cover raise ValueError('Could not set geometry (%s)' % str(gdal.GetLastErrorMsg()).strip('\n')) if not self.back_ds.allow_none_geometry and ftr.GetGeometryRef() is None: # pragma: no cover raise ValueError( 'Invalid geometry inserted ' '(Set `allow_none_geometry=True` in Dataset constructor to silence)' ) if index >= 0: err = ftr.SetFID(index) if err: # pragma: no cover raise ValueError('Could not set field id (%s)' % str(gdal.GetLastErrorMsg()).strip('\n')) for i, field in enumerate(fields): if field is not None: err = ftr.SetField2(i, self._type_of_field_index[i](field)) if err: # pragma: no cover raise ValueError('Could not set field #{} ({}) ({})'.format( i, field, str(gdal.GetLastErrorMsg()).strip('\n') )) passed = ftr.Validate(ogr.F_VAL_ALL, True) if not passed: # pragma: no cover raise ValueError('Invalid feature {} ({})'.format( err, str(gdal.GetLastErrorMsg()).strip('\n') )) err = lyr.CreateFeature(ftr) if err: # pragma: no cover raise ValueError('Could not create feature {} ({})'.format( err, str(gdal.GetLastErrorMsg()).strip('\n') ))
Example #20
Source File: abstractDb.py From DsgTools with GNU General Public License v2.0 | 4 votes |
def translateLayer(self, inputLayer, inputLayerName, outputLayer, outputFileName, layerPanMap, errorDict, defaults={}, translateValues={}): """ Makes the layer conversion """ inputLayer.ResetReading() inSpatialRef = inputLayer.GetSpatialRef() outSpatialRef = outputLayer.GetSpatialRef() coordTrans = None if not inSpatialRef.IsSame(outSpatialRef): coordTrans = osr.CoordinateTransformation(inSpatialRef, outSpatialRef) initialCount = outputLayer.GetFeatureCount() count = 0 feat=inputLayer.GetNextFeature() #for feat in inputLayer: while feat: if not feat.geometry(): continue inputId = feat.GetFID() if feat.geometry().GetGeometryCount() > 1: #Deaggregator for geom in feat.geometry(): newFeat=ogr.Feature(outputLayer.GetLayerDefn()) newFeat.SetFromWithMap(feat,True,layerPanMap) auxGeom = ogr.Geometry(newFeat.geometry().GetGeometryType()) auxGeom.AssignSpatialReference(newFeat.geometry().GetSpatialReference()) auxGeom.AddGeometry(geom) if coordTrans != None: auxGeom.Transform(coordTrans) newFeat.SetGeometry(auxGeom) out=outputLayer.CreateFeature(newFeat) if out != 0: self.utils.buildNestedDict(errorDict, [inputLayerName], [inputId]) else: count += 1 else: newFeat=ogr.Feature(outputLayer.GetLayerDefn()) newFeat.SetFromWithMap(feat,True,layerPanMap) if coordTrans != None: geom = feat.GetGeometryRef() geom.Transform(coordTrans) newFeat.SetGeometry(geom) out=outputLayer.CreateFeature(newFeat) if out != 0: self.utils.buildNestedDict(errorDict, [inputLayerName], [inputId]) else: count += 1 feat=inputLayer.GetNextFeature() return count
Example #21
Source File: analysis.py From RHEAS with MIT License | 4 votes |
def cropYield(shapefile, name, startdate="", enddate="", crop="maize", dbname="rheas"): """Extract crop yield from a specified simulation *name* for dates ranging from *startdate* to *enddate*, and saves them a *shapefile*.""" logging.basicConfig(level=logging.INFO, format='%(message)s') log = logging.getLogger(__name__) db = dbio.connect(dbname) cur = db.cursor() datesql = "" if len(startdate) > 0: try: sdt = datetime.strptime(startdate, "%Y-%m-%d") datesql = "and fdate>=date'{0}'".format(sdt.strftime("%Y-%m-%d")) except ValueError: log.warning("Start date is invalid and will be ignored.") if len(enddate) > 0: try: edt = datetime.strptime(enddate, "%Y-%m-%d") datesql += "and fdate<=date'{0}'".format(edt.strftime("%y-%m-%d")) except ValueError: log.warning("End date is invalid and will be ignored.") fsql = "with f as (select gid,geom,gwad,ensemble,fdate from (select gid,geom,gwad,ensemble,fdate,row_number() over (partition by gid,ensemble order by gwad desc) as rn from {0}.dssat) gwadtable where rn=1 {1})".format(name, datesql) sql = "{0} select gid,st_astext(geom),max(gwad) as max_yield,avg(gwad) as avg_yield,stddev(gwad) as std_yield,max(fdate) as fdate from f group by gid,geom".format(fsql) cur.execute(sql) if bool(cur.rowcount): results = cur.fetchall() drv = ogr.GetDriverByName("ESRI Shapefile") ds = drv.CreateDataSource(shapefile) lyr = ds.CreateLayer("yield", geom_type=ogr.wkbMultiPolygon) lyr.CreateField(ogr.FieldDefn("gid", ogr.OFTInteger)) lyr.CreateField(ogr.FieldDefn("average", ogr.OFTReal)) lyr.CreateField(ogr.FieldDefn("maximum", ogr.OFTReal)) lyr.CreateField(ogr.FieldDefn("minimum", ogr.OFTReal)) for row in results: feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField("gid", row[0]) feat.SetField("maximum", row[2]) feat.SetField("average", row[3]) feat.SetField("minimum", row[4]) feat.SetGeometry(ogr.CreateGeometryFromWkt(row[1])) lyr.CreateFeature(feat) feat.Destroy() ds.Destroy()