QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsalgorithmpixelcentroidsfrompolygons.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmpixelcentroidsfrompolygons.cpp
3 ---------------------
4 begin : December 2019
5 copyright : (C) 2019 by Alexander Bruy
6 email : alexander dot bruy at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
20#include "qgsgeos.h"
22
24
25QString QgsPixelCentroidsFromPolygonsAlgorithm::name() const
26{
27 return QStringLiteral( "generatepointspixelcentroidsinsidepolygons" );
28}
29
30QString QgsPixelCentroidsFromPolygonsAlgorithm::displayName() const
31{
32 return QObject::tr( "Generate points (pixel centroids) inside polygons" );
33}
34
35QStringList QgsPixelCentroidsFromPolygonsAlgorithm::tags() const
36{
37 return QObject::tr( "raster,polygon,centroid,pixel,create" ).split( ',' );
38}
39
40QString QgsPixelCentroidsFromPolygonsAlgorithm::group() const
41{
42 return QObject::tr( "Vector creation" );
43}
44
45QString QgsPixelCentroidsFromPolygonsAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectorcreation" );
48}
49
50QString QgsPixelCentroidsFromPolygonsAlgorithm::shortHelpString() const
51{
52 return QObject::tr( "This algorithm generates pixel centroids for the raster area falling inside polygons. Used to generate points "
53 "for further raster sampling." );
54}
55
56QString QgsPixelCentroidsFromPolygonsAlgorithm::shortDescription() const
57{
58 return QObject::tr( "Generates pixel centroids for the raster area falling inside polygons." );
59}
60
61Qgis::ProcessingAlgorithmDocumentationFlags QgsPixelCentroidsFromPolygonsAlgorithm::documentationFlags() const
62{
64}
65
66QgsPixelCentroidsFromPolygonsAlgorithm *QgsPixelCentroidsFromPolygonsAlgorithm::createInstance() const
67{
68 return new QgsPixelCentroidsFromPolygonsAlgorithm();
69}
70
71void QgsPixelCentroidsFromPolygonsAlgorithm::initAlgorithm( const QVariantMap & )
72{
73 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT_RASTER" ), QObject::tr( "Raster layer" ) ) );
74 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT_VECTOR" ), QObject::tr( "Vector layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
75
76 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Pixel centroids" ), Qgis::ProcessingSourceType::VectorPoint ) );
77}
78
79QVariantMap QgsPixelCentroidsFromPolygonsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
80{
81 QgsRasterLayer *rasterLayer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT_RASTER" ), context );
82
83 if ( !rasterLayer )
84 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT_RASTER" ) ) );
85
86 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT_VECTOR" ), context ) );
87 if ( !source )
88 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT_VECTOR" ) ) );
89
90 QgsFields fields;
91 fields.append( QgsField( QStringLiteral( "id" ), QMetaType::Type::LongLong ) );
92 fields.append( QgsField( QStringLiteral( "poly_id" ), QMetaType::Type::Int ) );
93 fields.append( QgsField( QStringLiteral( "point_id" ), QMetaType::Type::Int ) );
94
95 QString dest;
96 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, Qgis::WkbType::Point, rasterLayer->crs(), QgsFeatureSink::RegeneratePrimaryKey ) );
97 if ( !sink )
98 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
99
100 const double step = source->featureCount() ? 100.0 / source->featureCount() : 1;
101 QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest().setDestinationCrs( rasterLayer->crs(), context.transformContext() ).setSubsetOfAttributes( QList<int>() ) );
102
103 const double xPixel = rasterLayer->rasterUnitsPerPixelX();
104 const double yPixel = rasterLayer->rasterUnitsPerPixelY();
105 const QgsRectangle extent = rasterLayer->extent();
106
107 QgsFeature feature;
108 feature.setFields( fields );
109
110 int fid = 0;
111 int pointId = 0;
112
113 int i = 0;
114 QgsFeature f;
115 while ( it.nextFeature( f ) )
116 {
117 if ( feedback->isCanceled() )
118 {
119 break;
120 }
121
122 if ( !f.hasGeometry() )
123 {
124 continue;
125 }
126
127 const QgsRectangle bbox = f.geometry().boundingBox();
128 const double xMin = bbox.xMinimum();
129 const double xMax = bbox.xMaximum();
130 const double yMin = bbox.yMinimum();
131 const double yMax = bbox.yMaximum();
132
133 double x, y;
134 int startRow, startColumn;
135 int endRow, endColumn;
136 QgsRasterAnalysisUtils::mapToPixel( xMin, yMax, extent, xPixel, yPixel, startRow, startColumn );
137 QgsRasterAnalysisUtils::mapToPixel( xMax, yMin, extent, xPixel, yPixel, endRow, endColumn );
138
139 auto engine = std::make_unique<QgsGeos>( f.geometry().constGet() );
140 engine->prepareGeometry();
141
142 for ( int row = startRow; row <= endRow; row++ )
143 {
144 for ( int col = startColumn; col <= endColumn; col++ )
145 {
146 if ( feedback->isCanceled() )
147 {
148 break;
149 }
150
151 QgsRasterAnalysisUtils::pixelToMap( row, col, extent, xPixel, yPixel, x, y );
152 if ( engine->contains( x, y ) )
153 {
154 feature.setGeometry( std::make_unique<QgsPoint>( x, y ) );
155 feature.setAttributes( QgsAttributes() << fid << i << pointId );
156 if ( !sink->addFeature( feature, QgsFeatureSink::FastInsert ) )
157 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
158
159 fid++;
160 pointId++;
161 }
162 }
163 }
164
165 pointId = 0;
166
167 feedback->setProgress( i * step );
168 i++;
169 }
170
171 sink->finalize();
172
173 QVariantMap outputs;
174 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
175 return outputs;
176}
177
@ VectorPoint
Vector point layers.
Definition qgis.h:3534
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3536
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3619
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3630
@ Point
Point.
Definition qgis.h:279
A vector of attributes.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
void setFields(const QgsFields &fields, bool initAttributes=false)
Assigns a field map with the feature to allow attribute access by attribute name.
QgsGeometry geometry
Definition qgsfeature.h:69
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:54
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:73
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
virtual QgsRectangle extent() const
Returns the extent of the layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:87
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A raster layer parameter for processing algorithms.
Represents a raster layer.
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
double rasterUnitsPerPixelY() const
Returns the number of raster units per each raster pixel in Y axis.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
double yMaximum