QGIS API Documentation 3.99.0-Master (752b475928d)
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
26
27QString QgsRescaleRasterAlgorithm::name() const
28{
29 return QStringLiteral( "rescaleraster" );
30}
31
32QString QgsRescaleRasterAlgorithm::displayName() const
33{
34 return QObject::tr( "Rescale raster" );
35}
36
37QStringList QgsRescaleRasterAlgorithm::tags() const
38{
39 return QObject::tr( "raster,rescale,minimum,maximum,range" ).split( ',' );
40}
41
42QString QgsRescaleRasterAlgorithm::group() const
43{
44 return QObject::tr( "Raster analysis" );
45}
46
47QString QgsRescaleRasterAlgorithm::groupId() const
48{
49 return QStringLiteral( "rasteranalysis" );
50}
51
52QString QgsRescaleRasterAlgorithm::shortHelpString() const
53{
54 return QObject::tr( "This algorithm rescales a raster layer to a new value range, while preserving the shape "
55 "(distribution) of the raster's histogram (pixel values). Input values "
56 "are mapped using a linear interpolation from the source raster's minimum "
57 "and maximum pixel values to the destination minimum and maximum pixel range.\n\n"
58 "By default the algorithm preserves the original NoData value, but there is "
59 "an option to override it." );
60}
61
62QString QgsRescaleRasterAlgorithm::shortDescription() const
63{
64 return QObject::tr( "Rescales a raster layer to a new value range, while preserving the shape "
65 "(distribution) of the raster's histogram (pixel values)." );
66}
67
68QgsRescaleRasterAlgorithm *QgsRescaleRasterAlgorithm::createInstance() const
69{
70 return new QgsRescaleRasterAlgorithm();
71}
72
73void QgsRescaleRasterAlgorithm::initAlgorithm( const QVariantMap & )
74{
75 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT" ), QStringLiteral( "Input raster" ) ) );
76 addParameter( new QgsProcessingParameterBand( QStringLiteral( "BAND" ), QObject::tr( "Band number" ), 1, QStringLiteral( "INPUT" ) ) );
77 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "MINIMUM" ), QObject::tr( "New minimum value" ), Qgis::ProcessingNumberParameterType::Double, 0 ) );
78 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "MAXIMUM" ), QObject::tr( "New maximum value" ), Qgis::ProcessingNumberParameterType::Double, 255 ) );
79 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "NODATA" ), QObject::tr( "New NoData value" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true ) );
80
81 // backwards compatibility parameter
82 // TODO QGIS 4: remove parameter and related logic
83 auto createOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATE_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
84 createOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
85 createOptsParam->setFlags( createOptsParam->flags() | Qgis::ProcessingParameterFlag::Hidden );
86 addParameter( createOptsParam.release() );
87
88 auto creationOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATION_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
89 creationOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
90 creationOptsParam->setFlags( creationOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
91 addParameter( creationOptsParam.release() );
92
93 addParameter( new QgsProcessingParameterRasterDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Rescaled" ) ) );
94}
95
96bool QgsRescaleRasterAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
97{
98 Q_UNUSED( feedback );
99
100 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT" ), context );
101 if ( !layer )
102 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT" ) ) );
103
104 mBand = parameterAsInt( parameters, QStringLiteral( "BAND" ), context );
105 if ( mBand < 1 || mBand > layer->bandCount() )
106 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" )
107 .arg( mBand )
108 .arg( layer->bandCount() ) );
109
110 mMinimum = parameterAsDouble( parameters, QStringLiteral( "MINIMUM" ), context );
111 mMaximum = parameterAsDouble( parameters, QStringLiteral( "MAXIMUM" ), context );
112
113 mInterface.reset( layer->dataProvider()->clone() );
114
115 mCrs = layer->crs();
116 mLayerWidth = layer->width();
117 mLayerHeight = layer->height();
118 mExtent = layer->extent();
119 if ( parameters.value( QStringLiteral( "NODATA" ) ).isValid() )
120 {
121 mNoData = parameterAsDouble( parameters, QStringLiteral( "NODATA" ), context );
122 }
123 else
124 {
125 mNoData = layer->dataProvider()->sourceNoDataValue( mBand );
126 }
127
128 if ( std::isfinite( mNoData ) )
129 {
130 // Clamp nodata to float32 range, since that's the type of the raster
131 if ( mNoData < std::numeric_limits<float>::lowest() )
132 mNoData = std::numeric_limits<float>::lowest();
133 else if ( mNoData > std::numeric_limits<float>::max() )
134 mNoData = std::numeric_limits<float>::max();
135 }
136
137 mXSize = mInterface->xSize();
138 mYSize = mInterface->ySize();
139
140 return true;
141}
142
143QVariantMap QgsRescaleRasterAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
144{
145 feedback->pushInfo( QObject::tr( "Calculating raster minimum and maximum values…" ) );
146 const QgsRasterBandStats stats = mInterface->bandStatistics( mBand, Qgis::RasterBandStatistic::Min | Qgis::RasterBandStatistic::Max, QgsRectangle(), 0 );
147
148 feedback->pushInfo( QObject::tr( "Rescaling values…" ) );
149
150 QString creationOptions = parameterAsString( parameters, QStringLiteral( "CREATION_OPTIONS" ), context ).trimmed();
151 // handle backwards compatibility parameter CREATE_OPTIONS
152 const QString optionsString = parameterAsString( parameters, QStringLiteral( "CREATE_OPTIONS" ), context );
153 if ( !optionsString.isEmpty() )
154 creationOptions = optionsString;
155
156 const QString outputFile = parameterAsOutputLayer( parameters, QStringLiteral( "OUTPUT" ), context );
157 const QString outputFormat = parameterAsOutputRasterFormat( parameters, QStringLiteral( "OUTPUT" ), context );
158 auto writer = std::make_unique<QgsRasterFileWriter>( outputFile );
159 writer->setOutputProviderKey( QStringLiteral( "gdal" ) );
160 if ( !creationOptions.isEmpty() )
161 {
162 writer->setCreationOptions( creationOptions.split( '|' ) );
163 }
164
165 writer->setOutputFormat( outputFormat );
166 std::unique_ptr<QgsRasterDataProvider> provider( writer->createOneBandRaster( Qgis::DataType::Float32, mXSize, mYSize, mExtent, mCrs ) );
167 if ( !provider )
168 throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
169 if ( !provider->isValid() )
170 throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
171
172 QgsRasterDataProvider *destProvider = provider.get();
173 destProvider->setEditable( true );
174 destProvider->setNoDataValue( 1, mNoData );
175
178 const int numBlocksX = static_cast<int>( std::ceil( 1.0 * mLayerWidth / blockWidth ) );
179 const int numBlocksY = static_cast<int>( std::ceil( 1.0 * mLayerHeight / blockHeight ) );
180 const int numBlocks = numBlocksX * numBlocksY;
181
182 QgsRasterIterator iter( mInterface.get() );
183 iter.startRasterRead( mBand, mLayerWidth, mLayerHeight, mExtent );
184 int iterLeft = 0;
185 int iterTop = 0;
186 int iterCols = 0;
187 int iterRows = 0;
188 std::unique_ptr<QgsRasterBlock> inputBlock;
189 while ( iter.readNextRasterPart( mBand, iterCols, iterRows, inputBlock, iterLeft, iterTop ) )
190 {
191 auto outputBlock = std::make_unique<QgsRasterBlock>( destProvider->dataType( 1 ), iterCols, iterRows );
192 feedback->setProgress( 100 * ( ( iterTop / blockHeight * numBlocksX ) + iterLeft / blockWidth ) / numBlocks );
193
194 for ( int row = 0; row < iterRows; row++ )
195 {
196 if ( feedback->isCanceled() )
197 break;
198
199 for ( int col = 0; col < iterCols; col++ )
200 {
201 bool isNoData = false;
202 const double val = inputBlock->valueAndNoData( row, col, isNoData );
203 if ( isNoData )
204 {
205 outputBlock->setValue( row, col, mNoData );
206 }
207 else
208 {
209 const double newValue = ( ( val - stats.minimumValue ) * ( mMaximum - mMinimum ) / ( stats.maximumValue - stats.minimumValue ) ) + mMinimum;
210 outputBlock->setValue( row, col, newValue );
211 }
212 }
213 }
214 if ( !destProvider->writeBlock( outputBlock.get(), mBand, iterLeft, iterTop ) )
215 {
216 throw QgsProcessingException( QObject::tr( "Could not write raster block: %1" ).arg( destProvider->error().summary() ) );
217 }
218 }
219 destProvider->setEditable( false );
220
221 QVariantMap outputs;
222 outputs.insert( QStringLiteral( "OUTPUT" ), outputFile );
223 return outputs;
224}
225
@ Float32
Thirty two bit floating point (float).
Definition qgis.h:380
@ Hidden
Parameter is hidden and should not be shown to users.
Definition qgis.h:3764
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
@ Double
Double/float values.
Definition qgis.h:3804
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:130
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
virtual QgsRectangle extent() const
Returns the extent of the layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:87
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.
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 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.