def calculate_PCD(red,nir,pcdPath):


	# Obtain file information and create the layers

	redInfo=QFileInfo(red)
	nirInfo=QFileInfo(nir)
	redBaseName=redInfo.baseName()
	nirBaseName=nirInfo.baseName()
	folderPath = redInfo.absolutePath()
	redReflectancePath = folderPath + "/red_reflectance.tif" 
	nirReflectancePath = folderPath + "/nir_reflectance.tif"

	redLayer = QgsRasterLayer(red,redBaseName)

	if not redLayer.isValid():
		print "Error importing red band to calculate reflectances"

	nirLayer = QgsRasterLayer(nir,nirBaseName)
	
	if not nirLayer.isValid():
		print "Error importing NIR band to calculate reflectances"


	# The images are transformed into reflectances by dividing by 32768

	entries=[]

	redReflectance = QgsRasterCalculatorEntry()
	redReflectance.ref = "red_band@1"
	redReflectance.raster=redLayer
	redReflectance.bandNumber = 1
	entries.append(redReflectance)
	
	# Converts the DN raster into a reflectance raster
	calc=QgsRasterCalculator('float(' + redReflectance.ref + ')/32768', redReflectancePath,"GTiff",redLayer.extent(),redLayer.width(),redLayer.height(), entries)
	calc.processCalculation()


	nirReflectance = QgsRasterCalculatorEntry()
	nirReflectance.ref = "nir_band@1"
	nirReflectance.raster=nirLayer
	nirReflectance.bandNumber = 1
	entries.append(nirReflectance)
	
	# Converts the DN raster into a reflectance raster
	calc=QgsRasterCalculator('float(' + nirReflectance.ref + ')/32768', nirReflectancePath,"GTiff",nirLayer.extent(),nirLayer.width(),nirLayer.height(), entries)
	calc.processCalculation()

	# Calculate the PCD index

	calc=QgsRasterCalculator("float(" + nirReflectance.ref + ")/float(" + redReflectance.ref + ")", pcdPath,"GTiff",nirLayer.extent(),nirLayer.width(),nirLayer.height(), entries)
	calc.processCalculation()
	
	print "PCD calculated"
    def raster_subtract(self):
        # if the layer does not exist it has to be created
        rlayer1 = QgsMapLayerRegistry.instance().mapLayersByName( self.cb_input1.currentText() )[0]
        rlayer2 = QgsMapLayerRegistry.instance().mapLayersByName( self.cb_input2.currentText() )[0]
        fileName = self.lineEdit.text()
        
        entries = []
        # Define band1
        boh1 = QgsRasterCalculatorEntry()
        boh1.ref = 'boh@1'
        boh1.raster = rlayer1
        boh1.bandNumber = 1
        entries.append( boh1 )
        
        # Define band2
        boh2 = QgsRasterCalculatorEntry()
        boh2.ref = 'boh@2'
        boh2.raster = rlayer2
        boh2.bandNumber = 1
        entries.append( boh2 )
        
        # Process calculation with input extent and resolution
        calc = QgsRasterCalculator( 'boh@1 - boh@2', fileName, \
                                    'GTiff', rlayer1.extent(), \
                                    rlayer1.width(), rlayer1.height(), entries )
        calc.processCalculation()
        
        # Load the file into the map
        fileInfo = QFileInfo(fileName)
        baseName = fileInfo.baseName()

        root = QgsProject.instance().layerTreeRoot()
        node_group1 = root.insertGroup(0, "Group 1")
        node_subgroup1 = node_group1.addGroup("Sub-group 1")

        # Check out signals from nodes section
        # http://www.lutraconsulting.co.uk/blog/2014/07/25/qgis-layer-tree-api-part-2/

        # if the layer does not exist it has to be created
        if not QgsMapLayerRegistry.instance().mapLayersByName(baseName):
            rOutput = QgsRasterLayer(fileName, baseName)
            QgsMapLayerRegistry.instance().addMapLayer(rOutput, False)
            setRamp(rOutput, self.iface)
            node_layer1 = node_subgroup1.addLayer(rOutput)

        # if the layer already exists trigger a refresh
        else:
            rOutput = QgsMapLayerRegistry.instance().mapLayersByName(baseName)[0]
            rOutput.triggerRepaint()
Exemple #3
0
def split_bands(pathIn,pathOut):

# Recibe un path de entrada (raster multibanda) y devuelve las bandas por separado

	fileInfo=QFileInfo(pathIn)
	baseName=fileInfo.baseName()
	layer=QgsRasterLayer(pathIn, baseName)

	if not layer.isValid():
		print "Error importing Micasense Mosaic to split"

	print "Splitting bands from " + baseName

	numBands=layer.bandCount()
	i=1
	entries=[]
	output=[]
	while(i<=numBands):
		band = QgsRasterCalculatorEntry()
		band.ref = "band@"+str(i)
		band.raster=layer
		band.bandNumber=i
		entries.append(band)

		# Saves the current band as a separate file
		calc=QgsRasterCalculator(band.ref, pathOut+ "/" +baseName+"_band_"+str(i)+".tif","GTiff",layer.extent(),layer.width(),layer.height(), entries)
		calc.processCalculation()
		
		output.append(pathOut+"/"+baseName+"_band_"+str(i)+".tif")
		i=i+1
	return output
Exemple #4
0
    def processAlgorithm(self, parameters, context, feedback):
        expression = self.getParameterValue(self.EXPRESSION)
        layersValue = self.getParameterValue(self.LAYERS)
        layersDict = {}
        if layersValue:
            layers = [QgsProcessingUtils.mapLayerFromString(f, context) for f in layersValue.split(";")]
            layersDict = {os.path.basename(lyr.source().split(".")[0]): lyr for lyr in layers}

        for lyr in QgsProcessingUtils.compatibleRasterLayers(context.project()):
            name = lyr.name()
            if (name + "@") in expression:
                layersDict[name] = lyr

        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                entry = QgsRasterCalculatorEntry()
                entry.ref = '{:s}@{:d}'.format(name, n + 1)
                entry.raster = lyr
                entry.bandNumber = n + 1
                entries.append(entry)

        output = self.getOutputValue(self.OUTPUT)
        extentValue = self.getParameterValue(self.EXTENT)
        if not extentValue:
            extentValue = QgsProcessingUtils.combineLayerExtents(layersValue)

        if extentValue:
            extent = extentValue.split(',')
            bbox = QgsRectangle(float(extent[0]), float(extent[2]),
                                float(extent[1]), float(extent[3]))
        else:
            if layersDict:
                bbox = list(layersDict.values())[0].extent()
                for lyr in layersDict.values():
                    bbox.combineExtentWith(lyr.extent())
            else:
                raise GeoAlgorithmExecutionException(self.tr("No layers selected"))

        def _cellsize(layer):
            return (layer.extent().xMaximum() - layer.extent().xMinimum()) / layer.width()
        cellsize = self.getParameterValue(self.CELLSIZE) or min([_cellsize(lyr) for lyr in layersDict.values()])
        width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)
        calc = QgsRasterCalculator(expression,
                                   output,
                                   driverName,
                                   bbox,
                                   width,
                                   height,
                                   entries)

        res = calc.processCalculation()
        if res == QgsRasterCalculator.ParserError:
            raise GeoAlgorithmExecutionException(self.tr("Error parsing formula"))
Exemple #5
0
    def processAlgorithm(self, parameters, context, feedback):
        expression = self.parameterAsString(parameters, self.EXPRESSION, context)
        layers = self.parameterAsLayerList(parameters, self.LAYERS, context)
        layersDict = {}
        if layers:
            layersDict = {os.path.basename(lyr.source().split(".")[0]): lyr for lyr in layers}

        for lyr in QgsProcessingUtils.compatibleRasterLayers(context.project()):
            name = lyr.name()
            if (name + "@") in expression:
                layersDict[name] = lyr

        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                entry = QgsRasterCalculatorEntry()
                entry.ref = '{:s}@{:d}'.format(name, n + 1)
                entry.raster = lyr
                entry.bandNumber = n + 1
                entries.append(entry)

        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
        bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
        if bbox.isNull():
            bbox = QgsProcessingUtils.combineLayerExtents(layers)

        if bbox.isNull():
            if layersDict:
                bbox = list(layersDict.values())[0].extent()
                for lyr in layersDict.values():
                    bbox.combineExtentWith(lyr.extent())
            else:
                raise QgsProcessingException(self.tr("No layers selected"))

        def _cellsize(layer):
            return (layer.extent().xMaximum() - layer.extent().xMinimum()) / layer.width()
        cellsize = self.parameterAsDouble(parameters, self.CELLSIZE, context) or min([_cellsize(lyr) for lyr in layersDict.values()])
        width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)
        calc = QgsRasterCalculator(expression,
                                   output,
                                   driverName,
                                   bbox,
                                   width,
                                   height,
                                   entries)

        res = calc.processCalculation()
        if res == QgsRasterCalculator.ParserError:
            raise QgsProcessingException(self.tr("Error parsing formula"))

        return {self.OUTPUT: output}
Exemple #6
0
def reclassifyRaster(prjpath, inRasterName, bandnum, minValue, tupleUpValues,
                     outRasterName):
    """ Reclassify a raster to groups defined by tupleUpValues."""

    # Get raster
    inRaster=getRasterLayerByName(inRasterName)
    if not inRaster:
        message=inRasterName+ "  not loaded or not a raster!"
        QMessageBox.critical(None,'Error',message, QMessageBox.Ok)
        return False

    # Check prjpath exists
    if not os.path.isdir(prjpath):
        message= prjpath + " does not exist!"
        QMessageBox.critical(None,'Error',message, QMessageBox.Ok)
        return False

    # Define band
    boh = QgsRasterCalculatorEntry()
    bandName=inRasterName+'@'+str(bandnum)
    boh.ref = bandName
    boh.raster = inRaster
    boh.bandNumber =bandnum

    # Prepare entries
    entries = []
    entries.append( boh )

    # Prepare calculation command
    bandNameAddStr= '<='+ bandName + ' AND ' + bandName + '<'
    i = 1
    lowerVal=0
    calcCommand=""
    for upValue in tupleUpValues:
        calcCommand = calcCommand + '( ' + str(minValue) + bandNameAddStr
        calcCommand = calcCommand + str(upValue) + ')' + '*' + str(i)
        if i!=len(tupleUpValues):
            calcCommand = calcCommand + ' + '
            minValue = upValue
            i = i + 1

    # Process calculation with input extent and resolution
    pathFilename=os.path.join( prjpath, outRasterName) + '.tif'
    calc = QgsRasterCalculator(calcCommand, pathFilename, 'GTiff',
                               inRaster.extent(), inRaster.width(),
                               inRaster.height(), entries )
    if not calc: return False
    ok= (calc.processCalculation() == 0)

    return ok
def adjustRasterToBaseRaster (baseRaster, adjustingRaster, outputPath):
    entries = []
    rCalcObj = QgsRasterCalculatorEntry()
    rCalcObj.ref = 'rCalcObj@1'
    rCalcObj.raster = adjustingRaster
    rCalcObj.bandNumber = 1
    entries.append(rCalcObj)
    #print '---'
    #print baseRaster.extent()
    #print baseRaster.width()
    #print baseRaster.height()
    #print '---'
    calc = QgsRasterCalculator('rCalcObj@1', outputPath, 'GTiff',
                               baseRaster.extent(),
                               baseRaster.width(), baseRaster.height(), entries)
    #print 'calc'
    calc.processCalculation()
Exemple #8
0
 def StringToRaster(raster,banda):
     fileInfo = QFileInfo(raster)
     path = fileInfo.filePath()
     baseName = fileInfo.baseName()
     global layerglobal
     layerglobal = QgsRasterLayer(path, baseName)
     QgsMapLayerRegistry.instance().addMapLayer(layerglobal)
     if layerglobal.isValid() is True:
         bandaref=str(banda)+'@1'
         # Define band1
         banda = QgsRasterCalculatorEntry()
         banda.ref = bandaref
         banda.raster = layerglobal
         banda.bandNumber = 1
         entries.append( banda )
     else:
         print "Unable to read basename and file path - Your string is probably invalid" +str(baseName)
def generateOneValueRasterQGisCalc (baseRaster, value, outputPath):
    """
    Generates raster with extent and resolution of baseRaster, each pixel is value.
    QgsRasterCalculator used
    :param baseRaster:
    :param value: output value
    :param outputPath: path for output file
    """
    entries = []
    rCalcObj = QgsRasterCalculatorEntry()
    rCalcObj.ref = 'rCalcObj@1'
    rCalcObj.raster = baseRaster
    rCalcObj.bandNumber = 1
    entries.append(rCalcObj)
    calc = QgsRasterCalculator(str(value), outputPath, 'GTiff',
                               baseRaster.extent(),
                               baseRaster.width(), baseRaster.height(), entries)
    calc.processCalculation()
Exemple #10
0
    def run(self):
        """Run method that performs all the real work"""

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:

            # CARREGAR VALORES DOS PARAMETROS:
            #PARAMETRO 1
            ListaVarIndep = []
            ListaLayerName = []
            NrLinhasTabela = self.dlg.tableWidget.rowCount()
            for Linhas in range(NrLinhasTabela):
                VarIndepPath = self.dlg.tableWidget.item(Linhas, 0).text()
                VarIndepLayerName = self.dlg.tableWidget.item(Linhas, 1).text()
                ListaVarIndep.append(VarIndepPath)
                ListaLayerName.append(VarIndepLayerName)

        #PARAMETRO 2
            VarDep = self.dlg.lineEdit_2.text()
            VarDepDisplayName = self.dlg.lineEdit_4.text()

            #PARAMETRO 3
            InputOutputFolder = self.dlg.lineEdit_3.text()

            #PARAMETRO 4
            RasterValidacao = self.dlg.lineEdit_5.text()
            ValidacaoDisplayName = self.dlg.lineEdit_6.text()

            # INICIO DOS PROCESSOS:
            # CRIAR PASTA OUTPUT
            PastaOutput = os.path.join(InputOutputFolder, "Output")
            if not os.path.exists(PastaOutput):
                os.makedirs(PastaOutput)
            else:
                for NrPastas in range(1, 10):
                    sufixo = "_" + str(NrPastas)
                    PastaOutput = os.path.join(InputOutputFolder,
                                               "Output" + sufixo)
                    if not os.path.exists(PastaOutput):
                        os.makedirs(PastaOutput)
                        break

        # CRIAR SUBPASTA TABELAS
            PastaTabelas = os.path.join(PastaOutput, "Tabelas")
            os.makedirs(PastaTabelas)

            # CARREGAR VARIAVEL DEPENDENTE E ADICIONAR LAYER AO QGIS
            LoadVarDep = QgsRasterLayer(VarDep, VarDepDisplayName)

            ListaVarIndepVI = []

            # PROPRIEDADES DOS FICHEIROS DE INPUT
            for VarIndep, VarIndepLayerName in zip(ListaVarIndep,
                                                   ListaLayerName):

                # CARREGAR VARIAVEL INDEPENDENTE E ADICIONAR LAYER AO QGIS
                LoadVarIndep = QgsRasterLayer(VarIndep, VarIndepLayerName)
                AddVarIndep = QgsMapLayerRegistry.instance().addMapLayer(
                    LoadVarIndep)

                # DEFINIR EXTENSAO
                ext = AddVarIndep.extent()
                xmin = ext.xMinimum()
                xmax = ext.xMaximum()
                ymin = ext.yMinimum()
                ymax = ext.yMaximum()
                Mask = "%f,%f,%f,%f" % (xmin, xmax, ymin, ymax)

                # DEFINIR CELL SIZE
                PixelSizeX = LoadVarIndep.rasterUnitsPerPixelX()
                PixelSizeY = LoadVarIndep.rasterUnitsPerPixelY()
                CellSize = PixelSizeX * PixelSizeY

                # CRIAR REPORT E CALCULAR VALORES UNICOS
                CountUniqueValues = os.path.join(
                    PastaTabelas, VarIndepLayerName + "_CountUniqueValues.txt")
                processing.runalg("grass7:r.report", VarIndep, 5, "*", 255,
                                  True, True, True, True, Mask, None,
                                  CountUniqueValues)

                ReportReadLines = open(CountUniqueValues).readlines()
                ReportSelectLines = ReportReadLines[4:-4]
                UniqueValues = len(ReportSelectLines)

                # DEFINIR CAMINHO DO OUTPUT E EXECUTAR R.COIN
                RCoinFile = os.path.join(
                    PastaTabelas, VarIndepLayerName + "_x_" +
                    VarDepDisplayName + "_Original.txt")
                processing.runalg("grass7:r.coin", VarIndep, VarDep, 0, False,
                                  Mask, None, RCoinFile)

                # LER RCOINFILE E SELECIONAR AS LINHAS COM INFORMACAO UTIL
                ReadLines = open(RCoinFile).readlines()
                SelectLines = ReadLines[22:UniqueValues + 22]

                # FORMATAR DADOS PARA IMPORTACAO EM CSV
                ListaValores = []
                for row in SelectLines:
                    RemoverEspacos = re.sub(' +', ' ', row)
                    SubstituirEspacos = RemoverEspacos.replace(' ', ';')
                    SepararPontoVirgula = SubstituirEspacos.split(";")
                    SelecionarColunas = itemgetter(1, 3, 5,
                                                   7)(SepararPontoVirgula)
                    JuntarColunas = ';'.join(SelecionarColunas)
                    ListaValores.append(JuntarColunas)

                if UniqueValues <= 2:
                    JuntarLinhas = ';'.join(ListaValores)
                    SepararValores = JuntarLinhas.split(";")
                    ConversaoInteiros = map(int, SepararValores)
                    Linha0 = "V;V0;V1;T\n"
                    Linha1 = str(ConversaoInteiros[0] + 1) + ";" + str(
                        ConversaoInteiros[1]) + ";" + str(
                            ConversaoInteiros[5]) + ";" + str(
                                ConversaoInteiros[1] +
                                ConversaoInteiros[5]) + "\n"
                    Linha2 = str(ConversaoInteiros[4] + 1) + ";" + str(
                        ConversaoInteiros[2]) + ";" + str(
                            ConversaoInteiros[6]) + ";" + str(
                                ConversaoInteiros[2] + ConversaoInteiros[6])
                    ValoresImportar = [Linha0, Linha1, Linha2]
                else:
                    ListaValores.insert(0, 'V;V0;V1;T')
                    ValoresImportar = '\n'.join(ListaValores)

            # ESCREVER DADOS FORMATADOS NUM NOVO FICHEIRO TXT
                RCoinTemp = os.path.join(
                    PastaTabelas, VarIndepLayerName + "_x_" +
                    VarDepDisplayName + "_Tratado.txt")
                open(RCoinTemp, 'wb').writelines(ValoresImportar)

                # IMPORTAR PARA FICHEIRO CSV
                TabulateAreaCSV = os.path.join(
                    PastaTabelas,
                    VarIndepLayerName + "_x_" + VarDepDisplayName + ".csv")
                csv.writer(open(TabulateAreaCSV, 'wb')).writerows(
                    csv.reader(open(RCoinTemp, 'rb')))

                # EXPORTAR PARA DBF
                LoadTabulateAreaCSV = QgsVectorLayer(
                    TabulateAreaCSV,
                    VarIndepLayerName + "_x_" + VarDepDisplayName, "ogr")
                DbfTablePath = os.path.join(
                    PastaTabelas,
                    VarIndepLayerName + "_x_" + VarDepDisplayName)
                QgsVectorFileWriter.writeAsVectorFormat(
                    LoadTabulateAreaCSV, DbfTablePath, "System", None,
                    "ESRI Shapefile")
                os.remove(DbfTablePath + ".prj")
                os.remove(DbfTablePath + ".qpj")

                # CARREGAR TABELA DBF PARA o QGIS
                DbfTable = QgsVectorLayer(
                    DbfTablePath + ".dbf",
                    VarIndepLayerName + "_x_" + VarDepDisplayName + ".dbf",
                    "ogr")
                AddDbfTable = QgsMapLayerRegistry.instance().addMapLayer(
                    DbfTable)

                # OBTER INDEXs DOS CAMPOS EXISTENTES
                IndexCampoV = DbfTable.fieldNameIndex("V")
                IndexCampoV0 = DbfTable.fieldNameIndex("V0")
                IndexCampoV1 = DbfTable.fieldNameIndex("V1")
                IndexCampoT = DbfTable.fieldNameIndex("T")

                # CRIAR CAMPOS A CALCULAR
                CampoVALUE = DbfTable.dataProvider().addAttributes(
                    [QgsField("VALUE", QVariant.Int)])
                CampoVALUE_0 = DbfTable.dataProvider().addAttributes(
                    [QgsField("VALUE_0", QVariant.Int)])
                CampoVALUE_1 = DbfTable.dataProvider().addAttributes(
                    [QgsField("VALUE_1", QVariant.Int)])
                CampoARCLASSE = DbfTable.dataProvider().addAttributes(
                    [QgsField("ARCLASSE", QVariant.Int)])
                CampoPROBCOND = DbfTable.dataProvider().addAttributes(
                    [QgsField("PROBCOND", QVariant.Double)])
                CampoSUM_VALUE0 = DbfTable.dataProvider().addAttributes(
                    [QgsField("SUM_VALUE0", QVariant.Int)])
                CampoSUM_VALUE1 = DbfTable.dataProvider().addAttributes(
                    [QgsField("SUM_VALUE1", QVariant.Int)])
                CampoAR_TOTAL = DbfTable.dataProvider().addAttributes(
                    [QgsField("AR_TOTAL", QVariant.Int)])
                CampoPRIORI = DbfTable.dataProvider().addAttributes(
                    [QgsField("PRIORI", QVariant.Double)])
                CampoSINI_SN = DbfTable.dataProvider().addAttributes(
                    [QgsField("SINI_SN", QVariant.Double)])
                CampoVI = DbfTable.dataProvider().addAttributes(
                    [QgsField("VI", QVariant.Double)])
                DbfTable.updateFields()

                # OBTER INDEXs DOS CAMPOS CRIADOS
                IndexCampoVALUE = DbfTable.fieldNameIndex("VALUE")
                IndexCampoVALUE_0 = DbfTable.fieldNameIndex("VALUE_0")
                IndexCampoVALUE_1 = DbfTable.fieldNameIndex("VALUE_1")
                IndexCampoARCLASSE = DbfTable.fieldNameIndex("ARCLASSE")
                IndexCampoPROBCOND = DbfTable.fieldNameIndex("PROBCOND")
                IndexCampoSUM_VALUE0 = DbfTable.fieldNameIndex("SUM_VALUE0")
                IndexCampoSUM_VALUE1 = DbfTable.fieldNameIndex("SUM_VALUE1")
                IndexCampoAR_TOTAL = DbfTable.fieldNameIndex("AR_TOTAL")
                IndexCampoPRIORI = DbfTable.fieldNameIndex("PRIORI")
                IndexCampoSINI_SN = DbfTable.fieldNameIndex("SINI_SN")
                IndexCampoVI = DbfTable.fieldNameIndex("VI")

                # COPIAR VALORES PARA OS CAMPOS BASE
                DbfTable.startEditing()
                for Valores in processing.features(DbfTable):
                    DbfTable.changeAttributeValue(Valores.id(),
                                                  IndexCampoVALUE,
                                                  Valores[IndexCampoV])
                    DbfTable.changeAttributeValue(
                        Valores.id(), IndexCampoVALUE_0,
                        int(Valores[IndexCampoV0]) * CellSize)
                    DbfTable.changeAttributeValue(
                        Valores.id(), IndexCampoVALUE_1,
                        int(Valores[IndexCampoV1]) * CellSize)
                    DbfTable.changeAttributeValue(
                        Valores.id(), IndexCampoARCLASSE,
                        int(Valores[IndexCampoT]) * CellSize)
                DbfTable.commitChanges()
                DbfTable.updateFields()

                ListaVALUE_0 = []
                ListaVALUE_1 = []
                DbfTable.startEditing()
                for Valores in processing.features(DbfTable):
                    DbfTable.changeAttributeValue(
                        Valores.id(), IndexCampoPROBCOND,
                        float(Valores[IndexCampoVALUE_1]) /
                        float(Valores[IndexCampoARCLASSE]))
                    ListaVALUE_0.append(int(Valores[IndexCampoVALUE_0]))
                    ListaVALUE_1.append(int(Valores[IndexCampoVALUE_1]))
                DbfTable.commitChanges()
                DbfTable.updateFields()

                # CALCULAR CAMPOS 'SUM_VALUE0' e 'SUM_VALUE1'
                SomaVALUE_0 = sum(ListaVALUE_0)
                SomaVALUE_1 = sum(ListaVALUE_1)
                DbfTable.startEditing()
                for Valores in processing.features(DbfTable):
                    DbfTable.changeAttributeValue(Valores.id(),
                                                  IndexCampoSUM_VALUE0,
                                                  SomaVALUE_0)
                    DbfTable.changeAttributeValue(Valores.id(),
                                                  IndexCampoSUM_VALUE1,
                                                  SomaVALUE_1)
                DbfTable.commitChanges()
                DbfTable.updateFields()

                # CALCULAR CAMPO 'AR_TOTAL'
                DbfTable.startEditing()
                [
                    DbfTable.changeAttributeValue(
                        Valores.id(), IndexCampoAR_TOTAL,
                        float(Valores[IndexCampoSUM_VALUE0]) +
                        float(Valores[IndexCampoSUM_VALUE1]))
                    for Valores in processing.features(DbfTable)
                ]
                DbfTable.commitChanges()
                DbfTable.updateFields()

                # CALCULAR CAMPO 'PRIORI'
                DbfTable.startEditing()
                [
                    DbfTable.changeAttributeValue(
                        Valores.id(), IndexCampoPRIORI,
                        float(Valores[IndexCampoSUM_VALUE1]) /
                        float(Valores[IndexCampoAR_TOTAL]))
                    for Valores in processing.features(DbfTable)
                ]
                DbfTable.commitChanges()
                DbfTable.updateFields()

                # CALCULAR CAMPO 'SINI_SN'
                DbfTable.startEditing()
                [
                    DbfTable.changeAttributeValue(
                        Valores.id(), IndexCampoSINI_SN,
                        float(Valores[IndexCampoPROBCOND]) /
                        float(Valores[IndexCampoPRIORI]))
                    for Valores in processing.features(DbfTable)
                ]
                DbfTable.commitChanges()
                DbfTable.updateFields()

                # CALCULAR CAMPO 'VI'
                DbfTable.startEditing()
                ListaVI_Min = []
                for Valores in processing.features(DbfTable):
                    if float(Valores[IndexCampoSINI_SN]) > 0:
                        DbfTable.changeAttributeValue(
                            Valores.id(), IndexCampoVI,
                            math.log(float(Valores[IndexCampoSINI_SN])))
                        ListaVI_Min.append(
                            math.log(float(Valores[IndexCampoSINI_SN])))
                        ListaVI_Min.sort()
                        VI_MIN = (ListaVI_Min[0])
                for Valores in processing.features(DbfTable):
                    if float(Valores[IndexCampoSINI_SN]) == 0:
                        DbfTable.changeAttributeValue(Valores.id(),
                                                      IndexCampoVI,
                                                      float(VI_MIN))
                DbfTable.commitChanges()
                DbfTable.updateFields()

                # CRIAR EXPRESSAO E FICHEIRO TXT PARA RECLASSIFICACAO COM VALORES DE VI
                ListaReclass = []
                for Valores in processing.features(DbfTable):
                    ListaReclass.append(
                        str(Valores[IndexCampoVALUE]) + "=" +
                        str(int(round(Valores[IndexCampoVI], 9) * (10**8))))
                ExpressaoReclass = '\n'.join(ListaReclass)

                ReclassVITxt = os.path.join(
                    PastaTabelas, VarIndepLayerName + "_ReclassVI.txt")
                open(ReclassVITxt, 'wb').writelines(ExpressaoReclass)

                # RECLASSIFICACAO DAS VARIAVEIS INDEPENDENTES COM VALORES DE VI
                VarIndepVI = os.path.join(PastaOutput,
                                          VarIndepLayerName + "_VI.tif")
                processing.runalg("grass7:r.reclass", VarIndep, ReclassVITxt,
                                  Mask, 0, VarIndepVI)
                ListaVarIndepVI.append(VarIndepVI)

                # APAGAR CAMPOS INICIAIS PROVENIENTES DO CSV
                DbfTable.dataProvider().deleteAttributes(
                    [IndexCampoV, IndexCampoV0, IndexCampoV1, IndexCampoT])
                DbfTable.updateFields()

                # REMOVER VARIAVEIS INDEPENDENTES DO QGIS
                QgsMapLayerRegistry.instance().removeMapLayers(
                    [AddVarIndep.id()])

        # SOMAR RASTERS DAS VARIAVEIS INDEPENDENTES NO RASTER CALCULATOR PARA OBTER O MAPA VI FINAL
            EntriesVIRaster = []
            ListaVIRasterRef = []
            for Index, VarIndepVI, VarIndepLayerName in zip(
                    range(0, len(ListaVarIndepVI)), ListaVarIndepVI,
                    ListaLayerName):
                LoadVarIndepVI = QgsRasterLayer(VarIndepVI,
                                                VarIndepLayerName + "_VI")
                AddVarIndepVI = QgsMapLayerRegistry.instance().addMapLayer(
                    LoadVarIndepVI)
                VIRasterObject = processing.getObject(ListaVarIndepVI[Index])
                VIRaster = QgsRasterCalculatorEntry()
                VIRaster.raster = VIRasterObject
                VIRaster.ref = str(VarIndepLayerName + '_VI@1')
                VIRaster.bandNumber = 1
                EntriesVIRaster.append(VIRaster)
                ListaVIRasterRef.append(VIRaster.ref)

            ExpressaoCalculateVI = "(" + " + ".join(ListaVIRasterRef) + ")"
            VI = os.path.join(PastaOutput, "VI.tif")
            CalculateVI = QgsRasterCalculator(ExpressaoCalculateVI, VI,
                                              'GTiff', VIRasterObject.extent(),
                                              VIRasterObject.width(),
                                              VIRasterObject.height(),
                                              EntriesVIRaster)
            CalculateVI.processCalculation()

            # ADICIONAR RASTER DO VALOR INFORMATIVO AO QGIS
            LoadVI = QgsRasterLayer(VI, "VI")
            AddVI = QgsMapLayerRegistry.instance().addMapLayer(LoadVI)

            ####VALIDACAO:####

            # CONVERTER RASTER DO VI PARA VALORES INTEIROS
            VIint = os.path.join(PastaOutput, "VIint.tif")
            processing.runalg("gdalogr:rastercalculator", VI, "1", None, "1",
                              None, "1", None, "1", None, "1", None, "1",
                              "rint(A)", "", 4, "", VIint)

            # CRIAR REPORT E CALCULAR VALORES UNICOS DE VI
            VI_CountUniqueValues = os.path.join(PastaTabelas,
                                                "VI_CountUniqueValues.txt")
            processing.runalg("grass7:r.report", VIint, 5, "*", 255, True,
                              True, True, True, Mask, None,
                              VI_CountUniqueValues)

            VI_ReportReadLines = open(VI_CountUniqueValues).readlines()
            VI_ReportSelectLines = VI_ReportReadLines[4:-4]
            VI_UniqueValues = len(VI_ReportSelectLines)

            # DEFINIR CAMINHO DO OUTPUT E EXECUTAR R.COIN DE VALIDACAO
            VI_RCoin = os.path.join(
                PastaTabelas, "VI_x_" + ValidacaoDisplayName + "_Original.txt")
            processing.runalg("grass7:r.coin", VIint, RasterValidacao, 0,
                              False, Mask, None, VI_RCoin)

            # LER VI_RCOIN E SELECIONAR AS LINHAS COM INFORMACAO UTIL
            ValidacaoReadLines = open(VI_RCoin).readlines()
            ValidacaoSelectLines = ValidacaoReadLines[22:VI_UniqueValues + 22]

            # FORMATAR DADOS PARA IMPORTACAO EM CSV
            ValidacaoListaValores = []
            for row in ValidacaoSelectLines:
                RemoverEspacos = re.sub(' +', ' ', row)
                SubstituirEspacos = RemoverEspacos.replace(' ', ';')
                SepararPontoVirgula = SubstituirEspacos.split(";")
                SelecionarColunas = itemgetter(1, 5, 7)(SepararPontoVirgula)
                ConversaoInteiros = map(int, SelecionarColunas)
                ValidacaoListaValores.append(ConversaoInteiros)
            ValidacaoListaValores = sorted(ValidacaoListaValores, reverse=True)

            ListaOrdenada = []
            for row in ValidacaoListaValores:
                SubstituirEspacos = str(row).replace(', ', ';')
                RemoverParentese1 = SubstituirEspacos.replace('[', '')
                RemoverParentese2 = RemoverParentese1.replace(']', '')
                ListaOrdenada.append(RemoverParentese2)
            ListaOrdenada.insert(0, 'V;V1;T')
            ValidacaoValoresImportar = '\n'.join(ListaOrdenada)

            # ESCREVER DADOS FORMATADOS NUM NOVO FICHEIRO TXT
            VI_RCoinTemp = os.path.join(
                PastaTabelas, "VI_x_" + ValidacaoDisplayName + "_Tratado.txt")
            open(VI_RCoinTemp, 'wb').writelines(ValidacaoValoresImportar)

            # IMPORTAR PARA FICHEIRO CSV
            TS_CSV = os.path.join(PastaTabelas,
                                  "VI_x_" + ValidacaoDisplayName + ".csv")
            csv.writer(open(TS_CSV, 'wb')).writerows(
                csv.reader(open(VI_RCoinTemp, 'rb')))

            # EXPORTAR PARA DBF
            LoadTSCSV = QgsVectorLayer(TS_CSV, "TS", "ogr")
            DbfTSPath = os.path.join(PastaTabelas, "TS")
            QgsVectorFileWriter.writeAsVectorFormat(LoadTSCSV, DbfTSPath,
                                                    "System", None,
                                                    "ESRI Shapefile")
            os.remove(DbfTSPath + ".prj")
            os.remove(DbfTSPath + ".qpj")

            # CARREGAR TABELA DBF PARA o QGIS
            DbfTS = QgsVectorLayer(DbfTSPath + ".dbf", "TS.dbf", "ogr")
            AddDbfTS = QgsMapLayerRegistry.instance().addMapLayer(DbfTS)

            # OBTER INDEXs DOS CAMPOS EXISTENTES
            TS_IndexCampoV = DbfTS.fieldNameIndex("V")
            TS_IndexCampoV1 = DbfTS.fieldNameIndex("V1")
            TS_IndexCampoT = DbfTS.fieldNameIndex("T")

            # CRIAR CAMPOS A CALCULAR
            TS_CampoVI = DbfTS.dataProvider().addAttributes(
                [QgsField("VI", QVariant.Double)])
            TS_CampoARESTUDO = DbfTS.dataProvider().addAttributes(
                [QgsField("ARESTUDO", QVariant.Int)])
            TS_CampoARFENOM = DbfTS.dataProvider().addAttributes(
                [QgsField("ARFENOM", QVariant.Int)])
            TS_CampoArEstudAc = DbfTS.dataProvider().addAttributes(
                [QgsField("ArEstudAc", QVariant.Double)])
            TS_CampoArFenomAc = DbfTS.dataProvider().addAttributes(
                [QgsField("ArFenomAc", QVariant.Double)])
            TS_CampoLsi_Li = DbfTS.dataProvider().addAttributes(
                [QgsField("Lsi_Li", QVariant.Double)])
            TS_Campoai_b1_2 = DbfTS.dataProvider().addAttributes(
                [QgsField("ai_b1_2", QVariant.Double)])
            TS_CampoACC = DbfTS.dataProvider().addAttributes(
                [QgsField("ACC", QVariant.Double)])
            DbfTS.updateFields()

            # OBTER INDEXs DOS CAMPOS CRIADOS
            TS_IndexCampoVI = DbfTS.fieldNameIndex("VI")
            TS_IndexCampoARESTUDO = DbfTS.fieldNameIndex("ARESTUDO")
            TS_IndexCampoARFENOM = DbfTS.fieldNameIndex("ARFENOM")
            TS_IndexCampoArEstudAc = DbfTS.fieldNameIndex("ArEstudAc")
            TS_IndexCampoArFenomAc = DbfTS.fieldNameIndex("ArFenomAc")
            TS_IndexCampoLsi_Li = DbfTS.fieldNameIndex("Lsi_Li")
            TS_IndexCampoai_b1_2 = DbfTS.fieldNameIndex("ai_b1_2")
            TS_IndexCampoACC = DbfTS.fieldNameIndex("ACC")

            # COPIAR VALORES PARA OS CAMPOS BASE
            DbfTS.startEditing()
            for Valores in processing.features(DbfTS):
                DbfTS.changeAttributeValue(
                    Valores.id(), TS_IndexCampoVI,
                    float(Valores[TS_IndexCampoV]) / float(10**8))
                DbfTS.changeAttributeValue(
                    Valores.id(), TS_IndexCampoARESTUDO,
                    int(Valores[TS_IndexCampoT]) * CellSize)
                DbfTS.changeAttributeValue(
                    Valores.id(), TS_IndexCampoARFENOM,
                    int(Valores[TS_IndexCampoV1]) * CellSize)
            DbfTS.commitChanges()
            DbfTS.updateFields()

            # CPRIAR LISTAS DE VALORES PARA AS SOMAS ACUMULADAS
            ListaARESTUDO = []
            ListaARFENOM = []
            for Valores in processing.features(DbfTS):
                ListaARESTUDO.append(int(Valores[TS_IndexCampoARESTUDO]))
                ListaARFENOM.append(int(Valores[TS_IndexCampoARFENOM]))

        # CALCULAR CAMPOS 'ArEstudAc', 'ArFenomAc'
            SomaARESTUDO = sum(ListaARESTUDO)
            SomaARFENOM = sum(ListaARFENOM)
            DbfTS.startEditing()
            for Valores, SomaAcARESTUDO, SomaAcARFENOM in zip(
                    processing.features(DbfTS), numpy.cumsum(ListaARESTUDO),
                    numpy.cumsum(ListaARFENOM)):
                if Valores.id() == 0:
                    DbfTS.changeAttributeValue(Valores.id(),
                                               TS_IndexCampoArFenomAc, 0)
                    DbfTS.changeAttributeValue(Valores.id(),
                                               TS_IndexCampoArEstudAc, 0)
                else:
                    DbfTS.changeAttributeValue(
                        Valores.id(), TS_IndexCampoArEstudAc,
                        float(SomaAcARESTUDO) / float(SomaARESTUDO))
                    DbfTS.changeAttributeValue(
                        Valores.id(), TS_IndexCampoArFenomAc,
                        float(SomaAcARFENOM) / float(SomaARFENOM))
            DbfTS.commitChanges()

            # CALCULAR CAMPOS 'Lsi_Li', 'ai_b1_2'
            ListaArEstudAc = []
            ListaArFenomAc = []
            for Valores in processing.features(DbfTS):
                ListaArEstudAc.append(float(Valores[TS_IndexCampoArEstudAc]))
                ListaArFenomAc.append(float(Valores[TS_IndexCampoArFenomAc]))
            ListaArEstudAc.insert(0, 0)
            ListaArFenomAc.insert(0, 0)

            DbfTS.startEditing()
            for Valores, ValoresArEstudAc, ValoresArFenomAc in zip(
                    processing.features(DbfTS), ListaArEstudAc,
                    ListaArFenomAc):
                if Valores.id() == 0:
                    DbfTS.changeAttributeValue(Valores.id(),
                                               TS_IndexCampoLsi_Li, 0)
                    DbfTS.changeAttributeValue(Valores.id(),
                                               TS_IndexCampoai_b1_2, 0)
                else:
                    DbfTS.changeAttributeValue(
                        Valores.id(), TS_IndexCampoLsi_Li,
                        float(Valores[TS_IndexCampoArEstudAc]) -
                        float(ValoresArEstudAc))
                    DbfTS.changeAttributeValue(
                        Valores.id(), TS_IndexCampoai_b1_2,
                        float(
                            float(Valores[TS_IndexCampoArFenomAc]) +
                            float(ValoresArFenomAc)) / float(2))
            DbfTS.commitChanges()

            # CALCULAR CAMPO 'AAC'
            DbfTS.startEditing()
            for Valores in processing.features(DbfTS):
                DbfTS.changeAttributeValue(
                    Valores.id(), TS_IndexCampoACC,
                    float(Valores[TS_IndexCampoai_b1_2]) *
                    float(Valores[TS_IndexCampoLsi_Li]))
            DbfTS.commitChanges()

            # SOMAR VALORES DE ACC PARA ESCREVER A MENSAGEM
            ListaACC = []
            for Valores in DbfTS.getFeatures():
                ListaACC.append(Valores[TS_IndexCampoACC])
            SomaACC = round(sum(ListaACC), 4)

            # APAGAR CAMPOS INICIAIS PROVENIENTES DO CSV
            DbfTS.dataProvider().deleteAttributes(
                [TS_IndexCampoV, TS_IndexCampoV1, TS_IndexCampoT])
            DbfTS.updateFields()

            msgBar = self.iface.messageBar()
            msgBar.pushWidget(
                msgBar.createMessage(
                    "########### O MODELO FOI VALIDADO COM UMA TAXA DE SUCESSO DE "
                    + str(SomaACC) + "! ###########"), QgsMessageBar.INFO
            )  #"...INFO, 5)" para defenir o tempo da mensagem
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
import sys
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
import processing
import os

layer = iface.activeLayer()
entries = []

# Define band1
boh1 = QgsRasterCalculatorEntry()
boh1.ref = 'boh@1'
boh1.raster = layer
boh1.bandNumber = 1
entries.append(boh1)

# Define band3
boh3 = QgsRasterCalculatorEntry()
boh3.ref = 'boh@3'
boh3.raster = layer
boh3.bandNumber = 3
entries.append(boh3)

#project file path
project_file_root = QgsProject.instance().readPath("./")
# Process calculation with input extent and resolution
calc = QgsRasterCalculator('boh@1 + boh@3',
Exemple #12
0
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """

        # Retrieve the feature source and sink. The 'dest_id' variable is used
        # to uniquely identify the feature sink, and must be included in the
        # dictionary returned by the processAlgorithm function.
        rasterInput = self.parameterAsRasterLayer(parameters, self.INPUT,
                                                  context)

        firstVal = self.parameterAsDouble(parameters, self.INPUT_DOUBLE_1,
                                          context)

        secondVal = self.parameterAsDouble(parameters, self.INPUT_DOUBLE_2,
                                           context)

        feedback.pushInfo('First Value : ' + str(firstVal))
        feedback.pushInfo('Second Value: ' + str(secondVal))

        mFunction = self.parameterAsEnum(parameters, self.CHOICE_MFUNCTION,
                                         context)
        feedback.pushInfo('Membership Function: ' + str(mFunction))

        outputFile = self.parameterAsOutputLayer(parameters, self.OUTPUT,
                                                 context)
        feedback.pushInfo('Output File: ' + outputFile)

        rCalcEntry = QgsRasterCalculatorEntry()
        rCalcEntry.ref = 'r1@1'
        rCalcEntry.raster = rasterInput

        l_plus = '((r1@1 >= %s) AND (r1@1 <= %s)) * ((r1@1 -  %s) / (%s - %s))' % (
            firstVal, secondVal, firstVal, secondVal, firstVal)
        l_minus = '((r1@1 >= %s) AND (r1@1 <= %s)) * ((%s - r1@1 ) / (%s - %s))' % (
            firstVal, secondVal, secondVal, secondVal, firstVal)

        cos_plus = '((r1@1 >= %s) AND (r1@1 <= %s)) * ( 0.5 * ( 1 - cos( 3.141592 * (( r1@1 - %s ) / (%s - %s) ))))' % (
            firstVal, secondVal, firstVal, secondVal, firstVal)
        #No anda bien
        cos_minus = '((r1@1 >= %s) AND (r1@1 <= %s)) * ( 0.5 * ( 1 + cos( 3.141592 * (( r1@1 - %s ) / (%s - %s) ))))' % (
            firstVal, secondVal, firstVal, secondVal, firstVal)

        gaussf = ' ( 2.7182818 ^ (( -1 * (r1@1 - %s ) ^ 2) / (2 * %s * %s) ))' % (
            firstVal, secondVal, secondVal)

        ceroOne = '(r1@1 < %s) * 0 + (r1@1 > %s) * 1' % (firstVal, secondVal)
        oneCero = '(r1@1 < %s) * 1 + (r1@1 > %s) * 0' % (firstVal, secondVal)
        ceroCero = '(r1@1 < %s) * 0 + (r1@1 > %s) * 0' % (firstVal, secondVal)

        if mFunction == 0:
            formula = l_plus + ' + ' + ceroOne
        elif mFunction == 1:
            formula = l_minus + ' + ' + oneCero
        elif mFunction == 2:
            formula = cos_plus + ' + ' + ceroOne
        elif mFunction == 3:
            formula = cos_minus + ' + ' + oneCero
        elif mFunction == 4:
            formula = gaussf
        #formula = '(r1@1 < %s) * 0 + (r1@1 > %s) * 1 + (((r1@1 >= %s) AND (r1@1 <= %s)) * ((r1@1 -  %s) / (%s - %s)) ' % (firstVal, secondVal, firstVal, secondVal, firstVal, secondVal, firstVal )

        feedback.pushInfo('Formula: ' + str(formula))
        calc = QgsRasterCalculator(formula, outputFile, 'GTiff',
                                   rasterInput.extent(), rasterInput.width(),
                                   rasterInput.height(), [rCalcEntry])
        #calc = QgsRasterCalculator("r1@1", outputFile, 'GTiff', rasterInput.extent(), rasterInput.width(), rasterInput.height(), [rCalcEntry])

        feedback.pushInfo("p calc1")
        calc.processCalculation()
        feedback.pushInfo("p calc1")

        return {self.OUTPUT: outputFile}
Exemple #13
0
    def processAlgorithm(self, parameters, context, feedback):
        expression = self.parameterAsString(parameters, self.EXPRESSION, context)
        layers = self.parameterAsLayerList(parameters, self.LAYERS, context)

        layersDict = {}
        if layers:
            layersDict = {lyr.source(): lyr for lyr in layers}

        crs = self.parameterAsCrs(parameters, self.CRS, context)
        if crs is None or not crs.isValid():
            if not layers:
                raise QgsProcessingException(self.tr("No reference layer selected nor CRS provided"))
            else:
                crs = list(layersDict.values())[0].crs()

        bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
        if bbox.isNull() and not layers:
            raise QgsProcessingException(self.tr("No reference layer selected nor extent box provided"))

        if not bbox.isNull():
            bboxCrs = self.parameterAsExtentCrs(parameters, self.EXTENT, context)
            if bboxCrs != crs:
                transform = QgsCoordinateTransform(bboxCrs, crs, context.project())
                bbox = transform.transformBoundingBox(bbox)

        if bbox.isNull() and layers:
            bbox = QgsProcessingUtils.combineLayerExtents(layers, crs)

        cellsize = self.parameterAsDouble(parameters, self.CELLSIZE, context)
        if cellsize == 0 and not layers:
            raise QgsProcessingException(self.tr("No reference layer selected nor cellsize value provided"))

        def _cellsize(layer):
            ext = layer.extent()
            if layer.crs() != crs:
                transform = QgsCoordinateTransform(layer.crs(), crs, context.project())
                ext = transform.transformBoundingBox(ext)
            return (ext.xMaximum() - ext.xMinimum()) / layer.width()
        if cellsize == 0:
            cellsize = min([_cellsize(lyr) for lyr in layersDict.values()])

        # check for layers available in the model
        layersDictCopy = layersDict.copy() # need a shallow copy because next calls invalidate iterator
        for lyr in layersDictCopy.values():
            expression = self.mappedNameToLayer(lyr, expression, layersDict, context)

        # check for layers available in the project
        for lyr in QgsProcessingUtils.compatibleRasterLayers(context.project()):
            expression = self.mappedNameToLayer(lyr, expression, layersDict, context)

        # create the list of layers to be passed as inputs to RasterCalculaltor
        # at this phase expression has been modified to match available layers
        # in the current scope
        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                ref = '{:s}@{:d}'.format(name, n + 1)

                if ref in expression:
                    entry = QgsRasterCalculatorEntry()
                    entry.ref = ref
                    entry.raster = lyr
                    entry.bandNumber = n + 1
                    entries.append(entry)

        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)

        calc = QgsRasterCalculator(expression,
                                   output,
                                   driverName,
                                   bbox,
                                   crs,
                                   width,
                                   height,
                                   entries)

        res = calc.processCalculation(feedback)
        if res == QgsRasterCalculator.ParserError:
            raise QgsProcessingException(self.tr("Error parsing formula"))

        return {self.OUTPUT: output}
Exemple #14
0
rasterobject = None

# A list of QgsRasterCalculatorEntries, We append to this for later inputs
entries = []

path = "Path to export"

# Replace this with your raster object likely taken in from FileInput
raster = rasterobject

# Initilize the Raster Calculator Entries
rasterEntry1 = QgsRasterCalculatorEntry()
rasterEntry2 = QgsRasterCalculatorEntry()

# start assigning names for these things
rasterEntry1.ref = "raster1"
rasterEntry2.ref = "raster2"

rasterEntry1.bandNumber = 1  # This is the band to work from
rasterEntry2.bandNumber = 1

rasterEntry1.raster = raster

entries.append(rasterEntry1)

expression = "(\"{0}\"-\"{1}\")/(\"{2}\"+\"{3}\")".format(
    rasterEntry1.ref, rasterEntry2.ref, rasterEntry1.ref, rasterEntry2.ref)

# This follows the following requirements, the expression, path too,
# Export type, the extend of the image, the width then height followed by
# the rastercalc entries
    def normalization(self):
        tempdir = self.gettempdir()
        lst = self.chek_fields()
        lst_escNames = []

        for layer in lst[0:4]:
            lyrPath = layer.source()
            lyrName = layer.name()
            lyr2 = QgsRasterLayer(lyrPath, lyrName)

            entries = []
            ras1 = QgsRasterCalculatorEntry()
            ras1.ref = lyrName + '@1'
            ras1.raster = lyr2
            ras1.bandNumber = 1
            entries.append(ras1)

            formula = "\"" + ras1.ref + "\"" + ' / ' + str(self.sumValue(lyr2))
            output = tempdir + "/Stnd_Exp_%s.tif" % str(lyrName)
            lst_escNames.append(str(output))
            calc = QgsRasterCalculator(formula, output, 'GTiff', lyr2.extent(),
                                       lyr2.width(), lyr2.height(), entries)
            calc.processCalculation()

        for layer in lst[4:6]:
            lyrPath = layer.source()
            lyrName = layer.name()
            lyr2 = QgsRasterLayer(lyrPath, lyrName)

            entries = []
            ras1 = QgsRasterCalculatorEntry()
            ras1.ref = lyrName + '@1'
            ras1.raster = lyr2
            ras1.bandNumber = 1
            entries.append(ras1)

            formula = "\"" + ras1.ref + "\"" + ' / ' + str(self.sumValue(lyr2))
            output = tempdir + "/Stnd_Sen_%s.tif" % str(lyrName)
            lst_escNames.append(str(output))
            calc = QgsRasterCalculator(formula, output, 'GTiff', lyr2.extent(),
                                       lyr2.width(), lyr2.height(), entries)
            calc.processCalculation()

        for layer in lst[6:]:
            lyrPath = layer.source()
            lyrName = layer.name()
            lyr2 = QgsRasterLayer(lyrPath, lyrName)

            entries = []
            ras1 = QgsRasterCalculatorEntry()
            ras1.ref = lyrName + '@1'
            ras1.raster = lyr2
            ras1.bandNumber = 1
            entries.append(ras1)

            formula = "\"" + ras1.ref + "\"" + ' / ' + str(self.sumValue(lyr2))
            output = tempdir + "/Stnd_Capa_%s.tif" % str(lyrName)
            lst_escNames.append(str(output))
            calc = QgsRasterCalculator(formula, output, 'GTiff', lyr2.extent(),
                                       lyr2.width(), lyr2.height(), entries)
            calc.processCalculation()

        return lst_escNames
Exemple #16
0
##reflectance_mult=number 0
##reflectance_add=number 0
##sun_elevation=number 0
##inImage=raster
##outImage=output raster

from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

lyr = processing.getObject(inImage)
entries=[]
rasterCalcEntry=QgsRasterCalculatorEntry()
rasterCalcEntry.ref='IMG@1'
rasterCalcEntry.raster=lyr
rasterCalcEntry.bandNumber=1
entries.append(rasterCalcEntry)

if not ".tif" in outImage:
    outImage=outImage+".tif"

noData=-3.4028234663852886e+38
radElev = sun_elevation*3.14159/180
calc=QgsRasterCalculator('(IMG@1 != 0)*('+str(reflectance_mult)+' * IMG@1 + '+str(reflectance_add)+')/sin('+str(radElev)+') + (IMG@1 = 0) * '+str(noData), outImage, "GTiff",  lyr.extent(), lyr.crs(), lyr.width(), lyr.height(), entries)
calc.processCalculation()
Exemple #17
0
import processing
from qgis.core import QgsMapLayerRegistry, QgsRasterLayer
from qgis.analysis import QgsRasterCalculatorEntry, QgsRasterCalculator
from PyQt4.QtCore import QFileInfo

# Split rasters
layers = Raster.split(';')
output_path = OUT + "/"
suffix = "_suffix.tif"

for ras in layers:
    # Get layer object
    lyr = processing.getObjectFromUri(ras)
    entries = []
    ras = QgsRasterCalculatorEntry()
    ras.ref = 'lyr@1'
    ras.raster = lyr
    ras.bandNumber = 1
    entries.append(ras)
    calc = QgsRasterCalculator('(lyr@1 / lyr@1) * lyr@1',
                               output_path + lyr.name() + suffix, 'GTiff',
                               lyr.extent(), lyr.width(), lyr.height(),
                               entries)
    calc.processCalculation()

for results in glob.glob(output_path + "*" + suffix):
    fileInfo = QFileInfo(results)
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()
    layer = QgsRasterLayer(path, baseName)
    QgsMapLayerRegistry.instance().addMapLayer(layer)
Exemple #18
0
def genere_carteFinale(pP, pR, pI, pKa, rCarte_P, rCarte_R, rCarte_I,
                       rCarte_Ka, doss, extension):
    #creation des entrees pour le calculateur de raster
    entries = []
    LayI = QgsRasterCalculatorEntry()
    LayI.ref = "LayI@1"
    LayI.raster = rCarte_I
    LayI.bandNumber = 1
    entries.append(LayI)

    LayK = QgsRasterCalculatorEntry()
    LayK.ref = "LayK@1"
    LayK.raster = rCarte_Ka
    LayK.bandNumber = 1
    entries.append(LayK)

    LayR = QgsRasterCalculatorEntry()
    LayR.ref = "LayR@1"
    LayR.raster = rCarte_R
    LayR.bandNumber = 1
    entries.append(LayR)

    LayP = QgsRasterCalculatorEntry()
    LayP.ref = "LayP@1"
    LayP.raster = rCarte_P
    LayP.bandNumber = 1
    entries.append(LayP)

    #creation du calcul a realiser
    Formula = "LayI@1*%s+LayK@1*%s+LayR@1*%s+LayP@1*%s" % (pI, pKa, pR, pP)

    #realisation du calcul et affichage de la Carte Vg non reclassee
    calc = QgsRasterCalculator(Formula,
                               str(doss) + '/Carte_Vg.tif', 'Gtiff',
                               rCarte_I.extent(), rCarte_I.width(),
                               rCarte_I.height(), entries)
    test = calc.processCalculation()

    #reclassement
    #recuperation de l'extension en string pour le r:reclass
    extension1 = gdal.Open(extension.source())
    ExtentInfo = extension1.GetGeoTransform()
    Xmin = str(ExtentInfo[0])
    Ymin = str(ExtentInfo[3])
    Xmax = str(ExtentInfo[0] + ExtentInfo[1] * extension1.RasterXSize)
    Ymax = str(ExtentInfo[3] + ExtentInfo[5] * extension1.RasterYSize)
    Extent = (Xmin, Xmax, Ymax, Ymin)
    StrExtent = ','.join(Extent)

    #reclassement de la Carte Vg et affichage de la carte
    if QGis.QGIS_VERSION_INT > 21800:
        processing.runalg(
            "grass7:r.reclass",
            str(doss) + '/Carte_Vg.tif',
            os.path.dirname(os.path.abspath(__file__)) +
            '/reclass_rules/reclass_rules_carteVg.txt', "", StrExtent,
            int(ExtentInfo[1]),
            str(doss) + '/rVulnerability_Map.tif')
    else:
        processing.runalg(
            "grass7:r.reclass",
            str(doss) + '/Carte_Vg.tif',
            os.path.dirname(os.path.abspath(__file__)) +
            '/reclass_rules/reclass_rules_carteVg.txt', StrExtent,
            int(ExtentInfo[1]),
            str(doss) + '/rVulnerability_Map.tif')

    src_ds_Carte_Finale = gdal.Open(str(doss) + '/rVulnerability_Map.tif')
    driver_Carte_Finale = gdal.GetDriverByName("GTiff")
    dst_ds_Carte_Finale = driver_Carte_Finale.CreateCopy(
        str(doss) + '/Vulnerability_Map.tif', src_ds_Carte_Finale, 0)
    src_ds_Carte_Finale = None
    dst_ds_Carte_Finale = None
    os.remove(str(doss) + '/rVulnerability_Map.tif')
    os.remove(str(doss) + '/rVulnerability_Map.tfw')
    #rCarte_Finale = QgsRasterLayer(str(doss)+'/Vulnerability_Map.tif', "Vulnerability Map")

    #fermeture des connexions
    rCarte_I = None
    rCarte_P = None
    rCarte_Ka = None
    rCarte_R = None
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

layer = iface.activeLayer()
entries = []

# Define band1
band1 = QgsRasterCalculatorEntry()
band1.ref = 'band@1'
band1.raster = layer
band1.bandNumber = 1
entries.append(band1)

renderer = layer.renderer()
provider = layer.dataProvider()
extent = layer.extent()

stats = provider.bandStatistics(1, QgsRasterBandStats.All, extent, 0)

myMean = stats.mean
myStdDev = stats.stdDev

myFormula = '(band@1 -' + str(myMean) + ')/' + str(myStdDev)

print("mean = ", myMean)

print("stdev = ", myStdDev)

# Process calculation with input extent and resolution
calc = QgsRasterCalculator(myFormula, '/home/zeito/pyqgis_data/outputfile.tif',
                           'GTiff', layer.extent(), layer.width(),
                           layer.height(), entries)
Exemple #20
0
 def defineentry(self, layer):
     a = QgsRasterCalculatorEntry()
     a.ref = str(layer.name()) + '@1'
     a.raster = layer
     a.bandNumber = 1
     return a
Exemple #21
0
    def rastercalcmulti_ndvi(self,
                             rLayer1,
                             path,
                             calctype,
                             rLayer2=None,
                             r1Band=1,
                             r2Band=1,
                             rLayer3=None,
                             r3Band=1):
        """
        Calculate any type of NDVI like Calculation from various types of Cameras be they: Multi output, NGB, RGB, NR
        :param r1Band: first Raster Layer Band number
        :param rLayer3: third rLayer object
        :param r3Band: third Raster band
        :param rLayer1: first rLayer object
        :param path: path to Output
        :param calctype: Calculation to perform
        :param rLayer2: second rLayer object
        :param r2Band: band Number
        :return: None
        """
        """
        TODO: Add support for Multiple different Raster types, be they Single Raster (Of NGB, RGB or otherwise) or Multiraster

        https://maxmax.com/ndv_historyi.htm

        Implement NDVI Red
        NDVI blue
         and ENDVI (Enhanced NDVI)
        """
        if path == '' or path is None:
            self.com.log(
                "No Path on NDVI calc function, This will likely cause an error",
                level=2)

        path = path
        r1 = QgsRasterCalculatorEntry()
        r2 = QgsRasterCalculatorEntry()
        r3 = QgsRasterCalculatorEntry()

        exporttype = "GTiff"

        # Do variable creation
        # TODO: Fix this, it's spaghetti AF
        r1.raster = rLayer1
        r1.bandNumber = r1Band
        r2.bandNumber = r2Band
        r3.bandNumber = r3Band

        r1.ref = 'Input1@1'
        r2.ref = 'Input2@1'
        r3.ref = 'Input3@1'

        if r1Band is None:
            r1.bandNumber = 1

        if rLayer2 is not None:
            r2.raster = rLayer2

        if rLayer3 is not None:
            r3.raster = rLayer3

        entries = []

        if calctype is None:
            self.com.error(String="Calctype None", level=2)

        elif calctype == "NDVI":
            # This assumes that that rLayer1 is N and rLayer2 is R
            entries.append(r1)
            entries.append(r2)
            expression = "(\"{0}\"-\"{1}\")/(\"{2}\"+\"{3}\")".format(
                r1.ref, r2.ref, r1.ref, r2.ref)
            a = QgsRasterCalculator(expression, path, exporttype,
                                    rLayer1.extent(), rLayer1.width(),
                                    rLayer1.height(), entries)
            a.processCalculation()

        elif calctype == "bNDVI":
            # This assumes that rLayer1 in N and rLayer2 is B
            entries.append(r1)
            entries.append(r2)
            expression = "(\"{0}\"-\"{1}\")/(\"{2}\"+\"{3}\")".format(
                r1.ref, r2.ref, r1.ref, r2.ref)
            a = QgsRasterCalculator(expression, path, exporttype,
                                    rLayer1.extent(), rLayer1.width(),
                                    rLayer1.height(), entries)
            a.processCalculation()

        elif calctype == "ENDVI":
            # This assumes that rLayer1 is N, rLayer2 is Green and rLayer3 is
            # Blue
            entries.append(r1)
            entries.append(r2)
            entries.append(r3)
            expression = "((\"{0}\"+\"{1}\")-(2*\"{2}\"))/((\"{0}\"+\"{1}\")+(2*\"{2}\"))".format(
                r1.ref, r2.ref, r3.ref)
            a = QgsRasterCalculator(expression, path, exporttype,
                                    rLayer1.extent(), rLayer1.width(),
                                    rLayer1.height(), entries)
            a.processCalculation()

        elif calctype == "EVI":
            entries.append(r1)
            entries.append(r2)
            entries.append(r3)
            expression = "2.5*(\"{0}\"-\"{1}\")/(\"{0}\"+6*\"{1}\"-7.5*\"{2}\"+1)".format(
                r1.ref, r2.ref, r3.ref)

            a = QgsRasterCalculator(expression, path, exporttype,
                                    rLayer1.extent(), rLayer1.width(),
                                    rLayer1.height(), entries)

            a.processCalculation()

        else:
            self.com.error(Bold="CalcType Error",
                           String="Unrecognized calctype",
                           level=2)
    else:
        # print("Unable to read basename and file path - Your string is probably invalid")
        return NULL


luccfilename = r'G:\mongolia_grass_capacity\data\lucc_esacci\grass.tif'
luccraster = OpenRaster(luccfilename)
print("Lucc : " + str(luccraster.isValid()))

nppfilename = r'G:\mongolia_grass_capacity\data\npp_avhrr\output\n3stdgt0.tif'
nppraster = OpenRaster(nppfilename)
print("NPP : " + str(nppraster.isValid()))

entries = []
boh1 = QgsRasterCalculatorEntry()
boh1.ref = 'lucc@1'
boh1.raster = luccraster
boh1.bandNumber = 1
entries.append(boh1)

boh2 = QgsRasterCalculatorEntry()
boh2.ref = 'npp@1'
boh2.raster = nppraster
boh2.bandNumber = 1
entries.append(boh2)

# Process calculation with input extent and resolution
calc = QgsRasterCalculator('lucc@1 + npp@1', 'G:/abc.tif', 'GTiff',
                           luccraster.extent(), luccraster.width(),
                           luccraster.height(), entries)
Exemple #23
0
#Author: Isaac Lohnes
#Date: Revised on 2/18/2019

#Imports:
from PyQt4 import QtGui
import processing
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

#Setup input and output for comparison calc
julyLayer = processing.getObjectFromName('NDVI_Jul_4_18')
augustLayer = processing.getObjectFromName('NDVI_Aug_31_18')
output = "C:\schoolRepos\w0409360\GIS\NVDICompare\NDVI Rasters\NDVI Rasters\NDVI_Compare.tif"

#setting up new calc entry with reference, raster set to file, and band number set to 1
julyRaster = QgsRasterCalculatorEntry()
julyRaster.ref = "July@1"
julyRaster.raster = julyLayer
julyRaster.bandNumber = 1

#setting up new calc entry with reference, raster set to file, and band number set to 1
augustRaster = QgsRasterCalculatorEntry()
augustRaster.ref = "Aug@1"
augustRaster.raster = augustLayer
augustRaster.bandNumber = 1

#Creating list of rasters to use in calc
rasterList = [julyRaster, augustRaster]

#Formula finds difference in references
formula = ('Aug@1 - July@1')
Exemple #24
0
def mapa_final_no_compensatorio(n_variables, pesos, raster_inputs,
                                raster_salida):

    ecuacion = '('
    for a, b in zip(range(n_variables), pesos):

        if a < n_variables - 1:
            ecuacion += ("(" + str(b) + "^10) * " + "'(1 - (layer" +
                         str(a + 1) + "@1 ^10))'" + ' + ')
        else:
            ecuacion += ("(" + str(b) + "^10) * " + "'(1 - (layer" +
                         str(a + 1) + "@1 ^10))'")
    ecuacion += '  ) ^ 1/10'
    entries = []

    #abre el archivo raster1
    fileInfo = QFileInfo(raster_inputs[0])
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()
    layer1 = QgsRasterLayer(path, baseName)
    var1 = QgsRasterCalculatorEntry()
    var1.ref = 'layer1@1'
    var1.raster = layer1
    var1.bandNumber = 1
    entries.append(var1)

    if n_variables == 2:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)
    elif n_variables == 3:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

    elif n_variables == 4:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

        fileInfo = QFileInfo(raster_inputs[3])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer4 = QgsRasterLayer(path, baseName)
        var4 = QgsRasterCalculatorEntry()
        var4.ref = 'layer4@1'
        var4.raster = layer4
        var4.bandNumber = 1
        entries.append(var4)

    elif n_variables == 5:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

        fileInfo = QFileInfo(raster_inputs[3])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer4 = QgsRasterLayer(path, baseName)
        var4 = QgsRasterCalculatorEntry()
        var4.ref = 'layer4@1'
        var4.raster = layer4
        var4.bandNumber = 1
        entries.append(var4)

        fileInfo = QFileInfo(raster_inputs[4])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer5 = QgsRasterLayer(path, baseName)
        var5 = QgsRasterCalculatorEntry()
        var5.ref = 'layer5@1'
        var5.raster = layer5
        var5.bandNumber = 1
        entries.append(var5)

    calc = QgsRasterCalculator(ecuacion, raster_salida,
                               'GTiff', layer1.extent(), layer1.width(),
                               layer1.height(), entries)

    calc.processCalculation()
Exemple #25
0
import qgis
from qgis.analysis import QgsRasterCalculatorEntry, QgsRasterCalculator

lyr_red = 'T31TDF_20191109T104251_B04_10m'
lyr_ir = 'T31TDF_20191109T104251_B08_10m'
# Set this path before runing the script
lyr_ndvi = '/home/diego/Documents/maps/Barcelona/images/T31TDF_20191109_NDVI.tif'

# Set up raster bands as variables
ras_red = QgsRasterCalculatorEntry()
ras_ir = QgsRasterCalculatorEntry()
# Set up the references
ras_red.ref = 'red@1'
ras_ir.ref = 'ir@1'
# Set up raster values
ras_red.raster = QgsProject.instance().mapLayersByName(lyr_red)[0]
ras_ir.raster = QgsProject.instance().mapLayersByName(lyr_ir)[0]
# Set up the band to read digital levels
ras_red.bandNumber = 1
ras_ir.bandNumber = 1
# Set entries for the Raster Calculator
entries = []
entries.append(ras_red)
entries.append(ras_ir)
# Set the formula and execute it
calc = QgsRasterCalculator('("ir@1" - "red@1") / ("ir@1" + "red@1")', lyr_ndvi,
                           'GTiff', ras_red.raster.extent(),
                           ras_red.raster.width(), ras_red.raster.height(),
                           entries)
calc.processCalculation()
print('Executed')
Exemple #26
0
def raster_calc_qgis(ecuacion, raster_inputs, raster_salida):
    n_variables = len(raster_inputs)

    entries = []

    #abre el archivo raster1
    fileInfo = QFileInfo(raster_inputs[0])
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()
    layer1 = QgsRasterLayer(path, baseName)
    var1 = QgsRasterCalculatorEntry()
    var1.ref = 'layer1@1'
    var1.raster = layer1
    var1.bandNumber = 1
    entries.append(var1)

    if n_variables == 2:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)
    elif n_variables == 3:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

    elif n_variables == 4:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

        fileInfo = QFileInfo(raster_inputs[3])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer4 = QgsRasterLayer(path, baseName)
        var4 = QgsRasterCalculatorEntry()
        var4.ref = 'layer4@1'
        var4.raster = layer4
        var4.bandNumber = 1
        entries.append(var4)

    elif n_variables == 5:
        fileInfo = QFileInfo(raster_inputs[1])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer2 = QgsRasterLayer(path, baseName)
        var2 = QgsRasterCalculatorEntry()
        var2.ref = 'layer2@1'
        var2.raster = layer2
        var2.bandNumber = 1
        entries.append(var2)

        fileInfo = QFileInfo(raster_inputs[2])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer3 = QgsRasterLayer(path, baseName)
        var3 = QgsRasterCalculatorEntry()
        var3.ref = 'layer3@1'
        var3.raster = layer3
        var3.bandNumber = 1
        entries.append(var3)

        fileInfo = QFileInfo(raster_inputs[3])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer4 = QgsRasterLayer(path, baseName)
        var4 = QgsRasterCalculatorEntry()
        var4.ref = 'layer4@1'
        var4.raster = layer4
        var4.bandNumber = 1
        entries.append(var4)

        fileInfo = QFileInfo(raster_inputs[4])
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()
        layer5 = QgsRasterLayer(path, baseName)
        var5 = QgsRasterCalculatorEntry()
        var5.ref = 'layer5@1'
        var5.raster = layer5
        var5.bandNumber = 1
        entries.append(var5)

    calc = QgsRasterCalculator(ecuacion, raster_salida,
                               'GTiff', layer1.extent(), layer1.width(),
                               layer1.height(), entries)

    calc.processCalculation()
Exemple #27
0
    def run(self):
        """Run method that performs all the real work"""
        # Add items to Management Practices & Soil Type
        k_lists = []
        m_lists = []

        k_lists = self.k_list()
        m_lists = self.m_list()

        self.dlg.comboBox.addItems(k_lists)
        self.dlg.comboBox_2.addItems(m_lists)

        # show dialog box
        self.dlg.show()

        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:

            # Save paths of input directories
            selectedBoundary = self.dlg.lineEdit.text()
            selectedDEM = self.dlg.lineEdit_2.text()
            selectedRLayer = self.dlg.lineEdit_3.text()

            selectedOutput = self.dlg.lineEdit_4.text()
            for letter in selectedOutput:
                if letter == "\\":
                    selectedOutput = selectedOutput.replace(letter, "/")

            print(selectedBoundary)
            print(selectedDEM)
            print(selectedRLayer)
            print(selectedOutput)

            # Save indices for K and M
            selectedKLayer = self.dlg.comboBox.currentIndex()
            selectedMLayer = self.dlg.comboBox_2.currentIndex()

            boundary = QgsVectorLayer(selectedBoundary, 'Boundary', 'ogr')
            QgsMapLayerRegistry.instance().addMapLayer(boundary)

            entries = []

            # Retrieve K and M values

            k_value = self.k_index(selectedKLayer)
            m_value = self.m_index(selectedMLayer)

            km_value = k_value * m_value
            km_value = str(km_value)

            # Process R index

            ## CSV to Layer
            uri = 'file:///' + selectedRLayer + '?delimiter=%s&xField=%s&yField=%s&crs=%s' % (
                ",", "x", "y", "EPSG:4326")
            rainfall_unedited = QgsVectorLayer(uri, "rainfall",
                                               "delimitedtext")
            QgsMapLayerRegistry.instance().addMapLayer(rainfall_unedited)
            spatRef = QgsCoordinateReferenceSystem(
                4326, QgsCoordinateReferenceSystem.EpsgCrsId)

            ## CSV points to editable shapefile
            rainfall_edited = QgsVectorFileWriter(
                selectedOutput + '/rainfall_edited.shp', None,
                rainfall_unedited.pendingFields(), QGis.WKBPoint, spatRef)

            pt = QgsPoint()
            outFeature = QgsFeature()

            for feat in rainfall_unedited.getFeatures():
                attrs = feat.attributes()
                pt.setX(feat['x'])
                pt.setY(feat['y'])
                outFeature.setAttributes(attrs)
                outFeature.setGeometry(QgsGeometry.fromPoint(pt))
                rainfall_edited.addFeature(outFeature)
            del rainfall_edited

            rainfall_edited2 = QgsVectorLayer(
                selectedOutput + '/rainfall_edited.shp', 'rainfall_edited',
                'ogr')

            ## Add and calculate average field
            rainfall_edited2.startEditing()

            avgField = QgsField('average', QVariant.Double)
            rainfall_edited2.dataProvider().addAttributes([avgField])
            rainfall_edited2.updateFields()
            idx = rainfall_edited2.fieldNameIndex('average')

            time_count = idx - 2
            str_output = ''
            for i in range(1, time_count + 1):
                if i == 1:
                    a = str(i)
                    str_output += 'time' + a

                else:
                    a = str(i)
                    str_output += '+ time' + a

            e = QgsExpression(str_output)
            e.prepare(rainfall_edited2.pendingFields())

            for f in rainfall_edited2.getFeatures():
                f[idx] = e.evaluate(f) / time_count
                rainfall_edited2.updateFeature(f)

            rainfall_edited2.commitChanges()

            rainfall_edited3 = QgsVectorLayer(
                selectedOutput + '/rainfall_edited.shp', 'rainfall_edited',
                'ogr')
            QgsMapLayerRegistry.instance().addMapLayer(rainfall_edited3)

            ## Interpolating average using IDW
            ### Parameters for interpolation
            idx = rainfall_edited3.fieldNameIndex('average')

            layer_data = qgis.analysis.QgsInterpolator.LayerData()
            layer_data.vectorLayer = rainfall_edited3
            layer_data.zCoordInterpolation = False
            layer_data.interpolationAttribute = idx
            layer_data.mInputType = 1

            idw_interpolator = QgsIDWInterpolator([layer_data])

            ### Output parameter
            export_path = selectedOutput + "/interpolated_r_{}.asc".format(idx)
            rect = boundary.extent()
            res = 0.0001
            ncol = (rect.xMaximum() - rect.xMinimum()) / res
            nrows = (rect.yMaximum() - rect.yMinimum()) / res

            interpolated_r = QgsGridFileWriter(idw_interpolator,
                                               export_path, rect, int(ncol),
                                               int(nrows), res, res)
            interpolated_r.writeFile(True)

            interpolated_r2 = QgsRasterLayer(export_path, "interpolated_r")

            ## Clip output to boundary
            clippedR = processing.runandload(
                'gdalogr:cliprasterbymasklayer',
                interpolated_r2,  #INPUT <ParameterRaster>
                boundary,  #MASK <ParameterVector>
                "-9999",  #NO_DATA <ParameterString>
                False,  #ALPHA_BAND <ParameterBoolean>
                False,  #CROP_TO_CUTLINE <ParameterBoolean>
                False,  #KEEP_RESOLUTION <ParameterBoolean>
                5,  #RTYPE <ParameterSelection>
                4,  #COMPRESS <ParameterSelection>
                1,  #JPEGCOMPRESSION <ParameterNumber>
                6,  #ZLEVEL <ParameterNumber>
                1,  #PREDICTOR <ParameterNumber>
                False,  #TILED <ParameterBoolean>
                2,  #BIGTIFF <ParameterSelection>
                False,  #TFW <ParameterBoolean>
                "",  #EXTRA <ParameterString>
                selectedOutput +
                '/clip_interpolated_r.tif')  #OUTPUT <OutputRaster>

            r_layer = QgsRasterLayer(
                selectedOutput + '/clip_interpolated_r.tif', "R-index")
            boh4 = QgsRasterCalculatorEntry()
            boh4.ref = 'boh4@1'
            boh4.raster = r_layer
            boh4.bandNumber = 1
            entries.append(boh4)

            # Process S index
            ## Load DEM

            bohLayer1 = QgsRasterLayer(selectedDEM, "DEM")
            boh2 = QgsRasterCalculatorEntry()
            boh2.ref = 'boh2@1'
            boh2.raster = bohLayer1
            boh2.bandNumber = 1
            entries.append(boh2)

            ## Clip output to boundary
            clippedOutput2 = processing.runandload(
                'gdalogr:cliprasterbymasklayer',
                bohLayer1,  # INPUT <ParameterRaster>
                boundary,  # MASK <ParameterVector>
                "-9999",  # NO_DATA <ParameterString>
                False,  # ALPHA_BAND <ParameterBoolean>
                False,  # CROP_TO_CUTLINE <ParameterBoolean>
                False,  # KEEP_RESOLUTION <ParameterBoolean>
                5,  # RTYPE <ParameterSelection>
                4,  # COMPRESS <ParameterSelection>
                1,  # JPEGCOMPRESSION <ParameterNumber>
                6,  # ZLEVEL <ParameterNumber>
                1,  # PREDICTOR <ParameterNumber>
                False,  # TILED <ParameterBoolean>
                2,  # BIGTIFF <ParameterSelection>
                False,  # TFW <ParameterBoolean>
                "",  # EXTRA <ParameterString>
                selectedOutput + '/clip_dem.tif')  # OUTPUT <OutputRaster>

            bohLayer5 = QgsRasterLayer(selectedOutput + '/clip_dem.tif',
                                       "DEM-clipped")
            boh5 = QgsRasterCalculatorEntry()
            boh5.ref = 'boh5@1'
            boh5.raster = bohLayer5
            boh5.bandNumber = 1
            entries.append(boh5)

            ## GDAL algorithm for slope
            processing.runalg('gdalogr:slope', bohLayer5, 1, False, True, True,
                              111120, selectedOutput + '/slope(percent).tif')

            bohLayer6 = QgsRasterLayer(selectedOutput + '/slope(percent).tif',
                                       "slope(percent)")
            QgsMapLayerRegistry.instance().addMapLayer(bohLayer6)
            boh6 = QgsRasterCalculatorEntry()
            boh6.ref = 'boh6@1'
            boh6.raster = bohLayer6
            boh6.bandNumber = 1
            entries.append(boh6)

            # Process calculation with input extent and resolution
            calc = QgsRasterCalculator('(boh4@1 * boh6@1) *' + km_value,
                                       selectedOutput + '/soil_risk.tif',
                                       'GTiff', bohLayer6.extent(),
                                       bohLayer6.width(), bohLayer6.height(),
                                       entries)

            calc.processCalculation()
            bohLayer4 = QgsRasterLayer(selectedOutput + '/soil_risk.tif',
                                       "Soil_Risk")
            QgsMapLayerRegistry.instance().addMapLayer(bohLayer4)
Exemple #28
0
import qgis
from qgis.analysis import QgsRasterCalculatorEntry, QgsRasterCalculator

lyr_ir11 = 'T31TDF_20191109T104251_B11_20m'
lyr_ir8 = 'T31TDF_20191109T104251_B08_10m'
# Set this path before runing the script
lyr_ndvi = '/home/diego/Documents/maps/Barcelona/images/NDBI_2019_int.tif'

# Set up raster bands as variables
ras_ir11 = QgsRasterCalculatorEntry()
ras_ir8 = QgsRasterCalculatorEntry()
# Set up the references
ras_ir11.ref = 'ir11@1'
ras_ir8.ref = 'ir8@1'
# Set up raster values
ras_ir11.raster = QgsProject.instance().mapLayersByName(lyr_ir11)[0]
ras_ir8.raster = QgsProject.instance().mapLayersByName(lyr_ir8)[0]
# Set up the band to read digital levels
ras_ir11.bandNumber = 1
ras_ir8.bandNumber = 1
# Set entries for the Raster Calculator
entries = []
entries.append(ras_ir11)
entries.append(ras_ir8)
# Set the formula and execute it
calc = QgsRasterCalculator('("ir11@1" - "ir8@1") / ("ir11@1" + "ir8@1") * 100',
                           lyr_ndvi, 'GTiff', ras_ir11.raster.extent(),
                           ras_ir11.raster.width(), ras_ir11.raster.height(),
                           entries)
calc.processCalculation()
print('Executed')
Exemple #29
0
def buildCalculatorEntry(layer):
    raster = QgsRasterCalculatorEntry()
    raster.ref = "{}@1".format(layer.name())
    raster.raster = layer
    raster.bandNumber = 1
    return raster
Exemple #30
0
    def ProcessNBR(self, inFileA, inFileB):
        msg = u"NBR Processing for " + self.sceneID + "..."
        iface.mainWindow().statusBar().showMessage(msg)
        QgsMessageLog.logMessage(msg, level=QgsMessageLog.INFO)
        try:
            calculatorEntryList = []
            tempOutFile = self.outFileNBR.replace("NBR", "NBR_temp")

            fileInfo1 = QFileInfo(inFileA)
            baseName1 = fileInfo1.baseName()
            newLayer1 = QgsRasterLayer(inFileA, baseName1)
            boh1 = QgsRasterCalculatorEntry()
            boh1.ref = "boh@1"
            boh1.bandNumber = 1
            calculatorEntryList.append(boh1)
            boh1.raster = newLayer1

            if newLayer1.isValid():
                extents = newLayer1.extent()
                colCt = newLayer1.width()
                rowCt = newLayer1.height()
            else:
                raise IOError(u"Error, Invalid layer read!")

            fileInfo2 = QFileInfo(inFileB)
            baseName2 = fileInfo2.baseName()
            newLayer2 = QgsRasterLayer(inFileB, baseName2)
            boh2 = QgsRasterCalculatorEntry()
            boh2.ref = "boh@2"
            boh2.bandNumber = 1
            calculatorEntryList.append(boh2)
            boh2.raster = newLayer2
            if not newLayer2.isValid():
                raise IOError(u"Error, Invalid layer read!")

            formula = ("(((boh@1 != 0 AND boh@2 != 0) * "
                       "(boh@1 - boh@2) / (boh@1 + boh@2) * 1000) + "
                       "((boh@1 = 0 OR boh@2 = 0) * " + str(self.minShort) +
                       "))")

            # Process calculation with input extent and resolution
            calc = QgsRasterCalculator(formula, tempOutFile, 'GTiff', extents,
                                       colCt, rowCt, calculatorEntryList)

            result = calc.processCalculation()

            if result != 0:
                raise RuntimeError(u"Raster calculator failed.")

            # convert Raster Calculator result to int 16
            self.Float2IntTif(tempOutFile, self.outFileNBR)
        except:
            raise RuntimeError(u"Unspecified error when calculating NBR")
        finally:
            # cleanup
            calculatorEntryList = None
            fileInfo1 = None
            baseName1 = None
            fileInfo2 = None
            baseName2 = None
            formula = None
            boh1 = None
            boh2 = None
            calc = None
            newLayer1 = None
            newLayer2 = None

            del calculatorEntryList
            del fileInfo1
            del baseName1
            del fileInfo2
            del baseName2
            del formula
            del boh1
            del boh2
            del calc
            del newLayer1
            del newLayer2
        gc.collect()

        msg = u"NBR Processing for " + self.sceneID + " Completed"
        iface.mainWindow().statusBar().showMessage(msg)
        QgsMessageLog.logMessage(msg, level=QgsMessageLog.INFO)
        iface.mainWindow().statusBar().showMessage("")
        return result
Exemple #31
0
    def processAlgorithm(self, feedback):
        expression = self.getParameterValue(self.EXPRESSION)
        layersValue = self.getParameterValue(self.LAYERS)
        layersDict = {}
        if layersValue:
            layers = [
                dataobjects.getLayerFromString(f)
                for f in layersValue.split(";")
            ]
            layersDict = {
                os.path.basename(lyr.source().split(".")[0]): lyr
                for lyr in layers
            }

        for lyr in QgsProcessingUtils.compatibleRasterLayers(
                QgsProject.instance()):
            name = lyr.name()
            if (name + "@") in expression:
                layersDict[name] = lyr

        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                entry = QgsRasterCalculatorEntry()
                entry.ref = '{:s}@{:d}'.format(name, n + 1)
                entry.raster = lyr
                entry.bandNumber = n + 1
                entries.append(entry)

        output = self.getOutputValue(self.OUTPUT)
        extentValue = self.getParameterValue(self.EXTENT)

        if extentValue:
            extent = extentValue.split(',')
            bbox = QgsRectangle(float(extent[0]), float(extent[2]),
                                float(extent[1]), float(extent[3]))
        else:
            if layersDict:
                bbox = list(layersDict.values())[0].extent()
                for lyr in layersDict.values():
                    bbox.combineExtentWith(lyr.extent())
            else:
                raise GeoAlgorithmExecutionException(
                    self.tr("No layers selected"))

        def _cellsize(layer):
            return (layer.extent().xMaximum() -
                    layer.extent().xMinimum()) / layer.width()

        cellsize = self.getParameterValue(self.CELLSIZE) or min(
            [_cellsize(lyr) for lyr in layersDict.values()])
        width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)
        calc = QgsRasterCalculator(expression, output, driverName, bbox, width,
                                   height, entries)

        res = calc.processCalculation()
        if res == QgsRasterCalculator.ParserError:
            raise GeoAlgorithmExecutionException(
                self.tr("Error parsing formula"))
Exemple #32
0
##inImage_red=raster
##inImage_nir=raster
##outImage=output raster

from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

lyr = processing.getObject(inImage_red)
entries=[]
rasterCalcEntry=QgsRasterCalculatorEntry()
rasterCalcEntry.ref='R@1'
rasterCalcEntry.raster=lyr
rasterCalcEntry.bandNumber=1
entries.append(rasterCalcEntry)

lyr = processing.getObject(inImage_nir)
rasterCalcEntry=QgsRasterCalculatorEntry()
rasterCalcEntry.ref='NIR@1'
rasterCalcEntry.raster=lyr
rasterCalcEntry.bandNumber=1
entries.append(rasterCalcEntry)

if not ".tif" in outImage:
    outImage=outImage+".tif"

noData=-3.4028234663852886e+38
calc=QgsRasterCalculator('1.0*(NIR@1 - R@1)/(NIR@1 + R@1)+0.0', outImage, "GTiff",  lyr.extent(), lyr.crs(), lyr.width(), lyr.height(), entries)
calc.processCalculation()
def defineentry(layer): #function to attach a layer to an entry
    a = QgsRasterCalculatorEntry()
    a.ref = layer.name() + '@1'
    a.raster = layer
    a.bandNumber = 1
    return a
def StringToRaster(raster):
    # Check if string is provided

    fileInfo = QFileInfo(raster)
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()

    layer = QgsRasterLayer(path, baseName)
    #QgsMapLayerRegistry.instance().addMapLayer(layer)

    entries = []
    # Define band1
    boh1 = QgsRasterCalculatorEntry()
    boh1.ref = 'ndvi20160607sentinel@5'
    boh1.raster = layer
    boh1.bandNumber = 5
    entries.append(boh1)

    # Process calculation with input extent and resolution
    calc = QgsRasterCalculator(
        '(ndvi20160607sentinel@5) * 166.67 + 111.67',
        'C:/Hackathon Farmhack data/Output/outputfile.tif', 'GTiff',
        layer.extent(), layer.width(), layer.height(), entries)
    calc.processCalculation()

    fileInfo = QFileInfo('C:/Hackathon Farmhack data/Output/outputfile.tif')
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()

    layer = QgsRasterLayer(path, baseName)
    #QgsMapLayerRegistry.instance().addMapLayer(layer)

    if layer.isValid() is True:
        print "Layer was loaded successfully!"

    else:
        print "Unable to read basename and file path - Your string is probably invalid"

    shape = QgsVectorLayer(
        'C:/Hackathon Farmhack data/perceel-hier-rdnew.geojson', 'perceel',
        'ogr')
    #QgsMapLayerRegistry.instance().addMapLayer(shape)
    xmin = (shape.extent().xMinimum()
            )  #extract the minimum x coord from our layer
    xmax = (shape.extent().xMaximum()
            )  #extract our maximum x coord from our layer
    ymin = (shape.extent().yMinimum()
            )  #extract our minimum y coord from our layer
    ymax = (shape.extent().yMaximum()
            )  #extract our maximum y coord from our layer
    #prepare the extent in a format the VectorGrid tool can interpret (xmin,xmax,ymin,ymax)
    extent = str(xmin) + ',' + str(xmax) + ',' + str(ymin) + ',' + str(ymax)

    # raster the given shape
    processing.runalg(
        'qgis:vectorgrid', extent, 20, 20, 0,
        'C:/Hackathon Farmhack data/Output/rasterShapes.geojson')

    shapeRaster = QgsVectorLayer(
        'C:/Hackathon Farmhack data/Output/rasterShapes.geojson',
        'perceelRaster', 'ogr')
    shapeRaster.setCrs(
        QgsCoordinateReferenceSystem(28992,
                                     QgsCoordinateReferenceSystem.EpsgCrsId))
    #QgsMapLayerRegistry.instance().addMapLayer(shapeRaster)

    #clip the raster returned
    processing.runalg('qgis:clip', shapeRaster, shape,
                      'C:/Hackathon Farmhack data/Output/clippedRaster.shp')

    #define oldPath and newPath
    ogr2ogr.main([
        "", "-f", "ESRI Shapefile", "-s_srs", "epsg:28992", "-t_srs",
        "epsg:32632", "C:/Hackathon Farmhack data/Output/clippedRasterNew.shp",
        "C:/Hackathon Farmhack data/Output/clippedRaster.shp"
    ])

    clippedRaster = QgsVectorLayer(
        'C:/Hackathon Farmhack data/Output/clippedRasterNew.shp',
        'clippedRaster', 'ogr')
    clippedRaster.setCrs(
        QgsCoordinateReferenceSystem(32632,
                                     QgsCoordinateReferenceSystem.EpsgCrsId))
    #QgsMapLayerRegistry.instance().addMapLayer(clippedRaster)

    #zonalstatistics
    processing.runalg(
        'qgis:zonalstatistics', layer, 1, clippedRaster, '', False,
        'C:/Hackathon Farmhack data/Output/filledRaster.geojson')
    filledRaster = QgsVectorLayer(
        'C:/Hackathon Farmhack data/Output/filledRaster.geojson',
        'filledRaster', 'ogr')
    filledRaster.setCrs(
        QgsCoordinateReferenceSystem(32632,
                                     QgsCoordinateReferenceSystem.EpsgCrsId))
    #QgsMapLayerRegistry.instance().addMapLayer(filledRaster)

    ogr2ogr.main([
        "", "-f", "GeoJSON", "-s_srs", "epsg:32632", "-t_srs", "epsg:4326",
        "C:/Hackathon Farmhack data/Output/taakkaart.geojson",
        "C:/Hackathon Farmhack data/Output/filledRaster.geojson"
    ])
    taakkaart = QgsVectorLayer(
        'C:/Hackathon Farmhack data/Output/taakkaart.geojson', 'taakkaart',
        'ogr')
    QgsMapLayerRegistry.instance().addMapLayer(taakkaart)
Exemple #35
0
    def processAlgorithm(self, parameters, context, feedback):
        expression = self.parameterAsString(parameters, self.EXPRESSION,
                                            context)
        layers = self.parameterAsLayerList(parameters, self.LAYERS, context)

        layersDict = {}
        if layers:
            layersDict = {
                os.path.basename(lyr.source().split(".")[0]): lyr
                for lyr in layers
            }

        crs = self.parameterAsCrs(parameters, self.CRS, context)
        if not layers and not crs.isValid():
            raise QgsProcessingException(
                self.tr("No reference layer selected nor CRS provided"))

        if not crs.isValid() and layers:
            crs = list(layersDict.values())[0].crs()

        bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
        if not layers and bbox.isNull():
            raise QgsProcessingException(
                self.tr("No reference layer selected nor extent box provided"))

        if not bbox.isNull():
            bboxCrs = self.parameterAsExtentCrs(parameters, self.EXTENT,
                                                context)
            if bboxCrs != crs:
                transform = QgsCoordinateTransform(bboxCrs, crs,
                                                   context.project())
                bbox = transform.transformBoundingBox(bbox)

        if bbox.isNull() and layers:
            bbox = QgsProcessingUtils.combineLayerExtents(layers, crs)

        cellsize = self.parameterAsDouble(parameters, self.CELLSIZE, context)
        if not layers and cellsize == 0:
            raise QgsProcessingException(
                self.tr(
                    "No reference layer selected nor cellsize value provided"))

        def _cellsize(layer):
            ext = layer.extent()
            if layer.crs() != crs:
                transform = QgsCoordinateTransform(layer.crs(), crs,
                                                   context.project())
                ext = transform.transformBoundingBox(ext)
            return (ext.xMaximum() - ext.xMinimum()) / layer.width()

        if cellsize == 0:
            cellsize = min([_cellsize(lyr) for lyr in layersDict.values()])

        for lyr in QgsProcessingUtils.compatibleRasterLayers(
                context.project()):
            name = lyr.name()
            if (name + "@") in expression:
                layersDict[name] = lyr

        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                ref = '{:s}@{:d}'.format(name, n + 1)
                if ref in expression:
                    entry = QgsRasterCalculatorEntry()
                    entry.ref = ref
                    entry.raster = lyr
                    entry.bandNumber = n + 1
                    entries.append(entry)

        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)
        calc = QgsRasterCalculator(expression, output, driverName, bbox, crs,
                                   width, height, entries)

        res = calc.processCalculation(feedback)
        if res == QgsRasterCalculator.ParserError:
            raise QgsProcessingException(self.tr("Error parsing formula"))

        return {self.OUTPUT: output}
def computeMaskThreshold(dlg, conf, dir_raster_treat, dir_dest,
                         rasterTreatName, rasterSeuilName, seuilStr, deltaStr,
                         extension_input_raster):

    # Calcul du masque d'eau fonction du seuil choisi
    seuil = float(seuilStr)
    if not dlg.rbSeuil.isChecked():
        delta = 0
        values_seuil_list = [0]
    else:
        delta = float(deltaStr)
        values_seuil_list = [-1, 0, +1]

    messInfo(dlg, "Seuil: " + seuilStr)
    messInfo(dlg, "")

    if dlg.rbComputeNdvi.isChecked():
        direction = True
    elif dlg.rbComputeNdwi2.isChecked():
        direction = False
    else:
        direction = True

    if direction:
        direction_operator_str = "<"  # Operateur inferieur
    else:
        direction_operator_str = ">"  # Operateur superieur

    if conf.rbOTB.isChecked():
        # Calculatrice OTB
        init = 41253
    else:
        # Calculatrice QGIS
        init = 32526

    masks_list = []
    for i in values_seuil_list:
        newSeuil = seuil + i * delta

        if float(newSeuil) == 0:
            newSeuilStr = '0'
            newSeuil10Str = '0'
        else:
            newSeuilStr = str(newSeuil)
            newSeuil10Str = str(newSeuil * 10)
            while newSeuilStr[0] == '0' and len(
                    newSeuilStr) >= 2 and newSeuilStr[1] != '.':
                newSeuilStr = newSeuilStr[1:]
            if '.' in newSeuilStr:
                while newSeuilStr[-1] == '0':
                    newSeuilStr = newSeuilStr[:len(newSeuilStr) - 1]
                if newSeuilStr[-1] == '.':
                    newSeuilStr = newSeuilStr[:len(newSeuilStr) - 1]

        if newSeuil != init:
            init = newSeuil

            if delta == 0:
                layerSeuilName = rasterSeuilName + seuilStr
            else:
                layerSeuilName = rasterSeuilName + newSeuilStr

            layerSeuilPath = dir_dest + os.sep + layerSeuilName + EXT_RASTER

            if os.path.exists(layerSeuilPath):
                try:
                    os.remove(layerSeuilPath)
                except:
                    QMessageBox.information(
                        None, "Attention !!!", layerSeuilPath +
                        " ne peut pas être effacé. Vérifiez que le fichier n'est pas verrouillé par un autre utilisateur ou que le fichier peut être effacé manuellement (droits d'écriture sur le répertoire).",
                        QMessageBox.Ok, QMessageBox.NoButton)
                    messErreur(dlg,
                               layerSeuilPath + " ne peut pas être effacé.")
                    return None

            messInfo(dlg,
                     "Calcul du masque 'Eau' avec le seuil: " + newSeuilStr)
            messInfo(dlg, "")

            # Calculatrice OTB
            if conf.rbOTB.isChecked():
                rasterTreatPath = dir_raster_treat + os.sep + rasterTreatName + extension_input_raster
                try:
                    expression = 'im1b1' + direction_operator_str + newSeuilStr + '?1:2'
                    #processing.algorithmHelp("otb:BandMath")
                    #processing.runalg('otb:bandmath', rasterTreatPath, '128',expression ,layerSeuilPath)
                    parameters = {
                        "il": [rasterTreatPath],
                        "out": layerSeuilPath,
                        "exp": expression,
                        "outputpixeltype": 0
                    }
                    processing.run('otb:BandMath', parameters)
                except:
                    messErreur(
                        dlg,
                        "Erreur lors du lancement de otb:BandMath seuillage.")
                    return None
            # Fin OTB

            # Calculatrice QGIS
            else:
                entries = []
                li = layerList()
                raster = li[rasterTreatName]
                extent = raster.extent()
                height = raster.height()
                width = raster.width()

                s1 = QgsRasterCalculatorEntry()
                s1.ref = 's@1'
                s1.raster = raster
                s1.bandNumber = 1
                entries.append(s1)

                if platform.system() == "Linux":
                    # Bug calculatrice raster sous linux
                    calc = QgsRasterCalculator(
                        '(10*s@1' + direction_operator_str + newSeuil10Str +
                        ')', layerSeuilPath, FORMAT_IMA, extent, width, height,
                        entries)

                else:
                    calc = QgsRasterCalculator(
                        '(s@1' + direction_operator_str + newSeuilStr + ')',
                        layerSeuilPath, FORMAT_IMA, extent, width, height,
                        entries)

                ret = calc.processCalculation()
                if ret != 0:
                    QMessageBox.information(
                        None, "Attention !!!",
                        " Erreur d'exécution, cela peut être du à une insuffisance mémoire, image trop volumineuse.",
                        QMessageBox.Ok, QMessageBox.NoButton)
                    messErreur(
                        dlg, "Erreur de traitement sur QgsRasterCalculator.")
                    return None
            # Fin QGIS

            if os.path.exists(layerSeuilPath):
                mask = QgsRasterLayer(layerSeuilPath, layerSeuilName)
            else:
                QMessageBox.information(
                    None, "Attention !!!", layerSeuilPath +
                    " n'a pas été créé. Vérifiez que le fichier n'est pas verrouillé par un autre utilisateur ou que le fichier peut être effacé manuellement (droits d'écriture sur le répertoire).",
                    QMessageBox.Ok, QMessageBox.NoButton)
                messErreur(dlg, layerSeuilPath + " n'a pas été créé.")
                return None

            if not mask.isValid():
                messErreur(dlg, layerSeuilPath + " ne peut pas être chargé.")
                return None

            # Add list pour return
            masks_list.append(mask)

    return masks_list
Exemple #37
0
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """

        # Retrieve the feature source and sink. The 'dest_id' variable is used
        # to uniquely identify the feature sink, and must be included in the
        # dictionary returned by the processAlgorithm function.
        rasterInputLst = self.parameterAsLayerList(parameters, self.INPUT_1,
                                                   context)

        gammaVal = self.parameterAsDouble(parameters, self.INPUT_GAMMA,
                                          context)

        feedback.pushInfo('Gamma val: ' + str(gammaVal))

        outputFile = self.parameterAsOutputLayer(parameters, self.OUTPUT,
                                                 context)
        feedback.pushInfo('Output File: ' + outputFile)

        #Loop for calculation
        rEntriesLst = []
        cont = 1
        fsum = '1 - ('
        fMultiply = ''

        for r in rasterInputLst:
            rCalcEntry = QgsRasterCalculatorEntry()
            rRefName = 'r%s@1' % (str(cont))
            rCalcEntry.ref = rRefName
            feedback.pushInfo(rCalcEntry.ref)
            rCalcEntry.raster = r
            rEntriesLst.append(rCalcEntry)
            feedback.pushInfo('Raster n: %s' % (rRefName))

            if cont != 1: fsum = fsum + '* ( 1 - %s )' % rRefName
            else: fsum = fsum + '( 1 - %s )' % rRefName

            if cont != 1: fMultiply = fMultiply + ' * ' + rRefName
            else: fMultiply = rRefName

            cont += 1

        fsum = fsum + ')'
        feedback.pushInfo(fsum)
        feedback.pushInfo(fMultiply)

        formula = '((' + fsum + ') ^ ' + str(
            gammaVal) + ') *  ((' + fMultiply + ') ^ ( 1 - ' + str(
                gammaVal) + '))'
        feedback.pushInfo('Formula: ' + str(formula))

        rasterInput1 = rasterInputLst[0]
        calc = QgsRasterCalculator(formula, outputFile, 'GTiff',
                                   rasterInput1.extent(), rasterInput1.width(),
                                   rasterInput1.height(), rEntriesLst)

        feedback.pushInfo("Doing calculation")
        calc.processCalculation()
        feedback.pushInfo("Calculation finished")

        return {self.OUTPUT: outputFile}
Exemple #38
0
from qgis.core import *
from qgis.utils import iface
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

# Define Output file name
output_path = OUT + "/"
suffix = "_CWSI1.tif"

# Get layer object
bohLayer = processing.getObject(temp)

entries = []
# Define band1
boh1 = QgsRasterCalculatorEntry()
boh1.ref = 'boh@1'
boh1.raster = bohLayer
boh1.bandNumber = 1
entries.append( boh1 )

# Calculate CWSI1
#Tair = 20
Twet = Tcmin
Tdry = Tair + 5
Trange = Tdry - Twet
#formula = 'boh@1' + '+' + str(Tair)
'''CWSI = (Tc-Twet)/(Tdry-Twet) # using assumptions form.xyz.'''
formula = '(boh@1' + '-' + str(Twet) + ')/' + str(Trange)

calc = QgsRasterCalculator( formula, output_path + bohLayer.name() + suffix, 'GTiff', bohLayer.extent(), bohLayer.width(), bohLayer.height(), entries )
calc.processCalculation()
def StringToRaster(raster):
    # Check if string is provided

    fileInfo = QFileInfo(raster)
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()

    layer = QgsRasterLayer(path, baseName)
    #QgsMapLayerRegistry.instance().addMapLayer(layer)
    
    entries = []
    # Define band1
    boh1 = QgsRasterCalculatorEntry()
    boh1.ref = 'ndvi20160607sentinel@5'
    boh1.raster = layer
    boh1.bandNumber = 5
    entries.append( boh1 )
    	
    # Process calculation with input extent and resolution
    calc = QgsRasterCalculator( '(ndvi20160607sentinel@5) * 166.67 + 111.67', 'C:/Hackathon Farmhack data/Output/outputfile.tif', 'GTiff', layer.extent(), layer.width(), layer.height(), entries )
    calc.processCalculation()
    
    fileInfo = QFileInfo('C:/Hackathon Farmhack data/Output/outputfile.tif')
    path = fileInfo.filePath()
    baseName = fileInfo.baseName()
    
    layer = QgsRasterLayer(path, baseName)
    #QgsMapLayerRegistry.instance().addMapLayer(layer)
    
    if layer.isValid() is True:
        print "Layer was loaded successfully!"
    
    else:
        print "Unable to read basename and file path - Your string is probably invalid"
    
    shape = QgsVectorLayer('C:/Hackathon Farmhack data/perceel-hier-rdnew.geojson', 'perceel', 'ogr')
    #QgsMapLayerRegistry.instance().addMapLayer(shape)
    xmin = (shape.extent().xMinimum()) #extract the minimum x coord from our layer
    xmax = (shape.extent().xMaximum()) #extract our maximum x coord from our layer
    ymin = (shape.extent().yMinimum()) #extract our minimum y coord from our layer
    ymax = (shape.extent().yMaximum()) #extract our maximum y coord from our layer
    #prepare the extent in a format the VectorGrid tool can interpret (xmin,xmax,ymin,ymax)
    extent = str(xmin)+ ',' + str(xmax)+ ',' +str(ymin)+ ',' +str(ymax)  
    
    # raster the given shape
    processing.runalg('qgis:vectorgrid', extent, 20, 20, 0, 'C:/Hackathon Farmhack data/Output/rasterShapes.geojson')
    
    shapeRaster = QgsVectorLayer('C:/Hackathon Farmhack data/Output/rasterShapes.geojson', 'perceelRaster', 'ogr')
    shapeRaster.setCrs(QgsCoordinateReferenceSystem(28992,  QgsCoordinateReferenceSystem.EpsgCrsId))
    #QgsMapLayerRegistry.instance().addMapLayer(shapeRaster)
    
    #clip the raster returned
    processing.runalg('qgis:clip', shapeRaster, shape, 'C:/Hackathon Farmhack data/Output/clippedRaster.shp')

    #define oldPath and newPath
    ogr2ogr.main(["","-f", "ESRI Shapefile", "-s_srs", "epsg:28992", "-t_srs", "epsg:32632", "C:/Hackathon Farmhack data/Output/clippedRasterNew.shp", "C:/Hackathon Farmhack data/Output/clippedRaster.shp"])
    
    clippedRaster = QgsVectorLayer('C:/Hackathon Farmhack data/Output/clippedRasterNew.shp', 'clippedRaster', 'ogr')
    clippedRaster.setCrs(QgsCoordinateReferenceSystem(32632,  QgsCoordinateReferenceSystem.EpsgCrsId))
    #QgsMapLayerRegistry.instance().addMapLayer(clippedRaster)
    
    #zonalstatistics
    processing.runalg('qgis:zonalstatistics', layer, 1, clippedRaster, '', False, 'C:/Hackathon Farmhack data/Output/filledRaster.geojson')
    filledRaster = QgsVectorLayer('C:/Hackathon Farmhack data/Output/filledRaster.geojson', 'filledRaster', 'ogr')
    filledRaster.setCrs(QgsCoordinateReferenceSystem(32632,  QgsCoordinateReferenceSystem.EpsgCrsId))
    #QgsMapLayerRegistry.instance().addMapLayer(filledRaster)    
	
    ogr2ogr.main(["","-f", "GeoJSON", "-s_srs", "epsg:32632", "-t_srs", "epsg:4326", "C:/Hackathon Farmhack data/Output/taakkaart.geojson", "C:/Hackathon Farmhack data/Output/filledRaster.geojson"])
    taakkaart = QgsVectorLayer('C:/Hackathon Farmhack data/Output/taakkaart.geojson', 'taakkaart', 'ogr')
    QgsMapLayerRegistry.instance().addMapLayer(taakkaart)    
Exemple #40
0
import qgis
from qgis.analysis import QgsRasterCalculatorEntry, QgsRasterCalculator

ndvi_before = 'NDVI_2015_int'
ndvi_after = 'NDVI_2019_int'
# Set this path before runing the script
lyr_dif = '/home/diego/Documents/maps/Barcelona/images/NDVI_19_vs_15.tif'

# Set up raster bands as variables
ndvi_b = QgsRasterCalculatorEntry()
ndvi_a = QgsRasterCalculatorEntry()
# Set up the references
ndvi_b.ref = 'bef@1'
ndvi_a.ref = 'aft@1'
# Set up raster values
ndvi_b.raster = QgsProject.instance().mapLayersByName(ndvi_before)[0]
ndvi_a.raster = QgsProject.instance().mapLayersByName(ndvi_after)[0]
# Set up the band to read digital levels
ndvi_b.bandNumber = 1
ndvi_a.bandNumber = 1
# Set entries for the Raster Calculator
entries = []
entries.append(ndvi_b)
entries.append(ndvi_a)
# Set the formula and execute it
calc = QgsRasterCalculator('"aft@1" - "bef@1"', lyr_dif, 'GTiff',
                           ndvi_a.raster.extent(), ndvi_a.raster.width(),
                           ndvi_a.raster.height(), entries)
calc.processCalculation()
print('Executed')
    def processAlgorithm(self, parameters, context, feedback):
        expression = self.parameterAsString(parameters, self.EXPRESSION, context)
        layers = self.parameterAsLayerList(parameters, self.LAYERS, context)

        layersDict = {}
        if layers:
            layersDict = {os.path.basename(lyr.source().split(".")[0]): lyr for lyr in layers}

        crs = self.parameterAsCrs(parameters, self.CRS, context)
        if not layers and not crs.isValid():
            raise QgsProcessingException(self.tr("No reference layer selected nor CRS provided"))

        if not crs.isValid() and layers:
            crs = list(layersDict.values())[0].crs()

        bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
        if not layers and bbox.isNull():
            raise QgsProcessingException(self.tr("No reference layer selected nor extent box provided"))

        if not bbox.isNull():
            bboxCrs = self.parameterAsExtentCrs(parameters, self.EXTENT, context)
            if bboxCrs != crs:
                transform = QgsCoordinateTransform(bboxCrs, crs, context.project())
                bbox = transform.transformBoundingBox(bbox)

        if bbox.isNull() and layers:
            bbox = QgsProcessingUtils.combineLayerExtents(layers, crs)

        cellsize = self.parameterAsDouble(parameters, self.CELLSIZE, context)
        if not layers and cellsize == 0:
            raise QgsProcessingException(self.tr("No reference layer selected nor cellsize value provided"))

        def _cellsize(layer):
            ext = layer.extent()
            if layer.crs() != crs:
                transform = QgsCoordinateTransform(layer.crs(), crs, context.project())
                ext = transform.transformBoundingBox(ext)
            return (ext.xMaximum() - ext.xMinimum()) / layer.width()
        if cellsize == 0:
            cellsize = min([_cellsize(lyr) for lyr in layersDict.values()])

        for lyr in QgsProcessingUtils.compatibleRasterLayers(context.project()):
            name = lyr.name()
            if (name + "@") in expression:
                layersDict[name] = lyr

        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                ref = '{:s}@{:d}'.format(name, n + 1)
                if ref in expression:
                    entry = QgsRasterCalculatorEntry()
                    entry.ref = ref
                    entry.raster = lyr
                    entry.bandNumber = n + 1
                    entries.append(entry)

        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)
        calc = QgsRasterCalculator(expression,
                                   output,
                                   driverName,
                                   bbox,
                                   crs,
                                   width,
                                   height,
                                   entries)

        res = calc.processCalculation(feedback)
        if res == QgsRasterCalculator.ParserError:
            raise QgsProcessingException(self.tr("Error parsing formula"))

        return {self.OUTPUT: output}
def computeNdvi(dlg, conf, dir_raster_src, dir_dest, rasterName, ndviName,
                extension_input_raster):

    # Calcul despeckele indice Ndvi
    li = layerList()

    messInfo(dlg, "Calcul du NDVI.")
    messInfo(dlg, "")

    rasterPath = dir_raster_src + os.sep + rasterName + extension_input_raster
    ndviPath = dir_dest + os.sep + ndviName + EXT_RASTER

    # Test si c'est une image multibande
    cols, rows, bands = getGeometryImage(rasterPath)
    if bands < 4:
        QMessageBox.information(
            None, "Attention !!!", ndviPath +
            " ne peut pas être créé. L'image raster d'entrée n'a pas un nombre de bande suffisant.",
            QMessageBox.Ok, QMessageBox.NoButton)
        messErreur(dlg, ndviPath + " ne peut pas être créé.")
        return None

    # Selection des bandes pour le calcul du NDVI
    num_channel_red = 0
    num_channel_nir = 0
    d = conf.channelOrderDic
    key = "Red"
    if key in conf.channelOrderDic.keys():
        num_channel_red = int(conf.channelOrderDic[key])
    key = "NIR"
    if key in conf.channelOrderDic.keys():
        num_channel_nir = int(conf.channelOrderDic[key])

    if (num_channel_red == 0 or num_channel_nir == 0):
        QMessageBox.information(
            None, "Attention !!!", ndviPath +
            " ne peut pas être créé. NDVI needs Red and NIR channels to be computed).",
            QMessageBox.Ok, QMessageBox.NoButton)
        messErreur(dlg, ndviPath + " ne peut pas être créé.")
        return None

    # Suppression du fichier de sortie si il existe
    if os.path.exists(ndviPath):
        try:
            os.remove(ndviPath)
        except:
            QMessageBox.information(
                None, "Attention !!!", ndviPath +
                " ne peut pas être effacé. Vérifiez que le fichier n'est pas verrouillé par un autre utilisateur ou que le fichier peut être effacé manuellement (droits d'écriture sur le répertoire).",
                QMessageBox.Ok, QMessageBox.NoButton)
            messErreur(dlg, ndviPath + " ne peut pas être effacé.")
            return None

    # Calcul
    if conf.rbOTB.isChecked():
        # Calculatrice raster OTB
        try:
            expression = '(im1b%s - im1b%s)/(im1b%s + im1b%s)' % (
                str(num_channel_nir), str(num_channel_red),
                str(num_channel_nir), str(num_channel_red))
            #processing.algorithmHelp("otb:BandMath")
            #processing.runalg('otb:bandmath', rasterPath, '128',expression, ndviPath)
            parameters = {
                "il": [rasterPath],
                "out": ndviPath,
                "exp": expression,
                "outputpixeltype": 5
            }
            processing.run('otb:BandMath', parameters)
        except:
            messErreur(dlg, "Erreur de traitement sur otb:BandMath ndvi.")
            return None
        # Fin OTB

    else:
        # Calculatrice raster QGIS
        entries = []

        raster = li[rasterName]
        extent = raster.extent()
        height = raster.height()
        width = raster.width()

        b_red = QgsRasterCalculatorEntry()
        b_red.ref = 'b@%s' % (str(num_channel_red))
        b_red.raster = raster
        b_red.bandNumber = num_channel_red
        entries.append(b_red)

        b_nir = QgsRasterCalculatorEntry()
        b_nir.ref = 'b@%s' % (str(num_channel_nir))
        b_nir.raster = raster
        b_nir.bandNumber = num_channel_nir
        entries.append(b_nir)

        expression = '(b@%s - b@%s)/(b@%s + b@%s)' % (
            str(num_channel_nir), str(num_channel_red), str(num_channel_nir),
            str(num_channel_red))
        calc = QgsRasterCalculator(expression, ndviPath, FORMAT_IMA, extent,
                                   width, height, entries)

        ret = calc.processCalculation()

        if ret != 0:
            QMessageBox.information(
                None, "Attention !!!",
                " Erreur d'exécution, cela peut être du à une insuffisance mémoire, image trop volumineuse.",
                QMessageBox.Ok, QMessageBox.NoButton)
            messErreur(dlg, "Erreur lors du lancement de QgsRasterCalculator.")
            return None
        # Fin QGIS

    if os.path.exists(ndviPath):
        ndvi = QgsRasterLayer(ndviPath, ndviName)
    else:
        QMessageBox.information(
            None, "Attention !!!", ndviPath +
            " n'a pas été créé. Vérifiez que le fichier n'est pas verrouillé par un autre utilisateur ou que le fichier peut être effacé manuellement (droits d'écriture sur le répertoire).",
            QMessageBox.Ok, QMessageBox.NoButton)
        messErreur(dlg, ndviPath + " n'a pas été créé.")
        return None

    if not ndvi.isValid():
        messErreur(dlg, ndviPath + " ne peut pas être chargé.")
        return None

    return ndvi
Exemple #43
0
    def processAlgorithm(self, parameters, context, feedback):
        expression = self.parameterAsString(parameters, self.EXPRESSION, context)
        layers = self.parameterAsLayerList(parameters, self.LAYERS, context)

        layersDict = {}
        if layers:
            layersDict = {lyr.source(): lyr for lyr in layers}

        crs = self.parameterAsCrs(parameters, self.CRS, context)
        if crs is None or not crs.isValid():
            if not layers:
                raise QgsProcessingException(self.tr("No reference layer selected nor CRS provided"))
            else:
                crs = list(layersDict.values())[0].crs()

        bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
        if bbox.isNull() and not layers:
            raise QgsProcessingException(self.tr("No reference layer selected nor extent box provided"))

        if not bbox.isNull():
            bboxCrs = self.parameterAsExtentCrs(parameters, self.EXTENT, context)
            if bboxCrs != crs:
                transform = QgsCoordinateTransform(bboxCrs, crs, context.project())
                bbox = transform.transformBoundingBox(bbox)

        if bbox.isNull() and layers:
            bbox = QgsProcessingUtils.combineLayerExtents(layers, crs, context)

        cellsize = self.parameterAsDouble(parameters, self.CELLSIZE, context)
        if cellsize == 0 and not layers:
            raise QgsProcessingException(self.tr("No reference layer selected nor cellsize value provided"))

        def _cellsize(layer):
            ext = layer.extent()
            if layer.crs() != crs:
                transform = QgsCoordinateTransform(layer.crs(), crs, context.project())
                ext = transform.transformBoundingBox(ext)
            return (ext.xMaximum() - ext.xMinimum()) / layer.width()
        if cellsize == 0:
            cellsize = min([_cellsize(lyr) for lyr in layersDict.values()])

        # check for layers available in the model
        layersDictCopy = layersDict.copy() # need a shallow copy because next calls invalidate iterator
        for lyr in layersDictCopy.values():
            expression = self.mappedNameToLayer(lyr, expression, layersDict, context)

        # check for layers available in the project
        for lyr in QgsProcessingUtils.compatibleRasterLayers(context.project()):
            expression = self.mappedNameToLayer(lyr, expression, layersDict, context)

        # create the list of layers to be passed as inputs to RasterCalculaltor
        # at this phase expression has been modified to match available layers
        # in the current scope
        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                ref = '{:s}@{:d}'.format(name, n + 1)

                if ref in expression:
                    entry = QgsRasterCalculatorEntry()
                    entry.ref = ref
                    entry.raster = lyr
                    entry.bandNumber = n + 1
                    entries.append(entry)

        # Append any missing entry from the current project
        for entry in QgsRasterCalculatorEntry.rasterEntries():
            if not [e for e in entries if e.ref == entry.ref]:
                entries.append(entry)

        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        width = round((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = round((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)

        calc = QgsRasterCalculator(expression,
                                   output,
                                   driverName,
                                   bbox,
                                   crs,
                                   width,
                                   height,
                                   entries,
                                   context.transformContext())

        res = calc.processCalculation(feedback)
        if res == QgsRasterCalculator.ParserError:
            raise QgsProcessingException(self.tr("Error parsing formula"))

        return {self.OUTPUT: output}
Exemple #44
0
def DasimetricCalculator(diretorioOut, resolucao):
    try:
        raster1 = diretorioOut + r"\pop.asc"
        popLayer = QgsRasterLayer(raster1, "pop")
        raster2 = diretorioOut + r"\rdensity.asc"
        rdensityLayer = QgsRasterLayer(raster2, "rdensity")
        raster3 = diretorioOut + r"\outputE.asc"
        eLayer = QgsRasterLayer(raster3, "e")
        raster4 = diretorioOut + r"\outputT.asc"
        tLayer = QgsRasterLayer(raster4, "t")

        entries = []
        pop = QgsRasterCalculatorEntry()
        pop.ref = 'pop@1'
        pop.raster = popLayer
        pop.bandNumber = 1
        entries.append(pop)

        rdensity = QgsRasterCalculatorEntry()
        rdensity.ref = 'rdensity@1'
        rdensity.raster = rdensityLayer
        rdensity.bandNumber = 1
        entries.append(rdensity)

        e = QgsRasterCalculatorEntry()
        e.ref = 'e@1'
        e.raster = eLayer
        e.bandNumber = 1
        entries.append(e)

        t = QgsRasterCalculatorEntry()
        t.ref = 't@1'
        t.raster = tLayer
        t.bandNumber = 1
        entries.append(t)

        resultado = diretorioOut + r"\dasimetric.tif"
        resolucao2 = int(resolucao) * int(resolucao)
        expression = '(pop@1 * rdensity@1 *{})/(e@1 * t@1)'.format(resolucao2)
        print expression

        calc = QgsRasterCalculator(expression, resultado, 'GTiff',
                                   popLayer.extent(), popLayer.width(),
                                   popLayer.height(), entries)

        calc.processCalculation()

        fileInfo5 = QFileInfo(resultado)
        path5 = fileInfo5.filePath()
        baseName5 = fileInfo5.baseName()
        layer5 = QgsRasterLayer(path5, baseName5)
        QgsMapLayerRegistry.instance().addMapLayer(layer5)
        if layer5.isValid() is True:
            print "Dasimetric result was loaded successfully!"
        else:
            print "Unable to read basename and file path - Your string is probably invalid"

    except CalculationError:
        print "Dasimetric calculation error!"
    finally:
        print "Dasimetric calculation was successfully!"