本文整理汇总了Python中osgeo.ogr.Feature方法的典型用法代码示例。如果您正苦于以下问题:Python ogr.Feature方法的具体用法?Python ogr.Feature怎么用?Python ogr.Feature使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类osgeo.ogr
的用法示例。
在下文中一共展示了ogr.Feature方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_idx_as_shp
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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()
示例2: ogr_add_geometry
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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)
示例3: insertFrame
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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()
示例4: insertFrame
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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()
示例5: iter_features_driver
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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 **************************************************************** **
示例6: insert_data
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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')
))
示例7: write_geometry
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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
示例8: output_ogr
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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()
示例9: write_shp_layer
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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()
示例10: write_shp
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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()
示例11: test_feature
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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'])
示例12: test_feature_srid
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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)
示例13: test_feature_to_python
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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)
示例14: ogr_add_feature
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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)
示例15: _map_column_values
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import Feature [as 别名]
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