GDAL-based spatial buffer analysis (python)

Preface

Spatial buffer analysis is one of the basic spatial operation functions in geographic information systems. It is based on the point, line, and surface entities of the research target to establish a certain distance band around it to identify these target entities to adjacent objects The radiation range or influence degree of the radiation in order to provide a basis for an analysis or decision.

Buffers can be divided into point target buffers, line target buffers, and surface target buffers according to different research targets. Point target buffer is the area surrounded by the circle with the target point as the center and the buffer distance as the radius; line target buffer is the strip-shaped area with the target line as the centerline and a certain distance shifted to both sides or one side; The area target buffer area is a polygonal area formed by extending a certain distance outward or inward from the boundary line of the target surface (as shown in the figure below).
Insert picture description here
This article will take a line vector as an example to introduce how to create a buffer.

Vector data visualization

Input
Insert picture description here
output
Insert picture description here

Code

from pathlib import Path
import ogr

def buffer(inShp, fname, bdistance=0.01):
    """
    :param inShp: 输入的矢量路径
    :param fname: 输出的矢量路径
    :param bdistance: 缓冲区距离
    :return:
    """
    ogr.UseExceptions()
    in_ds = ogr.Open(inShp)
    in_lyr = in_ds.GetLayer()
    # 创建输出Buffer文件
    driver = ogr.GetDriverByName('ESRI Shapefile')
    if Path(fname).exists():
        driver.DeleteDataSource(fname)
    # 新建DataSource,Layer
    out_ds = driver.CreateDataSource(fname)
    out_lyr = out_ds.CreateLayer(fname, in_lyr.GetSpatialRef(), ogr.wkbPolygon)
    def_feature = out_lyr.GetLayerDefn()
    # 遍历原始的Shapefile文件给每个Geometry做Buffer操作
    for feature in in_lyr:
        geometry = feature.GetGeometryRef()
        buffer = geometry.Buffer(bdistance)
        out_feature = ogr.Feature(def_feature)
        out_feature.SetGeometry(buffer)
        out_lyr.CreateFeature(out_feature)
        out_feature = None
    out_ds.FlushCache()
    del in_ds, out_ds


if __name__ == '__main__':
    inShp = './data/shp/bj_line.shp'
    fname = 'Buffer.shp'
    buffer(inShp, fname)

Guess you like

Origin blog.csdn.net/weixin_42990464/article/details/111310000