3

I am trying to polygonize one of my rasters with PyGIS. I do this with the below script.

sourceRaster = 
gdal.Open('RASTER.tiff')
sr_proj=sourceRaster.GetProjection()
raster_proj = osr.SpatialReference()
raster_proj.ImportFromWkt(sr_proj)

band = sourceRaster.GetRasterBand(1) 
print  band
bandArray = band.ReadAsArray()
outShapefile = "POLYGON"
driver = ogr.GetDriverByName("ESRI Shapefile")
outDatasource = driver.CreateDataSource(outShapefile+ ".shp")
outLayer = outDatasource.CreateLayer('polygonized', srs=raster_proj)
newField = ogr.FieldDefn(str(1), ogr.OFTInteger)
outLayer.CreateField(newField)

gdal.Polygonize( band, None, outLayer, -1, [], callback=None )
outDatasource.Destroy()
sourceRaster = None

print "finish"

When I run the above, a polygonized version of my raster file has been created. The polygon looks like expected, it at least seems to fit the raster.

Raster and polygon projection

The weird thing however is that the attribute table is empty and it looks like only the shadow is projected

also when I Print the band

    band = sourceRaster.GetRasterBand(1) 
print  band

Below is printed

osgeo.gdal.Band; proxy of Swig Object of type 'GDALRasterBandShadow *' at 0x12a90a450
finish

When I use the QGIS GDAL Polygonize inbuilt function, the polygon looks like expected with a populated Attribute table.

Who can help?

1 Answer 1

5

Found out that the reason the attribute table was empty was due to

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

Updated it to

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

Now it also populates the actual values in the attribute table. Not sure what this parameter means, but it looks like it works now.

Does anyone know?

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.