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?

ImanolUr
  • 1,102
  • 1
  • 10
  • 21
  • Perhaps you can find something from the python script https://trac.osgeo.org/gdal/browser/trunk/gdal/swig/python/scripts/gdal_polygonize.py, documented in http://www.gdal.org/gdal_polygonize.html – user30184 Apr 11 '18 at 11:21
  • Is calling gdal.Polygonize() from the command line using subprocess in python an option? – Marcelo Villa Apr 11 '18 at 11:34

1 Answers1

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)
ImanolUr
  • 1,102
  • 1
  • 10
  • 21