I am trying to add an interpolation layer based on an existing vector layer by using the Python Console (initially in the menu Raster/Interpolation), but can't find anything related in the documentation.
I saw the QgsIDWInterpolator in the API, but can't get it working. It seems it expects a list of LayerData but it doesn't work neither. Here my current code:
ld = qgis.analysis.QgsIDWInterpolator.LayerData
ld.vectorLayer = vlayer
ld.zCoordInterpolation = 0
ld.interpolationAttribute = 5
ld.mInputType = 0
ldlist = [ld]
itp = qgis.analysis.QgsIDWInterpolator(ldlist)
I get the following error for the last command:
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: arguments did not match any overloaded call:
QgsIDWInterpolator(list-of-QgsInterpolator.LayerData): argument 1 has unexpected type 'list'
QgsIDWInterpolator(QgsIDWInterpolator): argument 1 has unexpected type 'list'
Best Answer
The documentation on pyqgis is not very self-explanatory, but i figured out how to properly call the associated interpolation classes (
QgsInterpolator
,QgsTINInterpolator
,QgsIDWInterpolator
,QgsGridFileWriter
) from python. I am going to describe every step of the script in great detail:Step 1:
Import the core and analysis module and get the desired vector layer for interpolation by selecting it with a mouseclick in the layer tab.
Step 2:
Prepare the interpolation classes with the necessary Parameters. The exact parameters for initialization of the LayerData struct can be found in the QGIS API docs (searchterm: QgsInterpolator).
Please notice that I don't use the z Coordinate, I get the first available field (index = 0) as interpolation attribute, and use POINTS as input type.
Step 3:
Choose your interpolation engine. Here you can choose between the TIN-Interpolation method (
QgsTINInterpolator
) and IDW-Interpolation (QgsIDWInterpolator
). I took theQgsTINInterpolator
in my code.Keep in mind that you have to pass a python list of
layer_data
to the interpolation engine! This also allows you to add multiple layer_data scenarios.Step 4:
Setup the parameters that are needed for the export of the interpolation-output (see documentation of
QgsGridFileWriter
). Those include similar information as the interpolation gui (filepath, extent, resolution, number of colums and rows).Be aware of the file extension of your output-raster as
QgsGridFileWriter
only writes ASCII-grids (.asc
). The data gets written to disk by calling thewriteFile()
method. After export you can add the grid-file as raster to the canvas.Full script for reference:
Keep in mind that the QGIS-API is currently rewritten to version 3.0 and the used interpolation-classes are moved from
qgis.analysis
toqgis.core
! This will have a huge impact on the functionality of this script so that it must be rewritten for version 3.0!