QGIS API Documentation 3.99.0-Master (2fe06baccd8)
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
24
25QString QgsVectorizeAlgorithmBase::group() const
26{
27 return QObject::tr( "Vector creation" );
28}
29
30QString QgsVectorizeAlgorithmBase::groupId() const
31{
32 return QStringLiteral( "vectorcreation" );
33}
34
35void QgsVectorizeAlgorithmBase::initAlgorithm( const QVariantMap & )
36{
37 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT_RASTER" ), QObject::tr( "Raster layer" ) ) );
38 addParameter( new QgsProcessingParameterBand( QStringLiteral( "RASTER_BAND" ), QObject::tr( "Band number" ), 1, QStringLiteral( "INPUT_RASTER" ) ) );
39 addParameter( new QgsProcessingParameterString( QStringLiteral( "FIELD_NAME" ), QObject::tr( "Field name" ), QStringLiteral( "VALUE" ) ) );
40
41 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), outputName(), outputType() ) );
42}
43
44bool QgsVectorizeAlgorithmBase::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
45{
46 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT_RASTER" ), context );
47
48 if ( !layer )
49 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT_RASTER" ) ) );
50
51 mBand = parameterAsInt( parameters, QStringLiteral( "RASTER_BAND" ), context );
52 if ( mBand < 1 || mBand > layer->bandCount() )
53 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() ) );
54
55 mInterface.reset( layer->dataProvider()->clone() );
56 mExtent = layer->extent();
57 mCrs = layer->crs();
58 mRasterUnitsPerPixelX = std::abs( layer->rasterUnitsPerPixelX() );
59 mRasterUnitsPerPixelY = std::abs( layer->rasterUnitsPerPixelY() );
60 mNbCellsXProvider = mInterface->xSize();
61 mNbCellsYProvider = mInterface->ySize();
62 return true;
63}
64
65QVariantMap QgsVectorizeAlgorithmBase::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
66{
67 const QString fieldName = parameterAsString( parameters, QStringLiteral( "FIELD_NAME" ), context );
68 QgsFields fields;
69 fields.append( QgsField( fieldName, QMetaType::Type::Double, QString(), 20, 8 ) );
70
71 QString dest;
72 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, sinkType(), mCrs ) );
73 if ( !sink )
74 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
75
76
79
80 QgsRasterIterator iter( mInterface.get() );
81 iter.startRasterRead( mBand, mNbCellsXProvider, mNbCellsYProvider, mExtent );
82
83 const int nbBlocksWidth = static_cast<int>( std::ceil( 1.0 * mNbCellsXProvider / maxWidth ) );
84 const int nbBlocksHeight = static_cast<int>( std::ceil( 1.0 * mNbCellsYProvider / maxHeight ) );
85 const int nbBlocks = nbBlocksWidth * nbBlocksHeight;
86
87 int iterLeft = 0;
88 int iterTop = 0;
89 int iterCols = 0;
90 int iterRows = 0;
91 std::unique_ptr<QgsRasterBlock> rasterBlock;
92 QgsRectangle blockExtent;
93 bool isNoData = false;
94 while ( iter.readNextRasterPart( mBand, iterCols, iterRows, rasterBlock, iterLeft, iterTop, &blockExtent ) )
95 {
96 if ( feedback )
97 feedback->setProgress( 100 * ( ( iterTop / maxHeight * nbBlocksWidth ) + iterLeft / maxWidth ) / nbBlocks );
98 if ( feedback && feedback->isCanceled() )
99 break;
100
101 double currentY = blockExtent.yMaximum() - 0.5 * mRasterUnitsPerPixelY;
102
103 for ( int row = 0; row < iterRows; row++ )
104 {
105 if ( feedback && feedback->isCanceled() )
106 break;
107
108 double currentX = blockExtent.xMinimum() + 0.5 * mRasterUnitsPerPixelX;
109
110 for ( int column = 0; column < iterCols; column++ )
111 {
112 const double value = rasterBlock->valueAndNoData( row, column, isNoData );
113 if ( !isNoData )
114 {
115 const QgsGeometry pixelRectGeometry = createGeometryForPixel( currentX, currentY, mRasterUnitsPerPixelX, mRasterUnitsPerPixelY );
116
117 QgsFeature f;
118 f.setGeometry( pixelRectGeometry );
119 f.setAttributes( QgsAttributes() << value );
120 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
121 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
122 }
123 currentX += mRasterUnitsPerPixelX;
124 }
125 currentY -= mRasterUnitsPerPixelY;
126 }
127 }
128
129 sink->finalize();
130
131 QVariantMap outputs;
132 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
133 return outputs;
134}
135
136//
137// QgsRasterPixelsToPolygonsAlgorithm
138//
139
140QString QgsRasterPixelsToPolygonsAlgorithm::name() const
141{
142 return QStringLiteral( "pixelstopolygons" );
143}
144
145QString QgsRasterPixelsToPolygonsAlgorithm::displayName() const
146{
147 return QObject::tr( "Raster pixels to polygons" );
148}
149
150QStringList QgsRasterPixelsToPolygonsAlgorithm::tags() const
151{
152 return QObject::tr( "vectorize,polygonize,raster,convert,pixels" ).split( ',' );
153}
154
155QString QgsRasterPixelsToPolygonsAlgorithm::shortHelpString() const
156{
157 return QObject::tr( "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
162QString QgsRasterPixelsToPolygonsAlgorithm::shortDescription() const
163{
164 return QObject::tr( "Creates a vector layer of polygons corresponding to each pixel in a raster layer." );
165}
166
167QgsRasterPixelsToPolygonsAlgorithm *QgsRasterPixelsToPolygonsAlgorithm::createInstance() const
168{
169 return new QgsRasterPixelsToPolygonsAlgorithm();
170}
171
172QString QgsRasterPixelsToPolygonsAlgorithm::outputName() const
173{
174 return QObject::tr( "Vector polygons" );
175}
176
177Qgis::ProcessingSourceType QgsRasterPixelsToPolygonsAlgorithm::outputType() const
178{
180}
181
182Qgis::WkbType QgsRasterPixelsToPolygonsAlgorithm::sinkType() const
183{
185}
186
187QgsGeometry QgsRasterPixelsToPolygonsAlgorithm::createGeometryForPixel( double centerX, double centerY, double pixelWidthX, double pixelWidthY ) const
188{
189 const double hCellSizeX = pixelWidthX / 2.0;
190 const double hCellSizeY = pixelWidthY / 2.0;
191 return QgsGeometry::fromRect( QgsRectangle( centerX - hCellSizeX, centerY - hCellSizeY, centerX + hCellSizeX, centerY + hCellSizeY ) );
192}
193
194
195//
196// QgsRasterPixelsToPointsAlgorithm
197//
198
199QString QgsRasterPixelsToPointsAlgorithm::name() const
200{
201 return QStringLiteral( "pixelstopoints" );
202}
203
204QString QgsRasterPixelsToPointsAlgorithm::displayName() const
205{
206 return QObject::tr( "Raster pixels to points" );
207}
208
209QStringList QgsRasterPixelsToPointsAlgorithm::tags() const
210{
211 return QObject::tr( "vectorize,polygonize,raster,convert,pixels,centers" ).split( ',' );
212}
213
214QString QgsRasterPixelsToPointsAlgorithm::shortHelpString() const
215{
216 return QObject::tr( "This algorithm converts a raster layer to a vector layer, by creating point features "
217 "for each individual pixel's center in the raster layer.\n\n"
218 "Any NoData pixels are skipped in the output." );
219}
220
221QString QgsRasterPixelsToPointsAlgorithm::shortDescription() const
222{
223 return QObject::tr( "Creates a vector layer of points corresponding to each pixel in a raster layer." );
224}
225
226QgsRasterPixelsToPointsAlgorithm *QgsRasterPixelsToPointsAlgorithm::createInstance() const
227{
228 return new QgsRasterPixelsToPointsAlgorithm();
229}
230
231QString QgsRasterPixelsToPointsAlgorithm::outputName() const
232{
233 return QObject::tr( "Vector points" );
234}
235
236Qgis::ProcessingSourceType QgsRasterPixelsToPointsAlgorithm::outputType() const
237{
239}
240
241Qgis::WkbType QgsRasterPixelsToPointsAlgorithm::sinkType() const
242{
244}
245
246QgsGeometry QgsRasterPixelsToPointsAlgorithm::createGeometryForPixel( double centerX, double centerY, double, double ) const
247{
248 return QgsGeometry( new QgsPoint( centerX, centerY ) );
249}
250
ProcessingSourceType
Processing data source types.
Definition qgis.h:3531
@ VectorPoint
Vector point layers.
Definition qgis.h:3534
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3536
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:277
@ Point
Point.
Definition qgis.h:279
@ Polygon
Polygon.
Definition qgis.h:281
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:58
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: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
A geometry is the spatial representation of a feature.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
virtual QgsRectangle extent() const
Returns the extent of the layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:87
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
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.
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.
static const int DEFAULT_MAXIMUM_TILE_WIDTH
Default maximum tile width.
static const int DEFAULT_MAXIMUM_TILE_HEIGHT
Default maximum tile height.
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