0

I am trying to calculate the centroids of polygons using PyQGIS.

When I calculate the centroids with the interface (Vector --> Geometry Tools --> Polygon Centroids) everything works out.

However, I fail to reproduce the same using the python console in QGIS (version 2.18.16).

Following the history output after conducting the operation manually as well as the QGIS documentation, I use this line of code:

processing.runalg("qgis:polygoncentroids", shapefile, "memory:")

This produces the error:

NameError: name 'processing' is not defined

What am I doing wrong here?

  • I still feel new to this site. Please let me know if and how I can improve my question to help you answer it. Thanks a lot. – eigenvector Jul 21 '18 at 13:45
3

To solve your problem you should only import the module before executing the command (usually this is not necessary).

import processing

If you want to use QGIS 3 to calculate the centroids of a polygon layer you can execute the following command:

processing.run("native:centroids", {'INPUT':'D:/polygons.shp','ALL_PARTS':False,'OUTPUT':'memory:'})

If you have a MultiPolygon layer and for each part you want to calculate its centroid you can execute the following command:

processing.run("native:centroids", {'INPUT':'D:/polygons.shp','ALL_PARTS':True,'OUTPUT':'memory:'})
2

You must Import the processing library

import processing
shapefile = "c:/tar/polygon.shp"
processing.runandload("qgis:polygoncentroids", shapefile, "memory")

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.