都什么年代了,还用传统矢量化 ?!都给我用raterio,快,不止一点点

都给我用rasterio!快,不止一点点

# Convert bitmask to polygon (zero values only)

import rasterio
from rasterio.features import shapes
from shapely.geometry import shape
import geopandas as gpd
import os,shutil
import gc

# Open the raster file
src_dir = "./"
dst_dir = "./"

#if os.path.exists(dst_dir):
#    shutil.rmtree(dst_dir)
#os.mkdir(dst_dir)

for file in os.listdir(src_dir):
    if not file[-4:] == ".tif":
        continue

    src_raster = os.path.join(src_dir,file)
    print(src_raster)

    with rasterio.open(src_raster) as src:
        image = src.read(1)  # Read the first band

        # Convert raster band into polygons
        results = [{'properties': {'raster_val': v}, 'geometry': s}
                for i, (s, v) in enumerate(shapes(image, transform=src.transform))]

        # Transform GeoJSON features into shapely geometries
        geoms = [shape(geom['geometry']) for geom in results]

        # Create a GeoDataFrame
        gdf = gpd.GeoDataFrame.from_features(results)

    src.close()

    # Now you have a GeoDataFrame with shapely polygons

    gdf = gdf[gdf['raster_val'] == 1]

    #dissolved = gdf.dissolve(by = 'raster_val')

    #dissolved['dem_id'] = (os.path.split(src_raster)[1])

    #print(dissolved.head())

    #dissolved.to_file(os.path.join(dst_dir,file[0:-4]+".shp"))

    gdf.to_file(os.path.join(dst_dir,file[0:-4]+".shp"))

    del image
    del results
    del geoms
    del gdf

    gc.collect() 

 

posted @ 2024-07-22 11:21  wsZhang  阅读(1)  评论(0编辑  收藏  举报