Вот несколько методов полигонизации растра с использованием GDAL, а также примеры кода:
Метод 1. Использование инструмента командной строки GDAL:
gdal_polygonize.py input_raster.tif -f "ESRI Shapefile" output_polygons.shp
Метод 2. Использование привязок GDAL Python:
from osgeo import gdal, ogr
# Open the raster dataset
raster_ds = gdal.Open('input_raster.tif')
# Create a vector layer for the output polygons
driver = ogr.GetDriverByName('ESRI Shapefile')
output_ds = driver.CreateDataSource('output_polygons.shp')
output_layer = output_ds.CreateLayer('polygons', geom_type=ogr.wkbPolygon)
# Perform the polygonization
gdal.Polygonize(raster_ds.GetRasterBand(1), None, output_layer, -1, [], callback=None)
# Close the datasets
output_ds = None
raster_ds = None
Метод 3. Использование библиотеки Rasterio (построенной на основе GDAL):
import rasterio
from rasterio.features import shapes
# Open the raster dataset
with rasterio.open('input_raster.tif') as src:
image = src.read(1)
# Perform the polygonization
results = (
{'properties': {'raster_val': v}, 'geometry': s}
for i, (s, v) in enumerate(shapes(image, mask=None, connectivity=4, transform=src.transform))
)
# Save the results as a GeoJSON file
with open('output_polygons.geojson', 'w') as f:
f.write('{"type":"FeatureCollection","features":[')
f.write(','.join([json.dumps(s) for s in results]))
f.write(']}')
Метод 4. Использование библиотеки WhiteboxTools (библиотеки геопространственного анализа):
import whitebox
# Create an instance of the WhiteboxTools tool
wbt = whitebox.WhiteboxTools()
# Set the working directory (where the input and output files will be located)
wbt.set_working_dir('/path/to/working/directory')
# Perform the polygonization
wbt.polygonize('input_raster.tif', 'output_polygons.shp', callback=lambda x: print(x))
# Close the WhiteboxTools instance
wbt.close()