QGIS API Documentation 3.43.0-Master (c4a2e9c6d2f)
qgsalgorithmfillnodata.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmfillnodata.cpp
3 ---------------------
4 begin : January 2020
5 copyright : (C) 2020 by Clemens Raffler
6 email : clemens dot raffler 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 "qgsrasterfilewriter.h"
20
22
23QString QgsFillNoDataAlgorithm::name() const
24{
25 return QStringLiteral( "fillnodata" );
26}
27
28QString QgsFillNoDataAlgorithm::displayName() const
29{
30 return QObject::tr( "Fill NoData cells" );
31}
32
33QStringList QgsFillNoDataAlgorithm::tags() const
34{
35 return QObject::tr( "data,cells,fill,set" ).split( ',' );
36}
37
38QString QgsFillNoDataAlgorithm::group() const
39{
40 return QObject::tr( "Raster tools" );
41}
42
43QString QgsFillNoDataAlgorithm::groupId() const
44{
45 return QStringLiteral( "rastertools" );
46}
47
48void QgsFillNoDataAlgorithm::initAlgorithm( const QVariantMap & )
49{
50 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT" ), QStringLiteral( "Raster input" ) ) );
51 addParameter( new QgsProcessingParameterBand( QStringLiteral( "BAND" ), QObject::tr( "Band Number" ), 1, QStringLiteral( "INPUT" ) ) );
52 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "FILL_VALUE" ), QObject::tr( "Fill value" ), Qgis::ProcessingNumberParameterType::Double, 1, false ) );
53
54 // backwards compatibility parameter
55 // TODO QGIS 4: remove parameter and related logic
56 auto createOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATE_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
57 createOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
58 createOptsParam->setFlags( createOptsParam->flags() | Qgis::ProcessingParameterFlag::Hidden );
59 addParameter( createOptsParam.release() );
60
61 auto creationOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATION_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
62 creationOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
63 creationOptsParam->setFlags( creationOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
64 addParameter( creationOptsParam.release() );
65
66 addParameter( new QgsProcessingParameterRasterDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Output raster" ) ) );
67}
68
69QString QgsFillNoDataAlgorithm::shortHelpString() const
70{
71 return QObject::tr( "This algorithm resets the NoData values in the input raster "
72 "to a chosen value, resulting in a raster dataset with no NoData pixels. "
73 "This value can be set by the user using the Fill value parameter. "
74 "The algorithm respects the input raster data type (eg. a floating point fill value will be truncated "
75 "when applied to an integer raster)." );
76}
77
78QgsFillNoDataAlgorithm *QgsFillNoDataAlgorithm::createInstance() const
79{
80 return new QgsFillNoDataAlgorithm();
81}
82
83bool QgsFillNoDataAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
84{
85 Q_UNUSED( feedback );
86 mInputRaster = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT" ), context );
87 mFillValue = parameterAsDouble( parameters, QStringLiteral( "FILL_VALUE" ), context );
88
89 if ( !mInputRaster )
90 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT" ) ) );
91
92 mBand = parameterAsInt( parameters, QStringLiteral( "BAND" ), context );
93 if ( mBand < 1 || mBand > mInputRaster->bandCount() )
94 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).arg( mInputRaster->bandCount() ) );
95
96 mInterface.reset( mInputRaster->dataProvider()->clone() );
97 mInputNoDataValue = mInputRaster->dataProvider()->sourceNoDataValue( mBand );
98 mExtent = mInputRaster->extent();
99 mLayerWidth = mInputRaster->width();
100 mLayerHeight = mInputRaster->height();
101 mCrs = mInputRaster->crs();
102 mNbCellsXProvider = mInterface->xSize();
103 mNbCellsYProvider = mInterface->ySize();
104 return true;
105}
106
107QVariantMap QgsFillNoDataAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
108{
109 //test if input dataset has NoData
110 if ( !mInputRaster->dataProvider()->sourceHasNoDataValue( mBand ) )
111 feedback->reportError( QObject::tr( "Input raster has no NoData values. There exist no NoData cells to fill." ), false );
112
113 //prepare output dataset
114 QString creationOptions = parameterAsString( parameters, QStringLiteral( "CREATION_OPTIONS" ), context ).trimmed();
115 // handle backwards compatibility parameter CREATE_OPTIONS
116 const QString optionsString = parameterAsString( parameters, QStringLiteral( "CREATE_OPTIONS" ), context );
117 if ( !optionsString.isEmpty() )
118 creationOptions = optionsString;
119
120 const QString outputFile = parameterAsOutputLayer( parameters, QStringLiteral( "OUTPUT" ), context );
121 const QFileInfo fi( outputFile );
122 const QString outputFormat = QgsRasterFileWriter::driverForExtension( fi.suffix() );
123 auto writer = std::make_unique<QgsRasterFileWriter>( outputFile );
124 writer->setOutputProviderKey( QStringLiteral( "gdal" ) );
125 if ( !creationOptions.isEmpty() )
126 {
127 writer->setCreationOptions( creationOptions.split( '|' ) );
128 }
129 writer->setOutputFormat( outputFormat );
130 std::unique_ptr<QgsRasterDataProvider> provider( writer->createOneBandRaster( mInterface->dataType( mBand ), mNbCellsXProvider, mNbCellsYProvider, mExtent, mCrs ) );
131 if ( !provider )
132 throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
133 if ( !provider->isValid() )
134 throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
135
136 //prepare output provider
137 QgsRasterDataProvider *destinationRasterProvider;
138 destinationRasterProvider = provider.get();
139 destinationRasterProvider->setEditable( true );
140
143 const int nbBlocksWidth = static_cast<int>( std::ceil( 1.0 * mLayerWidth / maxWidth ) );
144 const int nbBlocksHeight = static_cast<int>( std::ceil( 1.0 * mLayerHeight / maxHeight ) );
145 const int nbBlocks = nbBlocksWidth * nbBlocksHeight;
146
147 QgsRasterIterator iter( mInterface.get() );
148 iter.startRasterRead( mBand, mLayerWidth, mLayerHeight, mExtent );
149 int iterLeft = 0;
150 int iterTop = 0;
151 int iterCols = 0;
152 int iterRows = 0;
153 std::unique_ptr<QgsRasterBlock> filledRasterBlock;
154 while ( iter.readNextRasterPart( mBand, iterCols, iterRows, filledRasterBlock, iterLeft, iterTop ) )
155 {
156 if ( feedback )
157 feedback->setProgress( 100 * ( ( iterTop / maxHeight * nbBlocksWidth ) + iterLeft / maxWidth ) / nbBlocks );
158
159 if ( feedback && feedback->isCanceled() )
160 break;
161
162 if ( !filledRasterBlock->hasNoDataValue() )
163 {
164 if ( !destinationRasterProvider->writeBlock( filledRasterBlock.get(), mBand, iterLeft, iterTop ) )
165 {
166 throw QgsProcessingException( QObject::tr( "Could not write raster block: %1" ).arg( destinationRasterProvider->error().summary() ) );
167 }
168 continue;
169 }
170
171 for ( int row = 0; row < iterRows; row++ )
172 {
173 if ( feedback && feedback->isCanceled() )
174 break;
175 for ( int column = 0; column < iterCols; column++ )
176 {
177 if ( filledRasterBlock->isNoData( row, column ) )
178 filledRasterBlock->setValue( row, column, mFillValue );
179 }
180 }
181 if ( !destinationRasterProvider->writeBlock( filledRasterBlock.get(), mBand, iterLeft, iterTop ) )
182 {
183 throw QgsProcessingException( QObject::tr( "Could not write raster block: %1" ).arg( destinationRasterProvider->error().summary() ) );
184 }
185 }
186 destinationRasterProvider->setEditable( false );
187
188 QVariantMap outputs;
189 outputs.insert( QStringLiteral( "OUTPUT" ), outputFile );
190 return outputs;
191}
192
@ Hidden
Parameter is hidden and should not be shown to users.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
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:129
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
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 reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
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.
Base class for raster data providers.
bool writeBlock(QgsRasterBlock *block, int band, int xOffset=0, int yOffset=0)
Writes pixel data from a raster block into the provider data source.
virtual bool setEditable(bool enabled)
Turns on/off editing mode of the provider.
static QString driverForExtension(const QString &extension)
Returns the GDAL driver name for a specified file extension.
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.