Esempio n. 1
0
    def sclfactor(self):
        self.dlg.startprocessing.clicked.connect ( self.sclfactor )
        self.dlg.startprocessing.clicked.connect ( self.delfilescale )
        self.dlg.lineEdit_out.setText ( self.newfolderName )
        sf_path = self.newfolderName
        os.chdir ( sf_path )
        for sffile in glob.glob ( "*.tif" ):
            filname, exten = os.path.splitext ( sffile )
            outpt = ("sf_" + filname + exten)
            sf_out = (sf_path + outpt)
            entries = []
            myLayer1 = QgsRasterLayer ( sffile, 'raster' )
            my1 = QgsRasterCalculatorEntry ()
            my1.ref = 'my@1'
            my1.raster = myLayer1
            my1.bandNumber = 1
            entries.append ( my1 )
            SF = self.dlg.sfactor.text ()
            calc = QgsRasterCalculator ( 'my@1*{}'.format ( SF ),
                                         sf_out,
                                         'GTiff',
                                         myLayer1.extent (),
                                         myLayer1.width (),
                                         myLayer1.height (),
                                         entries )

            calc.processCalculation ()
    def calc_arvi(self):
        r = QgsRasterCalculatorEntry()
        r.ref = self.red.name() + '@1'
        r.raster = self.red
        r.bandNumber = 1

        ir = QgsRasterCalculatorEntry()
        ir.ref = self.nir.name() + '@2'
        ir.raster = self.nir
        ir.bandNumber = 1

        b = QgsRasterCalculatorEntry()
        b.ref = self.blue.name() + '@3'
        b.raster = self.blue
        b.bandNumber = 1

        entries = list()
        entries.append(r)
        entries.append(ir)
        entries.append(b)

        expression =  '({0} - ({1} - {3} * ({1} - {2}))) / ({0} + ({1} - {3} * ({1} - {2})))'.format(
            ir.ref, r.ref, b.ref, str(self.a)
        )

        calc = QgsRasterCalculator(
            expression,
            self.output, "GTiff",
            self.red.extent(), self.red.width(), self.red.height(),
            entries
        )
        calc.processCalculation()
Esempio n. 3
0
    def lulc_study_area(self):
        tempdir = self.gettempdir()
        lulc_layer = self.lulc_layer()
        study_area = self.study_layer()

        # Get Study area layer info.
        studylyrName = study_area.name()
        entries = []
        studyras = QgsRasterCalculatorEntry()
        studyras.ref = studylyrName + '@1'
        studyras.raster = study_area
        studyras.bandNumber = 1
        entries.append(studyras)

        # Get lulc layer info.
        lulcName = lulc_layer.name()
        lulcras = QgsRasterCalculatorEntry()
        lulcras.ref = lulcName + '@1'
        lulcras.raster = lulc_layer
        lulcras.bandNumber = 1
        entries.append(lulcras)

        formula = "\"" + studyras.ref + "\"" + ' * ' + "\"" + lulcras.ref + "\""
        output_lulc_study = tempdir + "/%s_study.tif" % str(lulcName)
        calc = QgsRasterCalculator(formula, output_lulc_study, 'GTiff',
                                   study_area.extent(), study_area.width(),
                                   study_area.height(), entries)
        calc.processCalculation()
        del entries

        return output_lulc_study
    def run(self):
        """
        Start of calculation.
        A GTiff-file is created in the process.
        """

        self.LOGGER.debug("start NDVI calculation")

        r = QgsRasterCalculatorEntry()
        ir = QgsRasterCalculatorEntry()

        r.raster = self.red_raster_layer
        ir.raster = self.infrared_raster_layer

        r.bandNumber = self.red_band_number
        ir.bandNumber = self.infrared_band_number

        r.ref = self.red_raster_layer.name() + "@" + str(self.red_band_number)
        ir.ref = self.infrared_raster_layer.name() + "@" + str(
            self.infrared_band_number)

        references = (ir.ref, r.ref, ir.ref, r.ref)
        formula_string = '("%s" - "%s") / ("%s" + "%s")' % references

        output_format = "GTiff"
        output_extent = self.red_raster_layer.extent()
        n_output_columns = self.red_raster_layer.width()
        n_output_rows = self.red_raster_layer.height()
        raster_entries = [ir, r]

        ndvi_raster_calculator = QgsRasterCalculator(
            formula_string, self.output_file_name, output_format,
            output_extent, n_output_columns, n_output_rows, raster_entries)
        ndvi_raster_calculator.processCalculation()
        self.finished.emit(self.output_file_name)
Esempio n. 5
0
    def weighted_sum(self):
        entries = []  # stores the enties for the rascalc operation
        instruccions = ""
        numbers = [x for x in xrange(0, 100)]
        numrasters = len(self.raster_years_layers)
        factor = [1 - 0.2 * x for x in xrange(0, numrasters)]
        factor.sort()
        items = ['(layer%s@1)' % (str(x)) for x in xrange(1, numrasters + 1)]
        sum_op = [
            items[x] + "*" + str(factor[x]) for x in xrange(0, len(factor))
        ]
        expresion = " + ".join(sum_op)

        for x in xrange(1, numrasters + 1):
            instruccions += 'layer%s = QgsRasterCalculatorEntry();' % (str(x))
            instruccions += "layer%s.ref = 'layer%s@1';" % (str(x), str(x))
            instruccions += 'layer%s.raster = self.raster_years_layers[%d];' % (
                str(x), x - 1)
            instruccions += 'layer%s.bandNumber = 1;' % (str(x))
            if x == numrasters:
                instruccions += 'entries.append( layer%s )' % (str(x))
            else:
                instruccions += 'entries.append( layer%s );' % (str(x))
        exec(instruccions)
        print expresion
        calc = QgsRasterCalculator(
            expresion, self.output_path + '\\' + 'suma_ponderada.tif', 'GTiff',
            self.imported_layer.extent(), self.raster_years_layers[0].width(),
            self.raster_years_layers[0].height(), entries)

        calc.processCalculation()
        rasterLyr = QgsRasterLayer(
            self.output_path + '\\' + 'suma_ponderada.tif', "suma_ponderada")
        self.raster_layer_ws = self.output_path + '\\' + 'suma_ponderada.tif'
        QgsMapLayerRegistry.instance().addMapLayers([rasterLyr])
Esempio n. 6
0
    def sum_second_impact_pop(self):
        # Get temporary directory.
        tempdir = self.gettempdir()

        # Get layers already created in temporary directory.
        first_area_list, second_area_list, first_pop_list, second_pop_list = self.pre_siam(
        )
        entries = []

        for i in range(0, len(second_pop_list)):
            raster = second_pop_list[i]
            readRst = processing.getObject(str(raster))
            ras1 = QgsRasterCalculatorEntry()
            ras1.raster = readRst
            ras1.ref = "second_impact_pop_" + str(i + 1) + "@1"
            ras1.bandNumber = 1
            entries.append(ras1)

        reflist = " + ".join([ent.ref for ent in entries])
        formula = '(' + reflist + ')'

        readRst = QgsRasterLayer(second_pop_list[0])
        sum_second_impact_pop = tempdir + "/sum_second_impact_pop.tif"
        calc = QgsRasterCalculator(formula, sum_second_impact_pop, 'GTiff',
                                   readRst.extent(), readRst.width(),
                                   readRst.height(), entries)
        calc.processCalculation()
        return sum_second_impact_pop
Esempio n. 7
0
    def pop_boundary(self):
        tempdir = self.gettempdir()
        study_area = self.study_layer()
        pop_layer = self.pop_layer()
        entries = []

        # Get Study area layer info.
        studylyrName = study_area.name()
        studyras = QgsRasterCalculatorEntry()
        studyras.ref = studylyrName + '@1'
        studyras.raster = study_area
        studyras.bandNumber = 1
        entries.append(studyras)

        # Get Population area layer info.
        poplyrName = pop_layer.name()
        popras = QgsRasterCalculatorEntry()
        popras.ref = poplyrName + '@1'
        popras.raster = pop_layer
        popras.bandNumber = 1
        entries.append(popras)

        formula = "\"" + studyras.ref + "\"" + ' * ' + "\"" + popras.ref + "\""
        #print formula
        pop_output = tempdir + "/%s_study.tif" % str(poplyrName)
        #print pop_output
        calc = QgsRasterCalculator(formula, pop_output, 'GTiff',
                                   study_area.extent(), study_area.width(),
                                   study_area.height(), entries)
        calc.processCalculation()
        del entries
        return pop_output
Esempio n. 8
0
    def capacity(self):
        lstStnd_Capa = self.lst_capa()
        tempdir = self.gettempdir()
        entries = []

        try:
            for i in range(0, len(lstStnd_Capa)):
                raster = lstStnd_Capa[i]
                readRst = processing.getObject(raster)
                ras1 = QgsRasterCalculatorEntry()
                ras1.raster = readRst
                ras1.ref = "capa_lyr" + str(i + 1) + "@1"
                ras1.bandNumber = 1
                entries.append(ras1)

            formula = '((' + entries[0].ref + ' * ' + entries[
                1].ref + ')^ 0.5)* 1000000'
            readRst = QgsRasterLayer(lstStnd_Capa[0])
            output = tempdir + "/Capacity.tif"
            calc = QgsRasterCalculator(formula, output, 'GTiff',
                                       readRst.extent(), readRst.width(),
                                       readRst.height(), entries)
            calc.processCalculation()
            return output

        except:
            self.userWarning(
                "Error in Create Adaptive Capacity map",
                "Can not create Create Adaptive Capacity map, Exit")
Esempio n. 9
0
    def lulc_rasters(self):
        tempdir = self.gettempdir()
        classes = self.lulc_classess()
        layerpath = self.lulc_study_area()

        fileInfo = QFileInfo(layerpath)
        baseName = fileInfo.baseName()
        lyr = QgsRasterLayer(layerpath, baseName)

        entries = []
        ras = QgsRasterCalculatorEntry()
        ras.ref = baseName + '@1'
        ras.raster = lyr
        ras.bandNumber = 1
        entries.append(ras)

        # List of output rasters for lulc types
        lulc_list = []

        for i in classes:
            formula = "(" + "\"" + ras.ref + "\"" + ' = ' + str(
                i) + " ) " + " * " + str(i)
            output = tempdir + "/" + str(baseName) + "_%s.tif" % str(i)
            lulc_list.append(output)
            calc = QgsRasterCalculator(formula, output, 'GTiff', lyr.extent(),
                                       lyr.width(), lyr.height(), entries)
            calc.processCalculation()
        del entries
        return lulc_list
Esempio n. 10
0
    def processing_ndvi_calc(rLayer1, rLayer2, path):
        """
        Older deprecated NDVI handler, This is simply the template for the monstrosity that the current one has become
        :param rLayer1: rLayer 1 Object
        :param rLayer2: rLayer 2 Object
        :param path: Path to Output too
        :return: None
        """

        path = path

        r1 = QgsRasterCalculatorEntry()
        r2 = QgsRasterCalculatorEntry()

        r1.ref = "rLayer@1"
        r2.ref = "rLayer@2"

        r1.raster = rLayer1
        r2.raster = rLayer2

        r1.bandNumber = 1
        r2.bandNumber = 1

        entries = [r1, r2]

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

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

        a.processCalculation()
Esempio n. 11
0
    def roundresult(self, result):
        filename = self.dlg.path.text()
        path = filename.replace(".tif","_risk.tif")
        entries = []
        entry = self.defineentry(result)
        entries.append(entry)
        formula = '(' + entries[0].ref + ' < 1.5) * 1 + (' + entries[0].ref + '>= 1.5 AND ' + entries[0].ref + ' < 2.5) * 2 + (' + entries[0].ref + ' >=2.5 AND ' + entries[0].ref + ' < 3.5) * 3 + (' + entries[0].ref + ' >=3.5 AND ' + entries[0].ref + ' < 4.5) * 4 + (' + entries[0].ref + ' >=4.5) * 5' # FALTA EDITAR A FORMULA
        print formula
        print path
        extent = result.extent()
        width = result.width()
        height = result.height()
        print extent
        print width
        print height
        #[extent, width, height] = self.resultextent(layers) #

        calc = QgsRasterCalculator(formula,
                                   path,
                                   'GTiff',
                                   extent,
                                   width,
                                   height,
                                   entries)
        calc.processCalculation()
        result = QgsRasterLayer(path,'Vulnerabilidade')
        if result.isValid():
            return result
        else:
            QMessageBox.warning(None, 'Coastal Risk Assessment', 'The output layer is not valid!')
Esempio n. 12
0
def RasterAddition(luccraster, nppraster, outputfilename):
    luccraster = OpenRaster(luccfilename)
    # print("Lucc : " + str(luccraster.isValid()))

    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', outputfilename, 'GTiff',
                               luccraster.extent(), luccraster.width(),
                               luccraster.height(), entries)

    calc.processCalculation()
    def processAlgorithm(self, parameters, context, progress):
        output = self.parameterAsOutputLayer(parameters, self.OUTPUT_SURFACE,
                                             context)

        bottomRaster = self.parameterAsRasterLayer(parameters,
                                                   self.BOTTOM_SURFACE,
                                                   context)
        topRaster = self.parameterAsRasterLayer(parameters, self.TOP_SURFACE,
                                                context)

        entries = []
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'ras@1'
        ras.raster = topRaster
        ras.bandNumber = 1
        entries.append(ras)
        ras1 = QgsRasterCalculatorEntry()
        ras1.ref = 'ras1@1'
        ras1.raster = bottomRaster
        ras1.bandNumber = 1
        entries.append(ras1)
        calc = QgsRasterCalculator(
            'ras@1 + (ras1@1 - ras@1) * ((ras1@1 - ras@1) >= 0)', output,
            'GTiff', bottomRaster.extent(), bottomRaster.width(),
            bottomRaster.height(), entries)
        calc.processCalculation()

        return {self.OUTPUT_SURFACE: output}
Esempio n. 14
0
    def NDVI_calc(self , layers):

        entries = []
        
        for l in layers:
            layer = QgsRasterCalculatorEntry()
            layer = QgsRasterCalculatorEntry()
            layer.ref = l.name() +'@1'
            layer.raster = l
            layer.bandNumber = 1
            entries.append(layer)
            
# Original path: C:/Users/fumibol/Documents/Wetlands/Python/QGIS arcPython/NDVI plugin/Output/NDVI.tif

#        for entry in entries:

        raster_salida = ""
# First it was raster_salida = ruta + os.path.sep + raster_salida + '.tif'
        raster_salida = unicode(self.dlg.ui.ln_name_ndvi.text())
            
        expression = '(' + entries[1].ref + ' + ' + entries[0].ref + ')/(' + entries[1].ref + ' - ' + entries[0].ref + '+ 1)'
        calc = QgsRasterCalculator(expression, raster_salida, 'GTiff', layers[0].extent(), layers[0].width(), layers[0].height(), entries)

        calc.processCalculation()
        
#        QgsMapLayerRegistry.instance().addMapLayer('C:/Users/fumibol/Documents/Wetlands/Python/QGIS arcPython/NDVI plugin/Output/NDVI.tif' , 'NDVI result')

        rl = self.iface.addRasterLayer(raster_salida , 'NDVI result')
			
        QMessageBox.information(self.iface.mainWindow(),"Success!" , "Raster image " + entries[0].ref + " created successfully ")
Esempio n. 15
0
    def calc_sipi(self):
        lyr1 = self.getRed()
        lyr2 = self.getNir()
        lyr3 = self.getBlue()
        output = os.path.join(self.dlg.le_output.text(),"sipi.tif")

        entries = []
        #red band
        ras1 = QgsRasterCalculatorEntry()
        ras1.ref = 'red'
        ras1.raster = lyr1
        ras1.bandNumber = 1
        entries.append(ras1)
        #nir band
        ras2 = QgsRasterCalculatorEntry()
        ras2.ref = 'nir'
        ras2.raster = lyr2
        ras2.bandNumber = 1
        entries.append( ras2 )
        #blue band
        ras3 = QgsRasterCalculatorEntry()
        ras3.ref = 'blue'
        ras3.raster = lyr3
        ras3.bandNumber = 1
        entries.append( ras3 )
        calc = QgsRasterCalculator( '("nir" - "blue") / ("nir" - "red")', \
        output, 'GTiff', lyr1.extent(), lyr1.width(), lyr1.height(), entries )
        calc.processCalculation()
        self.iface.messageBar().pushMessage("SIPI Output Created Successfully", level=Qgis.Success, duration=3)
Esempio n. 16
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
Esempio n. 17
0
    def calc_cvi(self):
        lyr1 = self.getRed()
        lyr2 = self.getNir()
        lyr3 = self.getGreen()
        output = os.path.join(self.dlg.le_output.text(),"cvi.tif")

        entries = []
        #red band
        ras1 = QgsRasterCalculatorEntry()
        ras1.ref = 'red'
        ras1.raster = lyr1
        ras1.bandNumber = 1
        entries.append(ras1)
        #nir band
        ras2 = QgsRasterCalculatorEntry()
        ras2.ref = 'nir'
        ras2.raster = lyr2
        ras2.bandNumber = 1
        entries.append( ras2 )
        #green band
        ras3 = QgsRasterCalculatorEntry()
        ras3.ref = 'green'
        ras3.raster = lyr3
        ras3.bandNumber = 1
        entries.append( ras3 )

        calc = QgsRasterCalculator( '"nir" * ("red" / ("green" * "green"))', \
        output, 'GTiff', lyr1.extent(), lyr1.width(), lyr1.height(), entries )
        calc.processCalculation()
        self.iface.messageBar().pushMessage("CVI Output Created Successfully", level=Qgis.Success, duration=3)
Esempio n. 18
0
def WeightedOverlay(bohLayer, bohLayer1):
    tf = tempfile.TemporaryDirectory()
    tfile = tf.name + "\\OUTPUT.tif"

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

    #define band 2
    boh2 = QgsRasterCalculatorEntry()
    boh2.ref = 'boh1@1'
    boh2.raster = bohLayer1
    boh2.bandNumber = 1
    entries.append(boh2)

    # Process calculation with input extent and resolution
    calc = QgsRasterCalculator('Float(boh1@1 - boh@1)/Float(boh1@1 + boh@1)',
                               'outputfile', 'GTiff', bohLayer.extent(),
                               bohLayer.width(), bohLayer.height(), entries)
    calc.processCalculation()
    '''
Esempio n. 19
0
    def processAlgorithm(self, parameters, context, progress):
        output = self.parameterAsOutputLayer(parameters, self.OUTPUT_SURFACE,
                                             context)
        topRaster = self.parameterAsRasterLayer(parameters, self.TOP_SURFACE,
                                                context)
        bottomRaster = self.parameterAsRasterLayer(parameters,
                                                   self.BOTTOM_SURFACE,
                                                   context)
        ntgRaster = self.parameterAsRasterLayer(parameters, self.NTG_SURFACE,
                                                context)
        poroRaster = self.parameterAsRasterLayer(parameters, self.PORO_SURFACE,
                                                 context)
        vnkValue = self.parameterAsDouble(parameters, self.VNK_VALUE, context)

        formula = '( base@1 - top@1 ) * ( base@1 <= {0} ) + ( {0} - top@1 ) * ( base@1 > {0} ) * ' \
                  '( (  base@1 - top@1 ) * ( base@1 <= {0}) + ( {0} - top@1 ) * ( base@1 > {0} ) > 0)'.format(vnkValue)

        entries = []
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'top@1'
        ras.raster = topRaster
        ras.bandNumber = 1
        entries.append(ras)
        ras1 = QgsRasterCalculatorEntry()
        ras1.ref = 'base@1'
        ras1.raster = bottomRaster
        ras1.bandNumber = 1
        entries.append(ras1)
        calc = QgsRasterCalculator(formula, output, 'GTiff',
                                   bottomRaster.extent(), bottomRaster.width(),
                                   bottomRaster.height(), entries)
        calc.processCalculation(progress)

        return {self.OUTPUT_SURFACE: output}
    def calc_savi(self):
        r = QgsRasterCalculatorEntry()
        r.ref = self.red.name() + '@1'
        r.raster = self.red
        r.bandNumber = 1

        ir = QgsRasterCalculatorEntry()
        ir.ref = self.nir.name() + '@2'
        ir.raster = self.nir
        ir.bandNumber = 1

        entries = list()
        entries.append(r)
        entries.append(ir)

        expression =  '(({0} - {1}) / ({0} + {1} + {2})) * (1 + {2})'.format(
            ir.ref, r.ref, self.L
        )

        calc = QgsRasterCalculator(
            expression,
            self.output, "GTiff",
            self.red.extent(), self.red.width(), self.red.height(),
            entries
        )
        calc.processCalculation()
Esempio n. 21
0
    def second_impact_rasters(self):
        tempdir = self.gettempdir()
        classes = self.second_impact_classes()
        layer = self.second_impact_layer()

        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)

        # List of output rasters for lulc types
        second_list = []

        for i in classes:
            formula = "(" + "\"" + ras1.ref + "\"" + ' = ' + str(
                i) + " ) " + " * " + str(i)
            output = tempdir + "/" + str(lyrName) + "_%s.tif" % str(i)
            second_list.append(output)
            calc = QgsRasterCalculator(formula, output, 'GTiff', lyr2.extent(),
                                       lyr2.width(), lyr2.height(), entries)
            calc.processCalculation()
        del entries
        return second_list
Esempio n. 22
0
    def processAlgorithm(self, feedback):
        expression = self.getParameterValue(self.EXPRESSION)
        layersValue = self.getParameterValue(self.LAYERS)
        layersDict = {}
        if layersValue:
            layers = [
                dataobjects.getObjectFromUri(f) for f in layersValue.split(";")
            ]
            layersDict = {
                os.path.basename(lyr.source().split(".")[0]): lyr
                for lyr in layers
            }

        for lyr in dataobjects.getRasterLayers():
            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"))
Esempio n. 23
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}
def Evapo (imagem, output):
	entries  = []
	raster1 = QgsRasterCalculatorEntry()
	raster1.ref = 'imagem@1'
	raster1.raster = imagem
	raster1.bandNumber = 1
	entries.append (raster1)
	calc =QgsRasterCalculator ('imagem@1 * 0.1', output, 'GTiff', imagem.extent(), imagem.width(), imagem.height(), entries)
	calc.processCalculation()
def Calibracao (imagem, output):
	entries  = []
	raster1 = QgsRasterCalculatorEntry()
	raster1.ref = 'imagem@1'
	raster1.raster = imagem
	raster1.bandNumber = 1
	entries.append (raster1)
	calc =QgsRasterCalculator ('0.9614*imagem@1 - 65.706', output, 'GTiff', imagem.extent(), imagem.width(), imagem.height(), entries)
	calc.processCalculation()
Esempio n. 26
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.
        rasterInput1 = self.parameterAsRasterLayer(parameters, self.INPUT_1,
                                                   context)

        rasterInput2 = self.parameterAsRasterLayer(parameters, self.INPUT_2,
                                                   context)

        FOperation = self.parameterAsEnum(parameters, self.CHOICE_FOPERATION,
                                          context)
        feedback.pushInfo('Fuzzy Operation: ' + str(FOperation))

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

        rCalcEntry1 = QgsRasterCalculatorEntry()
        rCalcEntry1.ref = 'r1@1'
        rCalcEntry1.raster = rasterInput1

        rCalcEntry2 = QgsRasterCalculatorEntry()
        rCalcEntry2.ref = 'r2@1'
        rCalcEntry2.raster = rasterInput2

        fsum = '1 - (( 1 - r1@1) * (1 - r2@1))'
        fAnd = '((r1@1 < r2@1) * r1@1 ) + ((r2@1 < r1@1) * r2@1 ) + ((r2@1 = r1@1) * r2@1 ) '
        fOr = '((r1@1 > r2@1) * r1@1 ) + ((r2@1 > r1@1) * r2@1 ) + ((r2@1 = r1@1) * r2@1 )'
        fMultiply = 'r1@1 * r2@1'

        if FOperation == 0:
            formula = fsum
        elif FOperation == 1:
            formula = fAnd
        elif FOperation == 2:
            formula = fOr
        elif FOperation == 3:
            formula = fMultiply

        feedback.pushInfo('Operator: ' + str(FOperation))
        feedback.pushInfo('Formula: ' + str(formula))
        calc = QgsRasterCalculator(formula, outputFile, 'GTiff',
                                   rasterInput1.extent(), rasterInput1.width(),
                                   rasterInput1.height(),
                                   [rCalcEntry1, rCalcEntry2])

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

        return {self.OUTPUT: outputFile}
Esempio n. 27
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"))
Esempio n. 28
0
            def calculo(expresion, capa):
                calc = QgsRasterCalculator(
                    expresion,
                    os.path.join(carpeta,
                                 troncoresumido + '_' + capa + '.tif'),
                    'GTiff', layerglobal.extent(), layerglobal.width(),
                    layerglobal.height(), entries)

                calc.processCalculation()
                del (calc)
Esempio n. 29
0
def main():
    # Read the options and arguments from the command line (w/ some default settings).
    options = Options()
    opts = options.parse(sys.argv[1:])

    # Configure logging.
    FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
    logging.basicConfig(filename=opts.logfile,
                        filemode="w",
                        format=FORMAT,
                        level=logging.DEBUG)
    logging.getLogger().addHandler(logging.StreamHandler())

    # Init QGIS
    app = QApplication(sys.argv)
    QgsApplication.setPrefixPath("/usr/local/qgis_master", True)
    QgsApplication.initQgis()

    #Load CIR orthofoto
    fileName = "/home/stefan/Downloads/1091-231.tif"
    fileInfo = QFileInfo(fileName)
    baseName = fileInfo.baseName()
    rlayer = QgsRasterLayer(fileName, baseName)
    if not rlayer.isValid():
        print "Layer failed to load!"

    print "************"
    print rlayer.width()
    print rlayer.bandCount()
    #print rlayer.metadata()
    #print rlayer.rasterType()
    #print rlayer.dataProvider().colorTable(1)
    print "************"

    # Define an alias for each band in form of a QgsRasterCalculatorEntry.
    entries = []

    band1 = QgsRasterCalculatorEntry()
    band1.ref = 'cir@1'
    band1.raster = rlayer
    band1.bandNumber = 1
    entries.append(band1)

    band2 = QgsRasterCalculatorEntry()
    band2.ref = 'cir@2'
    band2.raster = rlayer
    band2.bandNumber = 2
    entries.append(band2)

    # Process calculation with input extent and resolution
    calc = QgsRasterCalculator('(cir@1 - cir@2) / (cir@1 + cir@2)',
                               '/home/stefan/Downloads/1091-231_ndvi.tif',
                               'GTiff', rlayer.extent(), rlayer.width(),
                               rlayer.height(), entries)
    calc.processCalculation()
Esempio n. 30
0
 def calculo(expresion,capa):
     calc = QgsRasterCalculator(expresion, 
                     os.path.join(carpeta,troncoresumido+'_'+capa+'.tif'), 
                     'GTiff', 
                     layerglobal.extent(), 
                     layerglobal.width(), 
                     layerglobal.height(), 
                     entries )
                      
     calc.processCalculation()
     del(calc)
Esempio n. 31
0
    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = NDVIDialog()
            self.dlg.pushButton.clicked.connect(self.select_output_file)

        # Fetch the currently loaded layers
        layers = QgsProject.instance().layerTreeRoot().children()
        # Clear the contents of the comboBox from previous runs
        self.dlg.comboBox.clear()
        # Populate the comboBox with names of all the loaded layers
        self.dlg.comboBox.addItems([layer.name() for layer in layers])

        self.dlg.comboBox_2.clear()
        # Populate the comboBox with names of all the loaded layers
        self.dlg.comboBox_2.addItems([layer.name() for layer in layers])

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
                
            l7_b4 = self.dlg.comboBox.currentIndex()
            l7_b4 = layers[l7_b4].layer()
            l7_b3 = self.dlg.comboBox_2.currentIndex()
            l7_b3 = layers[l7_b3].layer() 
            entries = []
            output = self.dlg.lineEdit.text()
            raster4 = l7_b4
            b4 = QgsRasterCalculatorEntry()
            b4.ref = "b4@1"
            b4.raster = raster4
            b4.bandNumber = 1
            raster3 = l7_b3
            b3 = QgsRasterCalculatorEntry()
            b3.ref = "b3@1"
            b3.raster = raster3
            b3.bandNumber = 1
            entries.append(b4)
            entries.append(b3)
            calc = QgsRasterCalculator('("b4@1"-"b3@1")/("b4@1"+"b3@1")',output,"GTiff",\
                                    raster4.extent(),raster4.width(),raster4.height(),entries)
            calc.processCalculation()
            self.iface.messageBar().pushMessage(
                            "Success", "Output file written at " ,
            level=Qgis.Success, duration=3)
Esempio n. 32
0
    def calculate_raster(self, exp, output_ras, input_ras_dirs, dir_text_file):
        # raster calculator function for multi-layer-operations
        # exp = STR containing calculation expression
        # output_ras = STR of output Raster name
        # input_ras_dirs = LIST of calculator entries created with self.convert_to_calc_entry() function
        # dir_text_file = STR of a text file (full path) used where output Raster names will be logged

        logging.info(' *** -- expression: ' + exp)
        logging.info(' *** -- output target Raster: ' + str(output_ras))
        ras_lyrs = []
        entries = []
        for i in input_ras_dirs:
            lyr, ras = self.convert_to_calc_entry(i)
            ras_lyrs.append(ras)
            entries.append(lyr)
        try:
            if ras_lyrs[0].isValid():
                '''
                self.ras_lyrs[0].extent().width = self.output_size
                self.ras_lyrs[0].extent().height = self.output_size
                self.ras_lyrs[0].width= self.output_size
                self.ras_lyrs[0].height= self.output_size
                '''
                try:
                    logging.info(" *** -- calculating ... ")
                    calc = QgsRasterCalculator(exp, output_ras, 'GTiff',
                                               ras_lyrs[0].extent(),
                                               ras_lyrs[0].width(),
                                               ras_lyrs[0].height(), entries)
                    try:
                        logging.info(" *** -- " +
                                     str(calc.processCalculation()))
                    except:
                        print(calc.processCalculation())
                    logging.info(" *** -- calculation success (done).")
                except:
                    logging.warning("FAILED Raster Calculation.")
                    return -1
                if QgsRasterLayer(output_ras).isValid():
                    f = open(dir_text_file, 'a')
                    f.write(output_ras + "\n")
                    logging.info(" *** -- created Raster: " + output_ras +
                                 "\n")
                    f.close()
                else:
                    logging.warning("INVALID Output Raster: " + output_ras)
            else:
                try:
                    logging.warning("INVALID Raster: " + ras_lyrs[0].ref)
                except:
                    logging.warning("INVALID Raster.")
        except:
            logging.info("ERROR: Testing raster_layer.isValid() failed.")
Esempio n. 33
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}
Esempio n. 34
0
def raster_calculator(layerPath, expression, extentPathIndex=0, fname=None):
    '''
	calculate solution of one of more raster.

	Usage: 
		layerPath is a List of paths to rasters (e.g. ['var/myfile.tif',
		'var/myfile2.tif']) the expression variable will be passed to python's
		.format string function. Theirfore an example of a multiplying two
		rasters goes as follows. '{0} * {1}' where 0 and 1 are the indcies of the
		layerPath list, so in the example myfile.tif * myfile2.tif would be
		calculated. extentPathIndex sets the extent to be used during the
		calculation to the given index of the layerPath. It is set by default to
		0. fname is an optional variable which sets the output file name that is
		saved in the layerPath[0]'s parent folder if left as default, the layer
		will be named layerPath[0]'s value + _.output.tif
	'''
    from qgis.core import QgsRasterLayer

    if type(layerPath) != list:
        layerPath = [layerPath]
    layerNameList = [os.path.basename(x).split('.')[0] for x in layerPath]
    layerList = [
        QgsRasterLayer(layerPath[x], layerNameList[x])
        for x in range(len(layerPath))
    ]
    entries = [QgsRasterCalculatorEntry() for _ in range(len(layerPath))]

    def helper(L, L2, x):
        L[x].ref, L[x].raster, L[x].bandNumber = L2[x].name() + '@1', L2[x], 1

    [helper(entries, layerList, x) for x in range(len(entries))]
    rasterCalculationExpression = expression.format(
        *map(lambda x: x.ref, entries))
    if fname:
        # Creates the path for which the calculation is saved to.
        # THE FILE EXTENSION IS ASSUMED TO BE IN FNAME ex: fname = foo.tif
        fnamePath = os.path.join(os.path.dirname(layerPath[0]), fname)
    else:
        fnamePath = os.path.join(os.path.dirname(layerPath[0]),
                                 layerNameList[0] + '_output.tif')

    arglist = [
        rasterCalculationExpression, fnamePath, 'GTiff',
        layerList[extentPathIndex].extent(),
        layerList[extentPathIndex].width(),
        layerList[extentPathIndex].height(), entries
    ]
    rasterCalculation = QgsRasterCalculator(*arglist)
    if rasterCalculation.processCalculation() != 0:
        print("Houston we have a problem with the rasters")
    else:
        return os.path.join(os.path.dirname(layerPath[0]), fnamePath)
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"
Esempio n. 36
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 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()
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()
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()
Esempio n. 40
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}
Esempio n. 41
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()
Esempio n. 42
0
            def agregado(rasterdeentrada):
                #filtro gausian para dar valor en funcion de los vecinos
                input=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'1.tif')
                sigma=0.2
                mode=1
                radius=2
                result=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'g2.tif')
                processing.runalg('saga:gaussianfilter', input, sigma, mode, radius, result)
                StringToRaster(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'g2.tif'),rasterdeentrada+str("g2"))
                
                #filtro y me quedo con lo mayor de 0,40
                calc = QgsRasterCalculator("'"+rasterdeentrada+'g2@1 > 0.40',
                                           os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'g2s.tif'),
                                           'GTiff',
                                    layerglobal.extent(), 
                                    layerglobal.width(), 
                                    layerglobal.height(), 
                                    entries )
                calc.processCalculation()
                del(calc)
                StringToRaster(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'g2s.tif'),rasterdeentrada+str("g2s"))
                
                #convierto en nodata lo que no me interesa
                calc = QgsRasterCalculator(("'"+rasterdeentrada+'g2s@1'>0)*"'"+rasterdeentrada+'g2s@1', 
                            os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'g2sn.tif'), 
                            'GTiff', 
                            layerglobal.extent(), 
                            layerglobal.width(), 
                            layerglobal.height(), 
                            entries )
                calc.processCalculation()
                del(calc)
                StringToRaster(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'g2sn.tif'),rasterdeentrada+str("g2sn"))
               
                #filtro  filter clums eliminar los huecos menores de 1300 m2
                input=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'g2sn.tif')  
                threshold=13
                result=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'3.tif')
                processing.runalg('saga:filterclumps', input, threshold, result)
                StringToRaster(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'3.tif'),rasterdeentrada+str("3"))

                #filtro mayorityffilter para dar valor en funcion de los vecinos
                input=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'3.tif')
                mode=0
                radius=1
                threshold=4
                result=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'4.tif')
                try:
                    processing.runalg('saga:majorityfilter', input, mode, radius, threshold, result)
                    StringToRaster(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'4.tif'),rasterdeentrada+str("4"))
                    
                    #filtro para rellenar huecos pequenos
                    input=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'4.tif')
                    distance=3
                    iterations=0
                    band=1
                    mask=None
                    no_default_mask='True'
                    output=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'5.tif')
                    processing.runalg('gdalogr:fillnodata', input, distance, iterations, band,mask,no_default_mask, output)
                    StringToRaster(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'5.tif'),rasterdeentrada+str("5"))

                    #filtro  filter clums eliminar los huecos
                    input=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'5.tif')

                    threshold=5
                    result=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'6.tif')
                    processing.runalg('saga:filterclumps', input, threshold, result)
                    StringToRaster(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'6.tif'),rasterdeentrada+str("6"))

                    #filtro para rellenar huecos pequenos
                    input=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'6.tif')
                    distance=3
                    iterations=0
                    band=1
                    mask=None
                    no_default_mask='True'
                    output=os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'7.tif')
                    processing.runalg('gdalogr:fillnodata', input, distance, iterations, band,mask,no_default_mask, output)
                    StringToRaster(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'7.tif'),rasterdeentrada+str("7"))
                    
                    #lo vectorizo
                    processing.runalg("gdalogr:polygonize",os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'7.tif'),"DN",os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'.shp'))

                    #seleciono lo que me interesa
                    lyr=QgsVectorLayer(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'.shp'),rasterdeentrada,"ogr")
                    QgsMapLayerRegistry.instance().addMapLayers([lyr])
                    selection = lyr.getFeatures(QgsFeatureRequest().setFilterExpression(u'"DN" = 1'))
                    selecionado = lyr.setSelectedFeatures([s.id() for s in selection])
                    nbrSelected=lyr.selectedFeatureCount()

                    if nbrSelected > 0:
                        #guardo lo selecionado
                        processing.runalg("qgis:saveselectedfeatures",os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'.shp'),os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'2.shp'))

                        #calcula la superficie de esta capa pero no en todos los registros
                        layer=QgsVectorLayer(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'2.shp'),rasterdeentrada+str("2"),"ogr")
                        provider = layer.dataProvider()
                        areas = [ feat.geometry().area()  for feat in layer.getFeatures() ]
                        indice = [ feat.id()  for feat in layer.getFeatures() ]
                        field = QgsField("area", QVariant.Int)
                        provider.addAttributes([field])
                        layer.updateFields()
                        idx = layer.fieldNameIndex('area')
                        long=len(indice)
                        i=0
                        while i<long:
                            new_values = {idx : float(areas[i])}
                            provider.changeAttributeValues({indice[i]:new_values})
                            i=i+1           
                        layer.updateFields()

                        #selecciono las teselas mayor de una superficie dada.
                        layer2=QgsVectorLayer(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'2.shp'),rasterdeentrada+str("2"),"ogr")
                        QgsMapLayerRegistry.instance().addMapLayers([layer2])
                        selection = layer2.getFeatures(QgsFeatureRequest().setFilterExpression(u'"area" > 2500'))
                        selecionado = layer2.setSelectedFeatures([s.id() for s in selection])
                    
                        #guardo lo selecionado
                        processing.runalg("qgis:saveselectedfeatures",os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'2.shp'),os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'3.shp'))
                        layer3=QgsVectorLayer(os.path.join(carpeta,troncoresumido+'_'+rasterdeentrada+'3.shp'),rasterdeentrada+str("3"),"ogr")
                        QgsMapLayerRegistry.instance().addMapLayer(layer3)
                        del(selection)
                        del(selecionado)
                        
                except:
                    pass
Esempio n. 43
0
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)    
Esempio n. 44
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}