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