QGIS API Documentation 3.99.0-Master (09f76ad7019)
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
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29QString QgsPixelCentroidsFromPolygonsAlgorithm::name() const
30{
31 return u"generatepointspixelcentroidsinsidepolygons"_s;
32}
33
34QString QgsPixelCentroidsFromPolygonsAlgorithm::displayName() const
35{
36 return QObject::tr( "Generate points (pixel centroids) inside polygons" );
37}
38
39QStringList QgsPixelCentroidsFromPolygonsAlgorithm::tags() const
40{
41 return QObject::tr( "raster,polygon,centroid,pixel,create" ).split( ',' );
42}
43
44QString QgsPixelCentroidsFromPolygonsAlgorithm::group() const
45{
46 return QObject::tr( "Vector creation" );
47}
48
49QString QgsPixelCentroidsFromPolygonsAlgorithm::groupId() const
50{
51 return u"vectorcreation"_s;
52}
53
54QString QgsPixelCentroidsFromPolygonsAlgorithm::shortHelpString() const
55{
56 return QObject::tr( "This algorithm generates pixel centroids for the raster area falling inside polygons. Used to generate points "
57 "for further raster sampling." );
58}
59
60QString QgsPixelCentroidsFromPolygonsAlgorithm::shortDescription() const
61{
62 return QObject::tr( "Generates pixel centroids for the raster area falling inside polygons." );
63}
64
65Qgis::ProcessingAlgorithmDocumentationFlags QgsPixelCentroidsFromPolygonsAlgorithm::documentationFlags() const
66{
68}
69
70QgsPixelCentroidsFromPolygonsAlgorithm *QgsPixelCentroidsFromPolygonsAlgorithm::createInstance() const
71{
72 return new QgsPixelCentroidsFromPolygonsAlgorithm();
73}
74
75void QgsPixelCentroidsFromPolygonsAlgorithm::initAlgorithm( const QVariantMap & )
76{
77 addParameter( new QgsProcessingParameterRasterLayer( u"INPUT_RASTER"_s, QObject::tr( "Raster layer" ) ) );
78 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT_VECTOR"_s, QObject::tr( "Vector layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
79
80 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Pixel centroids" ), Qgis::ProcessingSourceType::VectorPoint ) );
81}
82
83QVariantMap QgsPixelCentroidsFromPolygonsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
84{
85 QgsRasterLayer *rasterLayer = parameterAsRasterLayer( parameters, u"INPUT_RASTER"_s, context );
86
87 if ( !rasterLayer )
88 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT_RASTER"_s ) );
89
90 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT_VECTOR"_s, context ) );
91 if ( !source )
92 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT_VECTOR"_s ) );
93
94 QgsFields fields;
95 fields.append( QgsField( u"id"_s, QMetaType::Type::LongLong ) );
96 fields.append( QgsField( u"poly_id"_s, QMetaType::Type::Int ) );
97 fields.append( QgsField( u"point_id"_s, QMetaType::Type::Int ) );
98
99 QString dest;
100 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, Qgis::WkbType::Point, rasterLayer->crs(), QgsFeatureSink::RegeneratePrimaryKey ) );
101 if ( !sink )
102 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
103
104 const double step = source->featureCount() ? 100.0 / source->featureCount() : 1;
105 QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest().setDestinationCrs( rasterLayer->crs(), context.transformContext() ).setSubsetOfAttributes( QList<int>() ) );
106
107 const double xPixel = rasterLayer->rasterUnitsPerPixelX();
108 const double yPixel = rasterLayer->rasterUnitsPerPixelY();
109 const QgsRectangle extent = rasterLayer->extent();
110
111 QgsFeature feature;
112 feature.setFields( fields );
113
114 int fid = 0;
115 int pointId = 0;
116
117 int i = 0;
118 QgsFeature f;
119 while ( it.nextFeature( f ) )
120 {
121 if ( feedback->isCanceled() )
122 {
123 break;
124 }
125
126 if ( !f.hasGeometry() )
127 {
128 continue;
129 }
130
131 const QgsRectangle bbox = f.geometry().boundingBox();
132 const double xMin = bbox.xMinimum();
133 const double xMax = bbox.xMaximum();
134 const double yMin = bbox.yMinimum();
135 const double yMax = bbox.yMaximum();
136
137 double x, y;
138 int startRow, startColumn;
139 int endRow, endColumn;
140 QgsRasterAnalysisUtils::mapToPixel( xMin, yMax, extent, xPixel, yPixel, startRow, startColumn );
141 QgsRasterAnalysisUtils::mapToPixel( xMax, yMin, extent, xPixel, yPixel, endRow, endColumn );
142
143 auto engine = std::make_unique<QgsGeos>( f.geometry().constGet() );
144 engine->prepareGeometry();
145
146 for ( int row = startRow; row <= endRow; row++ )
147 {
148 for ( int col = startColumn; col <= endColumn; col++ )
149 {
150 if ( feedback->isCanceled() )
151 {
152 break;
153 }
154
155 QgsRasterAnalysisUtils::pixelToMap( row, col, extent, xPixel, yPixel, x, y );
156 if ( engine->contains( x, y ) )
157 {
158 feature.setGeometry( std::make_unique<QgsPoint>( x, y ) );
159 feature.setAttributes( QgsAttributes() << fid << i << pointId );
160 if ( !sink->addFeature( feature, QgsFeatureSink::FastInsert ) )
161 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
162
163 fid++;
164 pointId++;
165 }
166 }
167 }
168
169 pointId = 0;
170
171 feedback->setProgress( i * step );
172 i++;
173 }
174
175 sink->finalize();
176
177 QVariantMap outputs;
178 outputs.insert( u"OUTPUT"_s, dest );
179 return outputs;
180}
181
@ VectorPoint
Vector point layers.
Definition qgis.h:3605
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3607
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3690
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3701
@ Point
Point.
Definition qgis.h:282
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:60
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:71
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:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
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:76
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:90
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