GDAL polygonize in python creating blank polygon?

The problem is that I was not creating a field to store the raster band. After digging through the gdal_polygonize.py file, I realized this is not automatically done when calling gdal.Polygonize, which instead uses the function found here.

Here is the extra step needed to create a field and write a band to the field:

newField = ogr.FieldDefn('MYFLD', ogr.OFTInteger)
outLayer.CreateField(newField)

We can then write the band to this field, with an index of 0:

gdal.Polygonize(band, None, outLayer, 0, [], callback=None )

I had the same problem and I fixed by closing the shapefile after using poligonize ("dst_ds.Destroy())":

def polygon_response(raster, poligonized_shp):
src_ds = gdal.Open(raster)
if src_ds is None:
    print('Unable to open %s' % src_filename)
    sys.exit(1)

try:
    srcband = src_ds.GetRasterBand(3)
except RuntimeError as e:
    # for example, try GetRasterBand(10)
    print('Band ( %i ) not found' % band_num)
    print(e)
    sys.exit(1)

#  create output datasource
dst_layername = poligonized_shp
drv = ogr.GetDriverByName("ESRI Shapefile")
dst_ds = drv.CreateDataSource( dst_layername + ".shp" )
dst_layer = dst_ds.CreateLayer(dst_layername, srs = None )

gdal.Polygonize( srcband, None, dst_layer, -1, [], callback=None )
dst_ds.Destroy()

polygon_response(raster, poligonized_shp)

Tags:

Python

Gdal