python生成点矢量缓冲区(Arcgis的Buffer功能)
根据点矢量,设定缓冲区距离,生成面状矢量
1.导入库:
import glob
import os
import osgeo.ogr , osgeo.gdal
from osgeo import ogr,gdal,osr
2.构建函数:
def create_buffer(inputfns, outputBufferfns, bufferDist):
# @param inputfns:输入文件夹路径
# @param outputBufferfns:输出文件夹路径
# @param bufferDis:设定缓冲区距离,此处距离单位为度
for inputfn in glob.glob(os.path.join(inputfns, '*.shp')):
inputds = ogr.Open(inputfn)
inputlyr = inputds.GetLayer()
# 检查输入图层是否有要素
if inputlyr.GetFeatureCount() == 0:
print(f"跳过 {inputfn},因为它没有要素。")
continue
inputdefn = inputlyr.GetLayerDefn()
inputfeature = inputlyr.GetFeature(0)
prj = inputlyr.GetSpatialRef()
driver = ogr.GetDriverByName('ESRI Shapefile')
### 输出shp文件在输入文件名后加'_buffer.shp'后缀
inpath_name = os.path.basename(inputfn).split('.')[0]
outpath_name = outputBufferfns + inpath_name + '_buffer.shp'
### 判断输出文件名是否存在,存在的话删除
if os.path.exists(outpath_name):
driver.DeleteDataSource(outpath_name)
outputBufferds = driver.CreateDataSource(outpath_name)
bufferlyr = outputBufferds.CreateLayer(outpath_name, srs=prj, geom_type=ogr.wkbPolygon)
featureDefn = bufferlyr.GetLayerDefn()
for feature in inputlyr:
ingeom = feature.GetGeometryRef()
geomBuffer = ingeom.Buffer(bufferDist)
outFeature = ogr.Feature(featureDefn)
outFeature.SetGeometry(geomBuffer)
bufferlyr.CreateFeature(outFeature)
3.调用函数:
inpath_buffer = "Your_Path\\1_Select\\" # 设置生成缓冲区的数据输入路径
outpath_buffer = r"Your_Path\\2_Buffer\\"
bufferDist = 0.018 # 设置缓冲区距离,单位为度,1800米缓冲区可以按0.018来算
create_buffer(inpath_buffer , outpath_buffer , bufferDist)