本文整理汇总了Python中osgeo.ogr.FieldDefn方法的典型用法代码示例。如果您正苦于以下问题:Python ogr.FieldDefn方法的具体用法?Python ogr.FieldDefn怎么用?Python ogr.FieldDefn使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类osgeo.ogr
的用法示例。
在下文中一共展示了ogr.FieldDefn方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_attribute
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def set_attribute(self, name, values):
"""Add/Set given Attribute with given values
Parameters
----------
name : string
Attribute Name
values : :class:`numpy:numpy.ndarray`
Values to fill in attributes
"""
lyr = self.ds.GetLayerByIndex(0)
lyr.ResetReading()
# todo: automatically check for value type
defn = lyr.GetLayerDefn()
if defn.GetFieldIndex(name) == -1:
lyr.CreateField(ogr.FieldDefn(name, ogr.OFTReal))
for i, item in enumerate(lyr):
item.SetField(name, values[i])
lyr.SetFeature(item)
示例2: polygonize
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def polygonize(img,shp_path):
# mapping between gdal type and ogr field type
type_mapping = {gdal.GDT_Byte: ogr.OFTInteger,
gdal.GDT_UInt16: ogr.OFTInteger,
gdal.GDT_Int16: ogr.OFTInteger,
gdal.GDT_UInt32: ogr.OFTInteger,
gdal.GDT_Int32: ogr.OFTInteger,
gdal.GDT_Float32: ogr.OFTReal,
gdal.GDT_Float64: ogr.OFTReal,
gdal.GDT_CInt16: ogr.OFTInteger,
gdal.GDT_CInt32: ogr.OFTInteger,
gdal.GDT_CFloat32: ogr.OFTReal,
gdal.GDT_CFloat64: ogr.OFTReal}
ds = gdal.Open(img)
prj = ds.GetProjection()
srcband = ds.GetRasterBand(1)
dst_layername = "Shape"
drv = ogr.GetDriverByName("ESRI Shapefile")
dst_ds = drv.CreateDataSource(shp_path)
srs = osr.SpatialReference(wkt=prj)
dst_layer = dst_ds.CreateLayer(dst_layername, srs=srs)
raster_field = ogr.FieldDefn('id', type_mapping[srcband.DataType])
dst_layer.CreateField(raster_field)
gdal.Polygonize(srcband, srcband, dst_layer, 0, [], callback=None)
del img, ds, srcband, dst_ds, dst_layer
# convert images in a selected folder to shapefiles
示例3: polygonize
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def polygonize(img,shp_path):
# mapping between gdal type and ogr field type
type_mapping = {gdal.GDT_Byte: ogr.OFTInteger,
gdal.GDT_UInt16: ogr.OFTInteger,
gdal.GDT_Int16: ogr.OFTInteger,
gdal.GDT_UInt32: ogr.OFTInteger,
gdal.GDT_Int32: ogr.OFTInteger,
gdal.GDT_Float32: ogr.OFTReal,
gdal.GDT_Float64: ogr.OFTReal,
gdal.GDT_CInt16: ogr.OFTInteger,
gdal.GDT_CInt32: ogr.OFTInteger,
gdal.GDT_CFloat32: ogr.OFTReal,
gdal.GDT_CFloat64: ogr.OFTReal}
ds = gdal.Open(img)
prj = ds.GetProjection()
srcband = ds.GetRasterBand(1)
dst_layername = "Shape"
drv = ogr.GetDriverByName("ESRI Shapefile")
dst_ds = drv.CreateDataSource(shp_path)
srs = osr.SpatialReference(wkt=prj)
dst_layer = dst_ds.CreateLayer(dst_layername, srs=srs)
# raster_field = ogr.FieldDefn('id', type_mapping[srcband.DataType])
raster_field = ogr.FieldDefn('id', type_mapping[gdal.GDT_Int32])
dst_layer.CreateField(raster_field)
gdal.Polygonize(srcband, srcband, dst_layer, 0, [], callback=None)
del img, ds, srcband, dst_ds, dst_layer
# extract sinks from dem
示例4: output_ogr
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [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()
示例5: saveToShape
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def saveToShape(self, array, srs, outShapeFile):
# Parse a delimited text file of volcano data and create a shapefile
# use a dictionary reader so we can access by field name
# set up the shapefile driver
outDriver = ogr.GetDriverByName('ESRI Shapefile')
# create the data source
if os.path.exists(outShapeFile):
outDriver.DeleteDataSource(outShapeFile)
# Remove output shapefile if it already exists
# options = ['SPATIALITE=YES'])
ds = outDriver.CreateDataSource(outShapeFile)
# create the spatial reference, WGS84
lyrout = ds.CreateLayer('randomSubset', srs)
fields = [
array[1].GetFieldDefnRef(i).GetName() for i in range(
array[1].GetFieldCount())]
for f in fields:
field_name = ogr.FieldDefn(f, ogr.OFTString)
field_name.SetWidth(24)
lyrout.CreateField(field_name)
for k in array:
lyrout.CreateFeature(k)
# Save and close the data source
ds = None
示例6: create_shp_layer
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def create_shp_layer(self, layer_type):
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
if layer_type in shp_types.keys():
layer = self.shp_datasource.CreateLayer(
layer_type, srs, geom_type=shp_types[layer_type])
field = ogr.FieldDefn('id', ogr.OFTString)
layer.CreateField(field)
return layer
示例7: ogr_create_layer
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def ogr_create_layer(ds, name, srs=None, geom_type=None, fields=None):
"""Creates OGR.Layer objects in gdal.Dataset object.
Creates one OGR.Layer with given name in given gdal.Dataset object
using given OGR.GeometryType and FieldDefinitions
Parameters
----------
ds : gdal.Dataset
object
name : string
OGRLayer name
srs : OSR.SpatialReference
object
geom_type : OGR GeometryType
(eg. ogr.wkbPolygon)
fields : list of 2 element tuples
(strings, OGR.DataType) field name, field type
Returns
-------
out : OGR.Layer
object
"""
if geom_type is None:
raise TypeError("geometry_type needed")
lyr = ds.CreateLayer(name, srs=srs, geom_type=geom_type)
if fields is not None:
for fname, fvalue in fields:
lyr.CreateField(ogr.FieldDefn(fname, fvalue))
return lyr
示例8: createField
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def createField(self,table,field):
#Creates an OGR field
colType = columnType(table, field)
#Get OGR type
ogrType = ogrTypes[colType]
#OGR date handling is broken! handle all dates as strings
if ogrType == OGRWriter.OGR_DATE_TYPE:
ogrType = OGRWriter.OGR_STRING_TYPE
field_defn = ogr.FieldDefn(field.encode('utf-8'), ogrType)
return field_defn
示例9: setUp
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
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
示例10: add_fields
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def add_fields(layer, fielddefs):
# fielddefs = [(new_field_name, data_type),...]
#
for fielddef in fielddefs:
layer.CreateField(ogr.FieldDefn(fielddef[0], fielddef[1]))
示例11: featuresToFile
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def featuresToFile(features, dst_drv, dst_name, dst_srs, layer_name=None,
geomtype=None, overwrite=True):
if not features: # features is empty list
print("No Features Created")
return
drv = ogr.GetDriverByName(dst_drv)
if drv is None:
print("Driver not available ({})".format(dst_drv))
return
dsrc = drv.CreateDataSource(dst_name)
if dsrc is None:
print("DataSource creation failed")
return
if not geomtype:
f0 = features[0]
geomref = features[0].GetGeometryRef()
if geomref is not None:
geomtype = geomref.GetGeometryType()
else:
return
layer = dsrc.CreateLayer(layer_name, srs=dst_srs, geom_type=geomtype)
# Create the fields for the new file
for i in range(features[0].GetFieldCount()):
fieldDef = features[0].GetFieldDefnRef(i)
if "List" in ogr.GetFieldTypeName(fieldDef.GetType()):
t = ogr.GetFieldTypeName(fieldDef.GetType())[:-4]
if t == "String":
fieldDef = ogr.FieldDefn(fieldDef.GetName(), ogr.OFTString)
elif t == "Integer":
fieldDef = ogr.FieldDefn(fieldDef.GetName(), ogr.OFTInteger)
layer.CreateField(fieldDef)
# print layer_name
for feature in features:
layer.CreateFeature(feature)
示例12: convert_file
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def convert_file(path, acronym, fields, values):
file = ogr.Open(str(path), True)
try:
layer = file.GetLayer()
defn = layer.GetLayerDefn()
existing_fields = []
missing_fields = []
for field in fields:
if defn.GetFieldIndex(field) >= 0:
existing_fields.append(field)
if defn.GetFieldIndex(field + '_txt') < 0:
missing_fields.append(ogr.FieldDefn(field + '_txt'))
layer.CreateFields(missing_fields)
feat = layer.GetNextFeature()
while feat:
for field in existing_fields:
value = feat.GetFieldAsString(field)
if value:
value = ','.join(
values[field].get(v, v)
for v in value.split(',')
)
feat.SetField(field + '_txt', value)
layer.SetFeature(feat)
feat = layer.GetNextFeature()
finally:
file.Destroy()
示例13: geologic_maps_modify_shapefile
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def geologic_maps_modify_shapefile(shapefile_name, geol_field = "xx"):
# The shapefile to be rasterized:
print('Rasterize ' + shapefile_name)
#get path and filename seperately
shapefilefilepath = LSDPT.GetPath(shapefile_name)
#shapefilename = LSDPT.GetFileNameNoPath(shapefile_name)
shapefileshortname = LSDPT.GetFilePrefix(shapefile_name)
# get the new shapefile name
new_shapefile_name = shapefilefilepath+os.sep+shapefileshortname+"_new.shp"
# copy the shapefile into the new shapefile--we don't wwant to mess up the original data
print("The New Shapefile name is: "+new_shapefile_name)
Copy_Shapefile(shapefile_name,new_shapefile_name)
# New shapefile is opened for writing.
dataSource = ogr.Open(new_shapefile_name,1)
daLayer = dataSource.GetLayer(0)
# add a new field
new_field = ogr.FieldDefn("GEOL_CODE", ogr.OFTInteger)
daLayer.CreateField(new_field)
# lets see what the layers are
print("Let me tell you what the names of the fields are after I added one!")
layerDefinition = daLayer.GetLayerDefn()
for i in range(layerDefinition.GetFieldCount()):
print(layerDefinition.GetFieldDefn(i).GetName())
# Make a key for the bedrock
geol_dict = dict()
geol_iterator = 0
geol_field = geol_field #
for feature in daLayer:
GEOL = feature.GetField(geol_field)
if GEOL not in geol_dict:
geol_iterator = geol_iterator+1
print("I found a new rock type, GEOL: "+ str(GEOL)+ " and rock type: " + str(geol_iterator))
geol_dict[GEOL] = geol_iterator
# now get the geol code
this_geol_code = geol_dict[GEOL]
# set the feature
feature.SetField("GEOL_CODE", this_geol_code)
# need to update the layer
daLayer.SetFeature(feature)
print("The rocks are: ")
print(geol_dict)
print("All done")
return new_shapefile_name, geol_dict
示例14: geologic_maps_modify_shapefile
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def geologic_maps_modify_shapefile(shapefile_name, geol_field = "xx"):
# The shapefile to be rasterized:
print('Rasterize ' + shapefile_name)
#get path and filename seperately
shapefilefilepath = LSDPT.GetPath(shapefile_name)
#shapefilename = LSDPT.GetFileNameNoPath(shapefile_name)
shapefileshortname = LSDPT.GetFilePrefix(shapefile_name)
# get the new shapefile name
new_shapefile_name = shapefilefilepath+os.sep+shapefileshortname+"_new.shp"
# copy the shapefile into the new shapefile--we don't wwant to mess up the original data
print("The New Shapefile name is: "+new_shapefile_name)
Copy_Shapefile(shapefile_name,new_shapefile_name)
# New shapefile is opened for writing.
dataSource = ogr.Open(new_shapefile_name,1)
daLayer = dataSource.GetLayer(0)
# add a new field
new_field = ogr.FieldDefn("GEOL_CODE", ogr.OFTInteger)
daLayer.CreateField(new_field)
# lets see what the layers are
print("Let me tell you what the names of the fields are after I added one!")
layerDefinition = daLayer.GetLayerDefn()
for i in range(layerDefinition.GetFieldCount()):
print(layerDefinition.GetFieldDefn(i).GetName())
# Make a key for the bedrock
geol_dict = dict()
geol_iterator = 0
for feature in daLayer:
GEOL = feature.GetField(geol_field)
if GEOL not in geol_dict:
geol_iterator = geol_iterator+1
print("I found a new rock type, GEOL: "+ str(GEOL)+ " and rock type: " + str(geol_iterator))
geol_dict[GEOL] = geol_iterator
# now get the geol code
this_geol_code = geol_dict[GEOL]
# set the feature
feature.SetField("GEOL_CODE", this_geol_code)
# need to update the layer
daLayer.SetFeature(feature)
print("The rocks are: ")
print(geol_dict)
print("All done")
return new_shapefile_name, geol_dict
示例15: make_tiles
# 需要导入模块: from osgeo import ogr [as 别名]
# 或者: from osgeo.ogr import FieldDefn [as 别名]
def make_tiles(self):
# Generate the vrt files for zoom ranges
i = 0
tmp_res = -1
vrt_file = None
for tz in range(self.tminz,self.tmaxz+1):
res = self.zoom_resolutions[tz][0] # I check only with resx, because resy will be positively correlated
if res != tmp_res:
if i>0:
self.vrts[vrt_file][1] = tz-1
tmp_res = res
resx = self.zoom_resolutions[tz][0]
resy = self.zoom_resolutions[tz][1]
self.make_vrt(resx,resy,i)
vrt_file = "cesium_%s.vrt" % i
self.vrts[vrt_file] = [tz,None]
i += 1
if tz == self.tmaxz:
self.vrts[vrt_file][1] = tz
self.ti_cum = 0
if self.options.createtileindexshp and self.tilelayer is None:
driver = ogr.GetDriverByName('Esri Shapefile')
shptileindexfile = os.path.join(self.output,'tilesindex.shp')
if os.path.exists(shptileindexfile):
for f in glob.glob(self.output+'/tilesindex.*'):
os.remove(f)
shptileindex = driver.CreateDataSource(shptileindexfile)
self.tilelayer = shptileindex.CreateLayer('tiles', None, ogr.wkbLineString)
self.tilelayer.CreateField(ogr.FieldDefn('id', ogr.OFTInteger))
self.tilelayer.CreateField(ogr.FieldDefn('zoom', ogr.OFTInteger))
self.tilelayer.CreateField(ogr.FieldDefn('tile', ogr.OFTString))
self.tilelayer.CreateField(ogr.FieldDefn('children', ogr.OFTInteger))
# Generate parent tiles
self.generate_fake_parent_tiles()
# For each vrt (i.e. zoom range) generate the tiles
self.steps = len(self.vrts)
self.step = 1
for vrt in self.vrts.keys():
self.process_vrt(vrt)
if not self.options.keepfiles:
try:
os.remove(vrt)
except:
pass
self.step += 1
self.create_layerjsonfile()
if self.options.createtileindexshp and self.tilelayer is not None:
shptileindex.Destroy()
shptileindex = self.tilelayer = feat = geom = None
print """Processing finished. Tiles written to "%s".""" % self.output