After converting a raster file to a vector file using gdal.polygonize
, I cannot carry out further commands (e.g. Clip) because the vector is produced with invalid geometries (as determined by the QGIS GUI). Within GIS itself, I can correct this by using Fix Geometries, but cannot using Python code outside of the GUI. I can't work out why this happens.
Is there a way to check/make valid geometries in Python/GDAL framework? I have not been able to find anything that works.
src_ds = gdal.Open('input.tif')
if src_ds is None:
print ('Unable to open %s' % src_filename)
sys.exit(1)
try:
srcband = src_ds.GetRasterBand(1)
except RuntimeError:
print ('Band 1 not found')
sys.exit(1)
dst_layername = "output/path/filename"
drv = ogr.GetDriverByName("ESRI Shapefile")
if os.path.exists(dst_layername + ".shp"):
drv.DeleteDataSource(dst_layername + ".shp")
# create spatial reference for the new vector based on the raster
srs = osr.SpatialReference()
srs.ImportFromWkt(src_ds.GetProjection())
dst_layer = dst_ds.CreateLayer(dst_layername, srs = srs)
# create polygon layer
dst_ds = drv.CreateDataSource(dst_layername + ".shp")
gdal.Polygonize(srcband, srcband, dst_layer, -1, [], callback=None)
### fix geometries
processing.run("native:fixgeometries",
{'INPUT':"output/path/filename.shp",
'OUTPUT':"output_fixed.shp"})
# > produces a file, but shows nothing