Skip to content

Commit

Permalink
Port Points From Polygons to new API
Browse files Browse the repository at this point in the history
  • Loading branch information
nyalldawson committed Aug 13, 2017
1 parent c8ac784 commit c6b3855
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 30 deletions.
60 changes: 34 additions & 26 deletions python/plugins/processing/algs/qgis/PointsFromPolygons.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,29 +28,30 @@
__revision__ = '$Format:%H$'

from osgeo import gdal
from qgis.core import (QgsApplication,
from qgis.core import (QgsFeatureRequest,
QgsFields,
QgsField,
QgsFeature,
QgsFeatureSink,
QgsGeometry,
QgsWkbTypes,
QgsPointXY,
QgsProcessingUtils)
QgsProcessingParameterBand,
QgsPoint,
QgsProcessing,
QgsProcessingParameterRasterLayer,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterFeatureSink)
from qgis.PyQt.QtCore import QVariant
from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
from processing.core.parameters import ParameterRaster
from processing.core.parameters import ParameterVector
from processing.core.outputs import OutputVector
from processing.tools import dataobjects, raster
from processing.tools import raster
from processing.tools.dataobjects import exportRasterLayer


class PointsFromPolygons(QgisAlgorithm):

INPUT_RASTER = 'INPUT_RASTER'
RASTER_BAND = 'RASTER_BAND'
INPUT_VECTOR = 'INPUT_VECTOR'
OUTPUT_LAYER = 'OUTPUT_LAYER'
OUTPUT = 'OUTPUT'

def group(self):
return self.tr('Vector analysis tools')
Expand All @@ -59,11 +60,11 @@ def __init__(self):
super().__init__()

def initAlgorithm(self, config=None):
self.addParameter(ParameterRaster(self.INPUT_RASTER,
self.tr('Raster layer')))
self.addParameter(ParameterVector(self.INPUT_VECTOR,
self.tr('Vector layer'), [dataobjects.TYPE_VECTOR_POLYGON]))
self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Points from polygons'), datatype=[dataobjects.TYPE_VECTOR_POINT]))
self.addParameter(QgsProcessingParameterRasterLayer(self.INPUT_RASTER,
self.tr('Raster layer')))
self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT_VECTOR,
self.tr('Vector layer'), [QgsProcessing.TypeVectorPolygon]))
self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT, self.tr('Points from polygons'), QgsProcessing.TypeVectorPoint))

def name(self):
return 'generatepointspixelcentroidsinsidepolygons'
Expand All @@ -72,21 +73,21 @@ def displayName(self):
return self.tr('Generate points (pixel centroids) inside polygons')

def processAlgorithm(self, parameters, context, feedback):
layer = QgsProcessingUtils.mapLayerFromString(self.getParameterValue(self.INPUT_VECTOR), context)
source = self.parameterAsSource(parameters, self.INPUT_VECTOR, context)

rasterPath = str(self.getParameterValue(self.INPUT_RASTER))
raster_layer = self.parameterAsRasterLayer(parameters, self.INPUT_RASTER, context)
rasterPath = exportRasterLayer(raster_layer)

rasterDS = gdal.Open(rasterPath, gdal.GA_ReadOnly)
geoTransform = rasterDS.GetGeoTransform()
rasterDS = None

fields = QgsFields()
fields.append(QgsField('id', QVariant.Int, '', 10, 0))
fields.append(QgsField('poly_id', QVariant.Int, '', 10, 0))
fields.append(QgsField('point_id', QVariant.Int, '', 10, 0))

writer = self.getOutputFromName(self.OUTPUT_LAYER).getVectorWriter(fields, QgsWkbTypes.Point,
layer.crs(), context)
(sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
fields, QgsWkbTypes.PointZ, raster_layer.crs())

outFeature = QgsFeature()
outFeature.setFields(fields)
Expand All @@ -95,9 +96,15 @@ def processAlgorithm(self, parameters, context, feedback):
polyId = 0
pointId = 0

features = QgsProcessingUtils.getFeatures(layer, context)
total = 100.0 / layer.featureCount() if layer.featureCount() else 0
features = source.getFeatures(QgsFeatureRequest().setDestinationCrs(raster_layer.crs()))
total = 100.0 / source.featureCount() if source.featureCount() else 0
for current, f in enumerate(features):
if feedback.isCanceled():
break

if not f.hasGeometry():
continue

geom = f.geometry()
bbox = geom.boundingBox()

Expand All @@ -115,10 +122,11 @@ def processAlgorithm(self, parameters, context, feedback):

for row in range(startRow, endRow + 1):
for col in range(startColumn, endColumn + 1):
if feedback.isCanceled():
break

(x, y) = raster.pixelToMap(row, col, geoTransform)
point = QgsPointXY()
point.setX(x)
point.setY(y)
point = QgsPoint(x, y)

if engine.contains(point):
outFeature.setGeometry(QgsGeometry(point))
Expand All @@ -129,11 +137,11 @@ def processAlgorithm(self, parameters, context, feedback):
fid += 1
pointId += 1

writer.addFeature(outFeature, QgsFeatureSink.FastInsert)
sink.addFeature(outFeature, QgsFeatureSink.FastInsert)

pointId = 0
polyId += 1

feedback.setProgress(int(current * total))

del writer
return {self.OUTPUT: dest_id}
6 changes: 2 additions & 4 deletions python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
from .PointOnSurface import PointOnSurface
from .PointsAlongGeometry import PointsAlongGeometry
from .PointsDisplacement import PointsDisplacement
from .PointsFromPolygons import PointsFromPolygons
from .PointsInPolygon import PointsInPolygon
from .PointsLayerFromTable import PointsLayerFromTable
from .PointsToPaths import PointsToPaths
Expand Down Expand Up @@ -154,7 +155,6 @@
# from .GeometryConvert import GeometryConvert
# from .FieldsCalculator import FieldsCalculator
# from .FieldPyculator import FieldsPyculator
# from .PointsFromPolygons import PointsFromPolygons
# from .PointsFromLines import PointsFromLines
# from .SetVectorStyle import SetVectorStyle
# from .SetRasterStyle import SetRasterStyle
Expand Down Expand Up @@ -191,9 +191,6 @@ def getAlgs(self):
# SpatialJoin(),
# GeometryConvert(), FieldsCalculator(),
# FieldsPyculator(),
#
# RasterLayerStatistics(),
# PointsFromPolygons(),
# PointsFromLines(),
# SetVectorStyle(), SetRasterStyle(),
# HypsometricCurves(),
Expand Down Expand Up @@ -262,6 +259,7 @@ def getAlgs(self):
PointOnSurface(),
PointsAlongGeometry(),
PointsDisplacement(),
PointsFromPolygons(),
PointsInPolygon(),
PointsLayerFromTable(),
PointsToPaths(),
Expand Down
14 changes: 14 additions & 0 deletions python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2919,3 +2919,17 @@ tests:
OUTPUT:
name: expected/displaced_points.gml
type: vector

- algorithm: qgis:generatepointspixelcentroidsinsidepolygons
name: Pixel centroids inside polygon
params:
INPUT_RASTER:
name: dem.tif
type: raster
INPUT_VECTOR:
name: custom/pixel_polygons.gml
type: vector
results:
OUTPUT:
name: expected/pixel_centroids_polygon.gml
type: vector

0 comments on commit c6b3855

Please sign in to comment.