QGIS API Documentation 4.3.0-Master (45633be667c)
Loading...
Searching...
No Matches
qgsalgorithmvectorize.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmvectorize.cpp
3 ---------------------
4 begin : June, 2018
5 copyright : (C) 2018 by Nyall Dawson
6 email : nyall dot dawson 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 "qgis.h"
21#include "qgsprocessing.h"
22
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29QString QgsVectorizeAlgorithmBase::group() const
30{
31 return QObject::tr( "Vector creation" );
32}
33
34QString QgsVectorizeAlgorithmBase::groupId() const
35{
36 return u"vectorcreation"_s;
37}
38
39void QgsVectorizeAlgorithmBase::initAlgorithm( const QVariantMap & )
40{
41 addParameter( new QgsProcessingParameterRasterLayer( u"INPUT_RASTER"_s, QObject::tr( "Raster layer" ) ) );
42 addParameter( new QgsProcessingParameterBand( u"RASTER_BAND"_s, QObject::tr( "Band number" ), 1, u"INPUT_RASTER"_s ) );
43 addParameter( new QgsProcessingParameterString( u"FIELD_NAME"_s, QObject::tr( "Field name" ), u"VALUE"_s ) );
44
45 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, outputName(), outputType() ) );
46}
47
48bool QgsVectorizeAlgorithmBase::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
49{
50 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, u"INPUT_RASTER"_s, context );
51
52 if ( !layer )
53 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT_RASTER"_s ) );
54
55 mBand = parameterAsInt( parameters, u"RASTER_BAND"_s, context );
56 if ( mBand < 1 || mBand > layer->bandCount() )
57 throw QgsProcessingException( QObject::tr( "Invalid band number for RASTER_BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).arg( layer->bandCount() ) );
58
59 mInterface.reset( layer->dataProvider()->clone() );
60 mExtent = layer->extent();
61 mCrs = layer->crs();
62 mRasterUnitsPerPixelX = std::abs( layer->rasterUnitsPerPixelX() );
63 mRasterUnitsPerPixelY = std::abs( layer->rasterUnitsPerPixelY() );
64 mNbCellsXProvider = mInterface->xSize();
65 mNbCellsYProvider = mInterface->ySize();
66 return true;
67}
68
69QVariantMap QgsVectorizeAlgorithmBase::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
70{
71 const QString fieldName = parameterAsString( parameters, u"FIELD_NAME"_s, context );
72 QgsFields fields;
73 fields.append( QgsField( fieldName, QMetaType::Type::Double, QString(), 20, 8 ) );
74
75 QString dest;
76 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, sinkType(), mCrs ) );
77 if ( !sink )
78 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
79
80 QgsRasterIterator iter( mInterface.get() );
81 iter.startRasterRead( mBand, mNbCellsXProvider, mNbCellsYProvider, mExtent );
82
83 int iterLeft = 0;
84 int iterTop = 0;
85 int iterCols = 0;
86 int iterRows = 0;
87 std::unique_ptr<QgsRasterBlock> rasterBlock;
88 QgsRectangle blockExtent;
89 bool isNoData = false;
90 while ( iter.readNextRasterPart( mBand, iterCols, iterRows, rasterBlock, iterLeft, iterTop, &blockExtent ) )
91 {
92 if ( feedback )
93 feedback->setProgress( 100 * iter.progress( mBand ) );
94 if ( feedback && feedback->isCanceled() )
95 break;
96
97 double currentY = blockExtent.yMaximum() - 0.5 * mRasterUnitsPerPixelY;
98
99 for ( int row = 0; row < iterRows; row++ )
100 {
101 if ( feedback && feedback->isCanceled() )
102 break;
103
104 double currentX = blockExtent.xMinimum() + 0.5 * mRasterUnitsPerPixelX;
105
106 for ( int column = 0; column < iterCols; column++ )
107 {
108 const double value = rasterBlock->valueAndNoData( row, column, isNoData );
109 if ( !isNoData )
110 {
111 const QgsGeometry pixelRectGeometry = createGeometryForPixel( currentX, currentY, mRasterUnitsPerPixelX, mRasterUnitsPerPixelY );
112
113 QgsFeature f;
114 f.setGeometry( pixelRectGeometry );
115 f.setAttributes( QgsAttributes() << value );
116 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
117 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
118 else
119 feedback->featureAddedToSink( u"OUTPUT"_s );
120 }
121 currentX += mRasterUnitsPerPixelX;
122 }
123 currentY -= mRasterUnitsPerPixelY;
124 }
125 }
126
127 sink->finalize();
128 feedback->featureSinkFinalized( u"OUTPUT"_s );
129
130 QVariantMap outputs;
131 outputs.insert( u"OUTPUT"_s, dest );
132 return outputs;
133}
134
135//
136// QgsRasterPixelsToPolygonsAlgorithm
137//
138
139QString QgsRasterPixelsToPolygonsAlgorithm::name() const
140{
141 return u"pixelstopolygons"_s;
142}
143
144QString QgsRasterPixelsToPolygonsAlgorithm::displayName() const
145{
146 return QObject::tr( "Raster pixels to polygons" );
147}
148
149QStringList QgsRasterPixelsToPolygonsAlgorithm::tags() const
150{
151 return QObject::tr( "vectorize,polygonize,raster,convert,pixels" ).split( ',' );
152}
153
154QString QgsRasterPixelsToPolygonsAlgorithm::shortHelpString() const
155{
156 return QObject::tr(
157 "This algorithm converts a raster layer to a vector layer, by creating polygon features "
158 "for each individual pixel's extent in the raster layer.\n\n"
159 "Any NoData pixels are skipped in the output."
160 );
161}
162
163QString QgsRasterPixelsToPolygonsAlgorithm::shortDescription() const
164{
165 return QObject::tr( "Creates a vector layer of polygons corresponding to each pixel in a raster layer." );
166}
167
168QgsRasterPixelsToPolygonsAlgorithm *QgsRasterPixelsToPolygonsAlgorithm::createInstance() const
169{
170 return new QgsRasterPixelsToPolygonsAlgorithm();
171}
172
173QString QgsRasterPixelsToPolygonsAlgorithm::outputName() const
174{
175 return QObject::tr( "Vector polygons" );
176}
177
178Qgis::ProcessingSourceType QgsRasterPixelsToPolygonsAlgorithm::outputType() const
179{
181}
182
183Qgis::WkbType QgsRasterPixelsToPolygonsAlgorithm::sinkType() const
184{
186}
187
188QgsGeometry QgsRasterPixelsToPolygonsAlgorithm::createGeometryForPixel( double centerX, double centerY, double pixelWidthX, double pixelWidthY ) const
189{
190 QGS_MARK_ALGORITHM_SOURCE
191
192 const double hCellSizeX = pixelWidthX / 2.0;
193 const double hCellSizeY = pixelWidthY / 2.0;
194 return QgsGeometry::fromRect( QgsRectangle( centerX - hCellSizeX, centerY - hCellSizeY, centerX + hCellSizeX, centerY + hCellSizeY ) );
195}
196
197
198//
199// QgsRasterPixelsToPointsAlgorithm
200//
201
202QString QgsRasterPixelsToPointsAlgorithm::name() const
203{
204 return u"pixelstopoints"_s;
205}
206
207QString QgsRasterPixelsToPointsAlgorithm::displayName() const
208{
209 return QObject::tr( "Raster pixels to points" );
210}
211
212QStringList QgsRasterPixelsToPointsAlgorithm::tags() const
213{
214 return QObject::tr( "vectorize,polygonize,raster,convert,pixels,centers" ).split( ',' );
215}
216
217QString QgsRasterPixelsToPointsAlgorithm::shortHelpString() const
218{
219 return QObject::tr(
220 "This algorithm converts a raster layer to a vector layer, by creating point features "
221 "for each individual pixel's center in the raster layer.\n\n"
222 "Any NoData pixels are skipped in the output."
223 );
224}
225
226QString QgsRasterPixelsToPointsAlgorithm::shortDescription() const
227{
228 return QObject::tr( "Creates a vector layer of points corresponding to each pixel in a raster layer." );
229}
230
231QgsRasterPixelsToPointsAlgorithm *QgsRasterPixelsToPointsAlgorithm::createInstance() const
232{
233 return new QgsRasterPixelsToPointsAlgorithm();
234}
235
236QString QgsRasterPixelsToPointsAlgorithm::outputName() const
237{
238 return QObject::tr( "Vector points" );
239}
240
241Qgis::ProcessingSourceType QgsRasterPixelsToPointsAlgorithm::outputType() const
242{
244}
245
246Qgis::WkbType QgsRasterPixelsToPointsAlgorithm::sinkType() const
247{
249}
250
251QgsGeometry QgsRasterPixelsToPointsAlgorithm::createGeometryForPixel( double centerX, double centerY, double, double ) const
252{
253 QGS_MARK_ALGORITHM_SOURCE
254
255 return QgsGeometry( new QgsPoint( centerX, centerY ) );
256}
257
ProcessingSourceType
Processing data source types.
Definition qgis.h:3749
@ VectorPoint
Vector point layers.
Definition qgis.h:3752
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3754
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:294
@ Point
Point.
Definition qgis.h:296
@ Polygon
Polygon.
Definition qgis.h:298
A vector of attributes.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
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 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
A geometry is the spatial representation of a feature.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
virtual Q_INVOKABLE QgsRectangle extent() const
Returns the extent of the layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:90
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
Contains information about the context in which a processing algorithm is executed.
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 raster band parameter for Processing algorithms.
A feature sink output for processing algorithms.
A raster layer parameter for processing algorithms.
A string parameter for processing algorithms.
QgsRasterDataProvider * clone() const override=0
Clone itself, create deep copy.
Iterator for sequentially processing raster cells.
Represents a raster layer.
int bandCount() const
Returns the number of bands in this layer.
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
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 yMaximum