QGIS 3.16.5 seems to crash when I use the following code block in the QGIS console.

However, there seems to be no issue at all when clicking through the same options using the GUI. The TIN interpolator works as expected when plugging-in through the GUI.

I have gone through the answers Calling interpolation plugin from Python console of QGIS and Interpolation (TIN) from Python Console in QGIS

import qgis.analysis
import qgis.core

file_path = 'D:/codebase'
pathToFile = f"{file_path}/gpd_df.shp"
layer = QgsVectorLayer(pathToFile, 'input','ogr')
layer_data = QgsInterpolator.LayerData()
layer_data.vectorLayer = layer
index = layer.fields().indexFromName("altitude")
layer_data.interpolationAttribute = index
layer_data.sourceType = QgsInterpolator.SourcePoints
interpolation_method = QgsTinInterpolator.Linear
tin_interpolator = QgsTinInterpolator([layer_data], interpolation_method)
export_path = "D:/codebase/test.tif"
# also tried export_path = "D:/codebase/test.asc"

rect = layer.extent()
res = 10
ncol = int( ( rect.xMaximum() - rect.xMinimum() ) / res )
nrows = int( (rect.yMaximum() - rect.yMinimum() ) / res)
output = QgsGridFileWriter(tin_interpolator, export_path, rect, ncol, nrows)
iface.addRasterLayer(export_path, "output")

gpd_df.shp (which loads as expected when used through GUI) file looks like the following table in the image attached.

gpd_df shape file with headers


Answers you used were initially for QGIS 2.x. They work for QGIS 3.0 too with some adaptations but IMO, you can make your life easier by calling the "interpolator" from PyQGIS processing algorithms available in "Processing Toolbox". See below GIF to understand that when you run an algorithm, in the history, you get the Python code executed.

Discover how to reuse processing algorithms in PyQGIS

From the last image in above GIF, I've copy & paste the part processing.run(... below, assigned to a variable result and finish by adding the resulting layer output

result = processing.run("qgis:tininterpolation", {
    'EXTENT':'5.053357400,8.904926200,43.502162600,45.567573400 [EPSG:4326]',
iface.addRasterLayer(result['OUTPUT'], "output file")

Do the same steps as below demo on your own dataset. You can now substitute some content with your specific parameters, making them dynamic if necessary.

To learn more about how to run Python processing algorithms, you may also look at https://docs.qgis.org/3.16/en/docs/user_manual/processing/console.html#calling-algorithms-from-the-python-console

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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