4

Is there any simple integration for calculating count of points in polygon using QGIS-Python integration?

In other words, are there any pre-defined functions for points in polygon of QGIS using python, so that we can use them in our python script?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Aug 25, 2015 at 21:08
2
  • Great questions, although It would be best to wrap these questions into a single question. Commented Aug 25, 2015 at 22:55
  • You can find some parallel code in this question counting points in current atlas feature: gis.stackexchange.com/questions/152296/… Commented Aug 26, 2015 at 6:20

6 Answers 6

6

I rewrote my answer from a parallel question counting points in current atlas feature: How to count points within the current Print composer atlas feature in QGIS 2.8?

Build a new function in the expression editor:

from qgis.core import *
from qgis.gui import *
from qgis.utils import iface
@qgsfunction(args="auto", group='Custom')
 def countPointsInPolygon(pointLayerName, geom, feature, parent):
 # If point geom is empty, return 0
 if (geom is None):
 return 0
 # Get point layer reference from layername
 pointLayer = QgsMapLayerRegistry.instance().mapLayersByName(pointLayerName)[0]
 # Raise if layer not found
 if pointLayer is None:
 raise Exception("Layer not found: " + pointLayerName)
 # Count point within current polygon feature
 countPoint = 0
 for pointFeature in pointLayer.getFeatures():
 pointGeom = pointFeature.geometry()
 if (pointGeom is None):
 continue
 if pointGeom.within(geom):
 countPoint += 1
 return countPoint 

Use it as a expression on the polygon layer where 'mypoints' is the name of the point layer: countPointsInPolygon( 'mypoints', $geometry )

If you don't want it implemented as an expression, you can call the function from your own script looping the features of the polygon layer calling countPointsInPolygon for each feature.

answered Aug 26, 2015 at 6:44
4

There are also tools from the Processing Toolbox which you could call from your script (this is assuming you are running scripts inside QGIS):

  • Count points in polygon
  • Counts points in polygon (weighted)
  • Count unique points in polygon

Taking the first tool, you could call it using:

import processing
Result = "path\to\saved_output.shp"
processing.runalg("qgis:countpointsinpolygon", "path\to\polygon_layer.shp", "path\to\point_layer.shp", 'NUMPOINTS', Result)

where NUMPOINTS is the name of the field which stores the number of points.

I'm using QGIS 2.8.2-Wien, Processing plugin v2.9.3.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
answered Aug 26, 2015 at 11:01
0
2

The simplest way is to use "Join attribute by location". You can do it from the menu (data managment > Join by location), or with Python ("qgis:joinbylocation") with the option "take summary of intersecting features", computing the sum of a field with "1" at each point.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
answered Aug 26, 2015 at 8:23
1

I have never worked with QGIS's python API, so my answer is a wild guess. But it looks like QGIS is using GEOS geometry objects similar to django. So this could work in QGIS too:

len(geom.coords)
answered Aug 25, 2015 at 22:46
1
  • Good guess but that is not what I am asking. I have every thing points, polygon. what I just want is to calculate the points in the polygon using pyqgis Commented Aug 25, 2015 at 22:52
1

I assume your polygon is a qgsfeature :

http://qgis.org/api/classQgsFeature.html

I didn't test it but I guess it would work :

len(polygon.geometry().asPolygon())

polygon.geometry() gives a qgsgeometry class.

qgsgeometry.asPolygon() gives a list of the point of your polygon.

Edit : You want the points inside the polygon? You have points in an other layer and wonder which ones intersect your polygon?

answered Aug 25, 2015 at 22:55
1

QGIS 3 has a processing tool for this task - Count points in polygon.

You can call it with pyqgis using this code:

processing.run(
"native:countpointsinpolygon", 
{'POLYGONS':'D:/POLYGONS.gpkg|layername=POLYGONS',
'POINTS': 'D:/POINTS.gpkg|layername=POINTS',
'WEIGHT':'',
'CLASSFIELD':'',
'FIELD':'NUMPOINTS',
'OUTPUT':'TEMPORARY_OUTPUT'}
)
answered Oct 31, 2024 at 5:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.