QGIS API Documentation 4.3.0-Master (d3b565c628d)
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(
57 "This algorithm generates pixel centroids for the raster area falling inside polygons. Used to generate points "
58 "for further raster sampling."
59 );
60}
61
62QString QgsPixelCentroidsFromPolygonsAlgorithm::shortDescription() const
63{
64 return QObject::tr( "Generates pixel centroids for the raster area falling inside polygons." );
65}
66
67Qgis::ProcessingAlgorithmDocumentationFlags QgsPixelCentroidsFromPolygonsAlgorithm::documentationFlags() const
68{
70}
71
72QgsPixelCentroidsFromPolygonsAlgorithm *QgsPixelCentroidsFromPolygonsAlgorithm::createInstance() const
73{
74 return new QgsPixelCentroidsFromPolygonsAlgorithm();
75}
76
77void QgsPixelCentroidsFromPolygonsAlgorithm::initAlgorithm( const QVariantMap & )
78{
79 addParameter( new QgsProcessingParameterRasterLayer( u"INPUT_RASTER"_s, QObject::tr( "Raster layer" ) ) );
80 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT_VECTOR"_s, QObject::tr( "Vector layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
81
82 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Pixel centroids" ), Qgis::ProcessingSourceType::VectorPoint ) );
83}
84
85QVariantMap QgsPixelCentroidsFromPolygonsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
86{
87 QGS_MARK_ALGORITHM_SOURCE
88
89 QgsRasterLayer *rasterLayer = parameterAsRasterLayer( parameters, u"INPUT_RASTER"_s, context );
90
91 if ( !rasterLayer )
92 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT_RASTER"_s ) );
93
94 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT_VECTOR"_s, context ) );
95 if ( !source )
96 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT_VECTOR"_s ) );
97
98 QgsFields fields;
99 fields.append( QgsField( u"id"_s, QMetaType::Type::LongLong ) );
100 fields.append( QgsField( u"poly_id"_s, QMetaType::Type::Int ) );
101 fields.append( QgsField( u"point_id"_s, QMetaType::Type::Int ) );
102
103 QString dest;
104 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, Qgis::WkbType::Point, rasterLayer->crs(), QgsFeatureSink::RegeneratePrimaryKey ) );
105 if ( !sink )
106 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
107
108 const double step = source->featureCount() ? 100.0 / source->featureCount() : 1;
109 QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest().setDestinationCrs( rasterLayer->crs(), context.transformContext() ).setSubsetOfAttributes( QList<int>() ) );
110
111 const double xPixel = rasterLayer->rasterUnitsPerPixelX();
112 const double yPixel = rasterLayer->rasterUnitsPerPixelY();
113 const QgsRectangle extent = rasterLayer->extent();
114
115 QgsFeature feature;
116 feature.setFields( fields );
117
118 int fid = 0;
119 int pointId = 0;
120
121 int i = 0;
122 QgsFeature f;
123 while ( it.nextFeature( f ) )
124 {
125 if ( feedback->isCanceled() )
126 {
127 break;
128 }
129
130 if ( !f.hasGeometry() )
131 {
132 continue;
133 }
134
135 const QgsRectangle bbox = f.geometry().boundingBox();
136 const double xMin = bbox.xMinimum();
137 const double xMax = bbox.xMaximum();
138 const double yMin = bbox.yMinimum();
139 const double yMax = bbox.yMaximum();
140
141 double x, y;
142 int startRow, startColumn;
143 int endRow, endColumn;
144 QgsRasterAnalysisUtils::mapToPixel( xMin, yMax, extent, xPixel, yPixel, startRow, startColumn );
145 QgsRasterAnalysisUtils::mapToPixel( xMax, yMin, extent, xPixel, yPixel, endRow, endColumn );
146
147 auto engine = std::make_unique<QgsGeos>( f.geometry().constGet() );
148 engine->prepareGeometry();
149
150 for ( int row = startRow; row <= endRow; row++ )
151 {
152 for ( int col = startColumn; col <= endColumn; col++ )
153 {
154 if ( feedback->isCanceled() )
155 {
156 break;
157 }
158
159 QgsRasterAnalysisUtils::pixelToMap( row, col, extent, xPixel, yPixel, x, y );
160 if ( engine->contains( x, y ) )
161 {
162 feature.setGeometry( std::make_unique<QgsPoint>( x, y ) );
163 feature.setAttributes( QgsAttributes() << fid << i << pointId );
164 if ( !sink->addFeature( feature, QgsFeatureSink::FastInsert ) )
165 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
166 else
167 feedback->featureAddedToSink( u"OUTPUT"_s );
168
169 fid++;
170 pointId++;
171 }
172 }
173 }
174
175 pointId = 0;
176
177 feedback->setProgress( i * step );
178 i++;
179 }
180
181 sink->finalize();
182 feedback->featureSinkFinalized( u"OUTPUT"_s );
183
184 QVariantMap outputs;
185 outputs.insert( u"OUTPUT"_s, dest );
186 return outputs;
187}
188
@ VectorPoint
Vector point layers.
Definition qgis.h:3750
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3752
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3836
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3847
@ Point
Point.
Definition qgis.h:296
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:66
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:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:45
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
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.
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.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
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.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
double yMaximum