Docker-in-Docker (DinD) capabilities of public runners deactivated. More info

Commit 36e5b0b4 authored by PIERSON Julie's avatar PIERSON Julie
Browse files

rename merge_rename_bands to rename_bands, merge_rename is now a copy of...

rename merge_rename_bands to rename_bands, merge_rename is now a copy of rename_bands (and previous rename_bands is renamed old)
parent a4cd5a7b
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
""" """
/*************************************************************************** /***************************************************************************
MergeAndRename MergeAndRenameBands
A QGIS plugin A QGIS plugin
Merge and rename raster bands Merge and Rename raster bands
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/ Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
------------------- -------------------
begin : 2021-09-09 begin : 2021-09-09
......
...@@ -31,13 +31,41 @@ __copyright__ = '(C) 2021 by J. Pierson, UMR 6554 LETG, CNRS' ...@@ -31,13 +31,41 @@ __copyright__ = '(C) 2021 by J. Pierson, UMR 6554 LETG, CNRS'
__revision__ = '$Format:%H$' __revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QCoreApplication from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing, from qgis.core import (QgsProcessingAlgorithm,
QgsProcessingAlgorithm, QgsProcessingParameterDefinition,
QgsProcessingParameterRasterLayer,
QgsProcessingParameterMatrix,
QgsProcessingParameterRasterDestination) QgsProcessingParameterRasterDestination)
from osgeo import gdal from osgeo import gdal
# custom band table widget
class ParameterBandTable(QgsProcessingParameterDefinition):
def __init__(self, name='', description='', parent=None, optional=False):
super().__init__(name, description, None, optional)
self.parent = parent
self.setMetadata({'widget_wrapper': 'BandTableWidget.BandTableWidgetWrapper'})
def type(self):
return 'Input parameters'
def clone(self):
return ParameterBandTable(self.name(), self.description(), self.parent, self.flags())
# getting output values as a list, 1st element for layer name, 2nd for layer path,
# then one element for each row :
# ['mylayer', '/path/to/mylayer.tif', 'band 1, old name 1, new name 1', 'band 2, old name 2, new name 2']
# (see BandTableWidget.py to change this)
@staticmethod
def tableValuesAsList(value):
if value is None:
return None
if value == '':
return None
else:
return value.split(';')
class RenameBandsAlgorithm(QgsProcessingAlgorithm): class RenameBandsAlgorithm(QgsProcessingAlgorithm):
""" """
...@@ -50,7 +78,6 @@ class RenameBandsAlgorithm(QgsProcessingAlgorithm): ...@@ -50,7 +78,6 @@ class RenameBandsAlgorithm(QgsProcessingAlgorithm):
# calling from the QGIS console. # calling from the QGIS console.
INPUT = 'INPUT' INPUT = 'INPUT'
TABLE = 'TABLE'
OUTPUT = 'OUTPUT' OUTPUT = 'OUTPUT'
def initAlgorithm(self, config): def initAlgorithm(self, config):
...@@ -58,25 +85,13 @@ class RenameBandsAlgorithm(QgsProcessingAlgorithm): ...@@ -58,25 +85,13 @@ class RenameBandsAlgorithm(QgsProcessingAlgorithm):
Here we define the inputs and output of the algorithm, along Here we define the inputs and output of the algorithm, along
with some other properties. with some other properties.
""" """
# input raster layer
self.addParameter(
QgsProcessingParameterRasterLayer(
self.INPUT,
self.tr('Input raster layer'),
[QgsProcessing.TypeVectorAnyGeometry]
)
)
# table to reaorder and rename bands # custom parameter : band table widget
self.addParameter( self.addParameter(
QgsProcessingParameterMatrix( ParameterBandTable(
self.TABLE, self.INPUT,
self.tr('Band names and order'), self.tr('Input parameters'),
numberRows=0, False # True if optional
hasFixedNumberRows = False,
headers=['future name', 'order'],
defaultValue=[None,None]
) )
) )
...@@ -89,72 +104,58 @@ class RenameBandsAlgorithm(QgsProcessingAlgorithm): ...@@ -89,72 +104,58 @@ class RenameBandsAlgorithm(QgsProcessingAlgorithm):
) )
def processAlgorithm(self, parameters, context, feedback): def processAlgorithm(self, parameters, context, feedback):
""" """
Here is where the processing itself takes place. Here is where the processing itself takes place.
""" """
# RETRIEVE INPUTS AND OUTPUT # RETRIEVE INPUTS AND OUTPUT
input_raster = self.parameterAsRasterLayer(parameters, self.INPUT, context) input_param = ParameterBandTable.tableValuesAsList(parameters[self.INPUT])
band_table = self.parameterAsMatrix(parameters, self.TABLE, context)
output_raster_path = self.parameterAsOutputLayer(parameters, self.OUTPUT, context) output_raster_path = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
# GETTING USEFUL PAREMETERS # GETTING USEFUL PARAMETERS
input_raster_path = input_param[1]
band_data = input_param[2:]
# number of columns in table is used later on, change it here if necessary # number of rows in table
nb_col = 2 nb_row = len(band_data)
# index of column used for band order # index of column used for band order
index_bandorder = 1 index_bandorder = 0
# index of column used for band description # index of column used for old band name
index_banddesc = 0 index_oldname = 1
# index of column used for new band name
index_newname = 2
# transform band_table in a nested list, with 1 element per band, and name and order of each band # transform band_table in a nested list, with 1 element per band, and name and order of each band
# [['band 1', 1], ['band 2', 2], ['band 3', 3]] # [['band 1', 1], ['band 2', 2], ['band 3', 3]]
band_table = [band_table[n:n+nb_col] for n in range(0, len(band_table), nb_col)] band_table = [i.split(',') for i in band_data]
# get input raster path
input_raster_path = input_raster.source()
# read raster with gdal
input_raster = gdal.Open(input_raster_path)
# REORDERING BANDS # REORDERING BANDS
# get order of bands as a list, i.e. [3,2,1] # get order of bands as a list, i.e. [3,2,1]
band_order = [i[index_bandorder] for i in band_table] band_order = [i[index_bandorder] for i in band_table]
# reordering bands using gdal_translate # reordering bands using gdal_translate
kwargs = { kwargs = {'bandList': band_order}
'bandList': band_order
}
output_raster = gdal.Translate(output_raster_path, input_raster_path, **kwargs) output_raster = gdal.Translate(output_raster_path, input_raster_path, **kwargs)
# RENAMING BANDS # RENAMING BANDS
# get number of bands of input raster
nbands = input_raster.RasterCount
# get number of rows in table
nrows = len(band_table)
# check if band number = row count in band_table
if nbands != nrows:
message = 'Number of rows in table is different from number of bands in input raster'
feedback.reportError(QCoreApplication.translate('Rename bands', message))
return{}
# reorder band table so that bands are in same order as in output raster
sorted_band_table = sorted(band_table, key = lambda x: x[index_bandorder])
# iterate over each band to set its description using table input # iterate over each band to set its description using table input
for band_number in range(nbands): for band_number in range(nb_row):
band = output_raster.GetRasterBand(band_number + 1) band = output_raster.GetRasterBand(band_number + 1)
band.SetDescription(sorted_band_table[band_number][index_banddesc]) new_name = band_table[band_number][index_newname]
# if no new name was set, use old name
if new_name == '':
new_name = band_table[band_number][index_oldname]
band.SetDescription(new_name)
# RETURNING RESULTS # RETURNING RESULTS
# Return the results of the algorithm as a dictionary # Return the results of the algorithm as a dictionary
return {self.OUTPUT: output_raster_path} return {self.OUTPUT: output_raster_path}
def name(self): def name(self):
""" """
Returns the algorithm name, used for identifying the algorithm. This Returns the algorithm name, used for identifying the algorithm. This
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment