Open faith1688 opened 1 month ago
求问,这里的shp是自动生成的吗,为什么我每次到这里都显示没有shp文件,然后就报错了,qiu'da求大佬解答一下,万分感谢!!
你的栅格矢量化出问题了,我当初调用的是C++封装的exe,这个工具,我有分享,你也可以换一种方式。
我已经解决了,这是平替的代码,可以直接复制完成,这里可以分享给后续有类似问题的伙伴们: def polygonize1(image_path, raster_path, forest_shp_path):
src_ds = gdal.Open(image_path)
band = src_ds.GetRasterBand(1)
src_array = band.ReadAsArray()
# Create mask of the raster
mask = src_array != 0
# Convert numpy array to gdal raster
driver = gdal.GetDriverByName('MEM')
mask_ds = driver.Create('', src_array.shape[1], src_array.shape[0], 1, gdal.GDT_Byte)
mask_ds.GetRasterBand(1).WriteArray(mask)
# Create output shapefile
shp_driver = ogr.GetDriverByName("ESRI Shapefile")
if os.path.exists(forest_shp_path):
shp_driver.DeleteDataSource(forest_shp_path)
out_datasource = shp_driver.CreateDataSource(forest_shp_path)
out_layer = out_datasource.CreateLayer("polygonized", srs=None)
fd = ogr.FieldDefn("DN", ogr.OFTInteger)
out_layer.CreateField(fd)
gdal.Polygonize(mask_ds.GetRasterBand(1), None, out_layer, 0, [], callback=None)
out_datasource.Destroy()
print(f"Shapefile created at {forest_shp_path}") 再次感谢大佬分享代码