1

I am trying to Polygonize one raster image that previously I convert to 1s and 0s.

If I do it from QGIS, there is the option to select the output field name, which stores as attributes the value of the pixel, and let me iterate over all the features afterwards and store only the ones with value 1. (Since apparently it's impossible to polygonize only pixels with a specific value)

The problem is, that I can't see in the documentation of gdal.Polygonize() (http://www.gdal.org/gdal__alg_8h.html#a3f522a9035d3512b5d414fb4752671b1) any option to select the output file, so I get a bunch of polygons numerated from 0 to end.

Is there any way of keep the values of the pixels as attributes?

2

1 Answer 1

2

Indeed going to the source code ended up solving the problem, I could not find it, thanks user30184.

Specifically, lines 242-253 has the answer. I upload me code with what I finally had to do:

import gdal, ogr
dst_layername = 'polygonized_test_all_all_2.shp'
drv = ogr.GetDriverByName("ESRI Shapefile")
dst_ds = drv.CreateDataSource(dst_layername)
dst_layer = dst_ds.CreateLayer(dst_layername, srs=srs)
fd = ogr.FieldDefn("DN", ogr.OFTInteger)
dst_layer.CreateField(fd)
dst_field = dst_layer.GetLayerDefn().GetFieldIndex("DN")
gdal.Polygonize(band, None, dst_layer, dst_field, [], callback=None)

By the way, apparently if you use the same binary raster as mask, indeed polygonize only value 1 pixels, I had read that was not possible but it works:

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

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.