QGIS API Documentation 3.99.0-Master (09f76ad7019)
Loading...
Searching...
No Matches
qgsalgorithmrescaleraster.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmrescaleraster.cpp
3 ---------------------
4 begin : July 2020
5 copyright : (C) 2020 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 <limits>
21#include <math.h>
22
23#include "qgsrasterfilewriter.h"
24
25#include <QString>
26
27using namespace Qt::StringLiterals;
28
30
31QString QgsRescaleRasterAlgorithm::name() const
32{
33 return u"rescaleraster"_s;
34}
35
36QString QgsRescaleRasterAlgorithm::displayName() const
37{
38 return QObject::tr( "Rescale raster" );
39}
40
41QStringList QgsRescaleRasterAlgorithm::tags() const
42{
43 return QObject::tr( "raster,rescale,minimum,maximum,range" ).split( ',' );
44}
45
46QString QgsRescaleRasterAlgorithm::group() const
47{
48 return QObject::tr( "Raster analysis" );
49}
50
51QString QgsRescaleRasterAlgorithm::groupId() const
52{
53 return u"rasteranalysis"_s;
54}
55
56QString QgsRescaleRasterAlgorithm::shortHelpString() const
57{
58 return QObject::tr( "This algorithm rescales a raster layer to a new value range, while preserving the shape "
59 "(distribution) of the raster's histogram (pixel values). Input values "
60 "are mapped using a linear interpolation from the source raster's minimum "
61 "and maximum pixel values to the destination minimum and maximum pixel range.\n\n"
62 "By default the algorithm preserves the original NoData value, but there is "
63 "an option to override it." );
64}
65
66QString QgsRescaleRasterAlgorithm::shortDescription() const
67{
68 return QObject::tr( "Rescales a raster layer to a new value range, while preserving the shape "
69 "(distribution) of the raster's histogram (pixel values)." );
70}
71
72QgsRescaleRasterAlgorithm *QgsRescaleRasterAlgorithm::createInstance() const
73{
74 return new QgsRescaleRasterAlgorithm();
75}
76
77void QgsRescaleRasterAlgorithm::initAlgorithm( const QVariantMap & )
78{
79 addParameter( new QgsProcessingParameterRasterLayer( u"INPUT"_s, u"Input raster"_s ) );
80 addParameter( new QgsProcessingParameterBand( u"BAND"_s, QObject::tr( "Band number" ), 1, u"INPUT"_s ) );
81 addParameter( new QgsProcessingParameterNumber( u"MINIMUM"_s, QObject::tr( "New minimum value" ), Qgis::ProcessingNumberParameterType::Double, 0 ) );
82 addParameter( new QgsProcessingParameterNumber( u"MAXIMUM"_s, QObject::tr( "New maximum value" ), Qgis::ProcessingNumberParameterType::Double, 255 ) );
83 addParameter( new QgsProcessingParameterNumber( u"NODATA"_s, QObject::tr( "New NoData value" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true ) );
84
85 // backwards compatibility parameter
86 // TODO QGIS 5: remove parameter and related logic
87 auto createOptsParam = std::make_unique<QgsProcessingParameterString>( u"CREATE_OPTIONS"_s, QObject::tr( "Creation options" ), QVariant(), false, true );
88 createOptsParam->setMetadata( QVariantMap( { { u"widget_wrapper"_s, QVariantMap( { { u"widget_type"_s, u"rasteroptions"_s } } ) } } ) );
89 createOptsParam->setFlags( createOptsParam->flags() | Qgis::ProcessingParameterFlag::Hidden );
90 addParameter( createOptsParam.release() );
91
92 auto creationOptsParam = std::make_unique<QgsProcessingParameterString>( u"CREATION_OPTIONS"_s, QObject::tr( "Creation options" ), QVariant(), false, true );
93 creationOptsParam->setMetadata( QVariantMap( { { u"widget_wrapper"_s, QVariantMap( { { u"widget_type"_s, u"rasteroptions"_s } } ) } } ) );
94 creationOptsParam->setFlags( creationOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
95 addParameter( creationOptsParam.release() );
96
97 addParameter( new QgsProcessingParameterRasterDestination( u"OUTPUT"_s, QObject::tr( "Rescaled" ) ) );
98}
99
100bool QgsRescaleRasterAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
101{
102 Q_UNUSED( feedback );
103
104 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, u"INPUT"_s, context );
105 if ( !layer )
106 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT"_s ) );
107
108 mBand = parameterAsInt( parameters, u"BAND"_s, context );
109 if ( mBand < 1 || mBand > layer->bandCount() )
110 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" )
111 .arg( mBand )
112 .arg( layer->bandCount() ) );
113
114 mMinimum = parameterAsDouble( parameters, u"MINIMUM"_s, context );
115 mMaximum = parameterAsDouble( parameters, u"MAXIMUM"_s, context );
116
117 mInterface.reset( layer->dataProvider()->clone() );
118
119 mCrs = layer->crs();
120 mLayerWidth = layer->width();
121 mLayerHeight = layer->height();
122 mExtent = layer->extent();
123 if ( parameters.value( u"NODATA"_s ).isValid() )
124 {
125 mNoData = parameterAsDouble( parameters, u"NODATA"_s, context );
126 }
127 else
128 {
129 mNoData = layer->dataProvider()->sourceNoDataValue( mBand );
130 }
131
132 if ( std::isfinite( mNoData ) )
133 {
134 // Clamp nodata to float32 range, since that's the type of the raster
135 if ( mNoData < std::numeric_limits<float>::lowest() )
136 mNoData = std::numeric_limits<float>::lowest();
137 else if ( mNoData > std::numeric_limits<float>::max() )
138 mNoData = std::numeric_limits<float>::max();
139 }
140
141 mXSize = mInterface->xSize();
142 mYSize = mInterface->ySize();
143
144 return true;
145}
146
147QVariantMap QgsRescaleRasterAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
148{
149 feedback->pushInfo( QObject::tr( "Calculating raster minimum and maximum values…" ) );
150 const QgsRasterBandStats stats = mInterface->bandStatistics( mBand, Qgis::RasterBandStatistic::Min | Qgis::RasterBandStatistic::Max, QgsRectangle(), 0 );
151
152 feedback->pushInfo( QObject::tr( "Rescaling values…" ) );
153
154 QString creationOptions = parameterAsString( parameters, u"CREATION_OPTIONS"_s, context ).trimmed();
155 // handle backwards compatibility parameter CREATE_OPTIONS
156 const QString optionsString = parameterAsString( parameters, u"CREATE_OPTIONS"_s, context );
157 if ( !optionsString.isEmpty() )
158 creationOptions = optionsString;
159
160 const QString outputFile = parameterAsOutputLayer( parameters, u"OUTPUT"_s, context );
161 const QString outputFormat = parameterAsOutputRasterFormat( parameters, u"OUTPUT"_s, context );
162 auto writer = std::make_unique<QgsRasterFileWriter>( outputFile );
163 writer->setOutputProviderKey( u"gdal"_s );
164 if ( !creationOptions.isEmpty() )
165 {
166 writer->setCreationOptions( creationOptions.split( '|' ) );
167 }
168
169 writer->setOutputFormat( outputFormat );
170 std::unique_ptr<QgsRasterDataProvider> provider( writer->createOneBandRaster( Qgis::DataType::Float32, mXSize, mYSize, mExtent, mCrs ) );
171 if ( !provider )
172 throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
173 if ( !provider->isValid() )
174 throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
175
176 QgsRasterDataProvider *destProvider = provider.get();
177 destProvider->setEditable( true );
178 destProvider->setNoDataValue( 1, mNoData );
179
180 const bool hasReportsDuringClose = provider->hasReportsDuringClose();
181 const double maxProgressDuringBlockWriting = hasReportsDuringClose ? 50.0 : 100.0;
182
183 QgsRasterIterator iter( mInterface.get() );
184 iter.startRasterRead( mBand, mLayerWidth, mLayerHeight, mExtent );
185 int iterLeft = 0;
186 int iterTop = 0;
187 int iterCols = 0;
188 int iterRows = 0;
189 std::unique_ptr<QgsRasterBlock> inputBlock;
190 while ( iter.readNextRasterPart( mBand, iterCols, iterRows, inputBlock, iterLeft, iterTop ) )
191 {
192 auto outputBlock = std::make_unique<QgsRasterBlock>( destProvider->dataType( 1 ), iterCols, iterRows );
193 feedback->setProgress( maxProgressDuringBlockWriting * iter.progress( mBand ) );
194
195 for ( int row = 0; row < iterRows; row++ )
196 {
197 if ( feedback->isCanceled() )
198 break;
199
200 for ( int col = 0; col < iterCols; col++ )
201 {
202 bool isNoData = false;
203 const double val = inputBlock->valueAndNoData( row, col, isNoData );
204 if ( isNoData )
205 {
206 outputBlock->setValue( row, col, mNoData );
207 }
208 else
209 {
210 const double newValue = ( ( val - stats.minimumValue ) * ( mMaximum - mMinimum ) / ( stats.maximumValue - stats.minimumValue ) ) + mMinimum;
211 outputBlock->setValue( row, col, newValue );
212 }
213 }
214 }
215 if ( !destProvider->writeBlock( outputBlock.get(), mBand, iterLeft, iterTop ) )
216 {
217 throw QgsProcessingException( QObject::tr( "Could not write raster block: %1" ).arg( destProvider->error().summary() ) );
218 }
219 }
220 destProvider->setEditable( false );
221
222 if ( hasReportsDuringClose )
223 {
224 std::unique_ptr<QgsFeedback> scaledFeedback( QgsFeedback::createScaledFeedback( feedback, maxProgressDuringBlockWriting, 100.0 ) );
225 if ( !provider->closeWithProgress( scaledFeedback.get() ) )
226 {
227 if ( feedback->isCanceled() )
228 return {};
229 throw QgsProcessingException( QObject::tr( "Could not write raster dataset" ) );
230 }
231 }
232
233 QVariantMap outputs;
234 outputs.insert( u"OUTPUT"_s, outputFile );
235 return outputs;
236}
237
@ Float32
Thirty two bit floating point (float).
Definition qgis.h:387
@ Hidden
Parameter is hidden and should not be shown to users.
Definition qgis.h:3835
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3834
@ Double
Double/float values.
Definition qgis.h:3875
virtual QgsError error() const
Gets current status error.
QString summary() const
Short error description, usually the first error in chain, the real error.
Definition qgserror.cpp:133
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
static std::unique_ptr< QgsFeedback > createScaledFeedback(QgsFeedback *parentFeedback, double startPercentage, double endPercentage)
Returns a feedback object whose [0, 100] progression range will be mapped to parentFeedback [startPer...
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.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
A raster band parameter for Processing algorithms.
A numeric parameter for processing algorithms.
A raster layer destination parameter, for specifying the destination path for a raster layer created ...
A raster layer parameter for processing algorithms.
The RasterBandStats struct is a container for statistics about a single raster band.
double minimumValue
The minimum cell value in the raster band.
double maximumValue
The maximum cell value in the raster band.
Base class for raster data providers.
QgsRasterDataProvider * clone() const override=0
Clone itself, create deep copy.
virtual bool setNoDataValue(int bandNo, double noDataValue)
Set no data value on created dataset.
virtual double sourceNoDataValue(int bandNo) const
Value representing no data value.
bool writeBlock(QgsRasterBlock *block, int band, int xOffset=0, int yOffset=0)
Writes pixel data from a raster block into the provider data source.
Qgis::DataType dataType(int bandNo) const override=0
Returns data type for the band specified by number.
virtual bool setEditable(bool enabled)
Turns on/off editing mode of the provider.
Iterator for sequentially processing raster cells.
Represents a raster layer.
int height() const
Returns the height of the (unclipped) raster.
int bandCount() const
Returns the number of bands in this layer.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
int width() const
Returns the width of the (unclipped) raster.
A rectangle specified with double values.