Python多个栅格数据转单个矢量文件【tif 转shp】

Python多个栅格数据转单个矢量文件【more tif 转shp】

1. 操作说明

1.1 文件类型说明

  • 栅格数据为:mask掩码.tif
    在这里插入图片描述

  • 矢量数据为:.shp
    在这里插入图片描述

1.2 操作说明

  • 将多个mask tif图片转为shp,保存在一个shp文件

2. 相关代码

  • 完整代码
    import os
    import rasterio
    import geopandas as gpd
    from rasterio import features
    from shapely.geometry import shape
    root_path=""  # tif图片文件夹
    root_fold = os.walk(root_path)
    save_file=os.path.join(root_path, 'whole.shp')
    out_shp = gpd.GeoDataFrame(columns=['name','geometry']) # 保存的shp属性表
    file_list=[folder_list for path, folder_list, file_list in root_fold][0]
    nodata,i=0,0
    for tif in file_list:
        if tif.split('.')[-1]!='tif':
                    continue
        tif_filename=os.path.join(dirpath,tif)
        with rasterio.open(tif_filename) as f:
            image = f.read(1)
            img_crs = f.crs
            image[image == f.nodata] = nodata
            for coords, value in features.shapes(image, transform=f.transform):
                if value != nodata:
                    geom = shape(coords)
                    out_shp.loc[i] = [tif,geom]
                    i += 1
            out_shp.set_geometry('geometry',inplace=True)   
    out_shp.to_file(save_file,crs=img_crs,encoding='utf-8')
    

猜你喜欢

转载自blog.csdn.net/m0_46926492/article/details/130239415