python+gdal实现矢量栅格之间相互转换

python+gdal实现矢量转栅格,栅格转矢量

矢量转栅格

# 两文件的坐标系必须一致
def shp_to_tiff(shp_file,refore_tif, output_tiff):
    """
     将shp文件转换成tiff文件,用来去黑边
    :param shp_file: 边界矢量数据
    :param output_tiff: 转换的tiff结果
    :param projection:  转换后的tiff格式
    :param transform:
    :param rows:
    :param cols:
    :return: 矢量栅格图像
    """
    # 读取shp文件
    driver = ogr.GetDriverByName("ESRI Shapefile")
    data_source = driver.Open(shp_file, 1)
    # 获取图层文件对象
    shp_layer = data_source.GetLayer()

    img = gdal.Open(refore_tif)
    projection = img.GetProjection()
    transform = img.GetGeoTransform()
    cols = img.RasterXSize
    rows = img.RasterYSize
    img = None  # todo 释放内存,只有强制为None才可以释放干净
    del img
    # 构建临时存储tif路径
    # index_arr = str_all_index(output_tiff, '\\')
    # last_index = index_arr[len(index_arr) - 1] + 1
    # temp_output_tiff = output_tiff[:last_index] + 'temp.tif'

    # 根据模板tif属性信息创建对应标准的目标栅格
    target_ds = gdal.GetDriverByName('GTiff').Create(output_tiff, cols, rows, 1, gdal.GDT_Byte)
    target_ds.SetGeoTransform(transform)
    target_ds.SetProjection(projection)

    band = target_ds.GetRasterBand(1)
    # 设置背景数值
    NoData_value = 0
    band.SetNoDataValue(NoData_value)
    band.FlushCache()

    # 调用栅格化函数。gdal.RasterizeLayer函数有四个参数,分别有栅格对象,波段,矢量对象,value的属性值将为栅格值
    gdal.RasterizeLayer(target_ds, [1], shp_layer, options=["ATTRIBUTE=Id"])
    # 直接写入??
    y_buffer = band.ReadAsArray()
    target_ds.WriteRaster(0, 0, cols, rows, y_buffer.tobytes())
    target_ds = None  # todo 释放内存,只有强制为None才可以释放干净
    del target_ds, shp_layer

    # 读取模板tif文件相关属性信息 这里用到了read_tiff, 后面可以考虑和读取栅格重合 因为都要读栅格数据,避免重复读取
    # img_array, projection, transform, rows, cols = read_tiff(template_tiff)

栅格转矢量

def polygonize_Raster(input_File, out_File):
    ds = gdal.Open(input_File)
    srcband = ds.GetRasterBand(1)
    maskband = srcband.GetMaskBand()
    drv = ogr.GetDriverByName('ESRI Shapefile')
    dst_ds = drv.CreateDataSource(out_File)
    srs = None
    dst_layername = 'out'
    dst_layer = dst_ds.CreateLayer(dst_layername, srs=srs)
    dst_fieldname = 'DN'
    fd = ogr.FieldDefn(dst_fieldname, ogr.OFTInteger)
    dst_layer.CreateField(fd)
    dst_field = 0
    options = []
    # 参数  输入栅格图像波段\掩码图像波段、矢量化后的矢量图层、需要将DN值写入矢量字段的索引、算法选项、进度条回调函数、进度条参数
    gdal.Polygonize(srcband, maskband, dst_layer, dst_field, options)

你可能感兴趣的:(python,影像处理,python,开发语言,后端)