[GIS] Using callback with python gdal.RasterizeLayer

gdalpythonqgis-plugins

In a QGis python plugin i rasterize a vector layer with this code. All work fine except the callback: no error but nothing happen. The function callbackRasterize is never called

    gdal.RasterizeLayer(target_ds, [1], source_layer,
                        options=["ALL_TOUCHED=TRUE", attribute],
                        callback=self.callbackRasterize)

I found that using this code, the progress is visualized on standard output, but i can't use it with python:

    gdal.RasterizeLayer( .... callback=gdal.TermProgress)

How can I do to know when the rasterization process is over?

Best Answer

Alex is right, the call to gdal.RasterizeLayer is synchronous. There's little reason to include a callback unless you wish to obtain progress information, or to cancel the rasterisation part way through.

At a guess I'd say the method signature of your callbackRasterize doesn't match that expected by GDAL. Though a little trial and error I got the following to work.

def progress_callback(complete, message, unknown):
    print('progress: {}, message: "{}", unknown {}'.format(complete, message, unknown))
    return 1

Called by using something like:

exitcode = gdal.RasterizeLayer(targetds, [1], source_layer, 
                               burn_values=[1], callback = progress_callback )

Prints out the following:

progress: 0.0, message: "", unknown None
progress: 0.230125, message: "", unknown None
progress: 0.46025, message: "", unknown None
progress: 0.690375, message: "", unknown None
progress: 0.9205, message: "", unknown None
progress: 1.0, message: "", unknown None

Returning a 0 value from the progress_callback causes gdal.RasterizeLayer to return immediately with a non-zero exit code. I've no idea on what the unknown parameter is for, however it is required for the callback to work.

Related Question