SonwYang / SLP-cropland-parcel-extraction

cropland-parcel extraction
32 stars 6 forks source link

关于在进行推理时出现的Failed to create shapefile at F:/test_results\predict_shp\test_final.shp问题,无法进行推理 #7

Open faith1688 opened 1 month ago

faith1688 commented 1 month ago

image 求问,这里的shp是自动生成的吗,为什么我每次到这里都显示没有shp文件,然后就报错了,qiu'da求大佬解答一下,万分感谢!! image

SonwYang commented 1 month ago

你的栅格矢量化出问题了,我当初调用的是C++封装的exe,这个工具,我有分享,你也可以换一种方式。

faith1688 commented 1 month ago

我已经解决了,这是平替的代码,可以直接复制完成,这里可以分享给后续有类似问题的伙伴们: def polygonize1(image_path, raster_path, forest_shp_path):

Open the input raster file

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}")       再次感谢大佬分享代码