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()
Esempio n. 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
Esempio n. 4
0
def Calibracao (imagem, output):
	entries  = []
	raster1 = QgsRasterCalculatorEntry()
	raster1.ref = 'imagem@1'
	raster1.raster = imagem
	raster1.bandNumber = 1
	entries.append (raster1)
	calc =QgsRasterCalculator ('0.7575*imagem@1 + 15.703', output, 'GTiff', imagem.extent(), imagem.width(), imagem.height(), entries)
	calc.processCalculation()
Esempio n. 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}
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()
Esempio n. 7
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. 8
0
    def calc_a0(self, dir_output, dir_E1, dir_E2, temp_folder, A10, A11):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_E1 = dir_E1
        self.dir_E2 = dir_E2
        self.dir_output_temp = self.path + 'A0.tif'

        self.A10 = A10
        self.A11 = A11

        entries = []

        E1 = QgsRasterLayer(self.dir_E1)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'E1@1'
        ras.raster = E1
        ras.bandNumber = 1
        entries.append(ras)

        E2 = QgsRasterLayer(self.dir_E2)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'E2@1'
        ras.raster = E2
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator(
                '"E1@1" * ' + self.A10 + ' + "E2@1" * ' + self.A11,
                self.dir_output_temp, 'GTiff', E2.extent(), E2.width(),
                E2.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                '"E1@1" * ' + self.A10 + ' + "E2@1" * ' + self.A11,
                self.dir_output, 'GTiff', E2.extent(), E2.width(), E2.height(),
                entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 9
0
def NDWI(band3, band8, output):
    entries = []
    #define raster 1 (band8)
    raster1 = QgsRasterCalculatorEntry()
    raster1.ref = 'band8@1'
    raster1.raster = band8
    raster1.bandNumber = 1
    entries.append(raster1)
    #define raster 2 (band3)
    raster2 = QgsRasterCalculatorEntry()
    raster2.ref = 'band3@1'
    raster2.raster = band3
    raster2.bandNumber = 1
    entries.append(raster2)
    #NDWI Procesado de las bandas
    # calc=QgsRasterCalculator('("band3@1"-"band8@1")/("band3@1"+"band8@1")',output,'GTiff',band8.extent(),band8.width(),band8.height(),entries)
    calc = QgsRasterCalculator(
        '(("band3@1"-"band8@1")/("band3@1"+"band8@1"))*100', output, 'GTiff',
        band8.extent(), band8.width(), band8.height(), entries)
    calc.processCalculation()
Esempio n. 10
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. 11
0
    def calc_ipvi(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}/({0} + {1})'.format(ir.ref, r.ref)

        calc = QgsRasterCalculator(expression, self.output, "GTiff",
                                   self.red.extent(), self.red.width(),
                                   self.red.height(), entries)
        calc.processCalculation()
Esempio n. 12
0
    def calc_a2(self, dir_output, dir_A, dir_E2, temp_folder, B11):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_A = dir_A
        self.dir_E2 = dir_E2
        self.dir_output_temp = self.path + 'A2.tif'

        self.B11 = B11

        entries = []

        A = QgsRasterLayer(self.dir_A)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'A@1'
        ras.raster = A
        ras.bandNumber = 1
        entries.append(ras)

        E2 = QgsRasterLayer(self.dir_E2)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'E2@1'
        ras.raster = E2
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator('"A@1" + "E2@1" * ' + self.B11 + ' ',
                                       self.dir_output_temp, 'GTiff',
                                       E2.extent(), E2.width(), E2.height(),
                                       entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator('"A@1" + "E2@1" * ' + self.B11 + ' ',
                                       self.dir_output, 'GTiff', E2.extent(),
                                       E2.width(), E2.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 13
0
    def calc_a1(self, dir_output, dir_A, dir_E1, temp_folder, B10):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_A = dir_A
        self.dir_E1 = dir_E1
        self.dir_output_temp = self.path + 'A1.tif'

        self.B10 = B10

        entries = []

        A = QgsRasterLayer(self.dir_A)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'A@1'
        ras.raster = A
        ras.bandNumber = 1
        entries.append(ras)

        E1 = QgsRasterLayer(self.dir_E1)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'E1@1'
        ras.raster = E1
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator('1 + "A@1" + "E1@1" * ' + self.B10,
                                       self.dir_output_temp, 'GTiff',
                                       E1.extent(), E1.width(), E1.height(),
                                       entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator('1 + "A@1" + "E1@1" * ' + self.B10,
                                       self.dir_output, 'GTiff', E1.extent(),
                                       E1.width(), E1.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 14
0
    def multiply_pop_second_impacts(self):
        tempdir = self.gettempdir()
        second_list = self.second_impact_rasters()
        pop_boundary_fullpath = self.pop_boundary()

        # Get Population area layer info.
        fileInfo = QFileInfo(pop_boundary_fullpath)
        poplyrName = fileInfo.baseName()
        poplyr = QgsRasterLayer(pop_boundary_fullpath, poplyrName)

        # poplyrName = pop_layer.name()
        popras = QgsRasterCalculatorEntry()
        popras.ref = poplyrName + '@1'
        popras.raster = poplyr
        popras.bandNumber = 1

        second_pop_list = []
        # multiply lulc classes with first impact class layers.
        for fullpathlayer1 in second_list:
            fileInfo1 = QFileInfo(fullpathlayer1)
            baseName1 = fileInfo1.baseName()
            firstlyr = processing.getObject(str(fullpathlayer1))
            ras1 = QgsRasterCalculatorEntry()
            ras1.ref = baseName1 + '@1'
            ras1.raster = firstlyr
            ras1.bandNumber = 1
            entries1 = []
            entries1.append(popras)
            entries1.append(ras1)

            formula1 = "\"" + ras1.ref + "\"" + ' * ' + "\"" + popras.ref + "\""
            output1 = tempdir + "/%s_%s.tif" % (str(baseName1),
                                                str(poplyrName))
            second_pop_list.append(output1)
            calc1 = QgsRasterCalculator(formula1, output1, 'GTiff',
                                        firstlyr.extent(), firstlyr.width(),
                                        firstlyr.height(), entries1)
            calc1.processCalculation()
            del entries1
        return second_pop_list
    def processWithRasterCalculator(self, parameters, context, feedback):  #pylint: disable=unused-argument,missing-docstring

        raster1 = self.parameterAsRasterLayer(parameters, self.RASTER1,
                                              context)
        band1 = self.parameterAsInt(parameters, self.BAND1, context)
        raster2 = self.parameterAsRasterLayer(parameters, self.RASTER2,
                                              context)
        band2 = self.parameterAsInt(parameters, self.BAND2, context)
        output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)

        bbox = raster1.extent()
        # cellsize = (bbox.xMaximum() - bbox.xMinimum()) / raster1.width()
        # width = round((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        # height = round((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        width = raster1.width()
        height = raster1.height()
        driver = GdalUtils.getFormatShortNameFromFilename(output)
        crs = raster1.crs()

        entry1 = QgsRasterCalculatorEntry()
        entry1.ref = 'A@%d' % band1
        entry1.raster = raster1
        entry1.bandNumber = 1

        entry2 = QgsRasterCalculatorEntry()
        entry2.ref = 'B@%d' % band2
        entry2.raster = raster2
        entry2.bandNumber = 1

        entries = [entry1, entry2]
        expression = "A@%d - B@%d" % (band1, band2)

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

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

        return {self.OUTPUT: output}
Esempio n. 16
0
    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model

        sample_raster = self.parameterAsRasterLayer(parameters, 'SAMPLE',
                                                    context)
        layers = self.parameterAsLayerList(parameters, 'LAYERS', context)

        letter_order = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

        raster_entries = []
        for idx, raster_layer in enumerate(layers):
            for band in range(1, raster_layer.bandCount() + 1):
                raster_entry = QgsRasterCalculatorEntry()
                raster_entry.raster = raster_layer
                raster_entry.bandNumber = band
                raster_entry.ref = "{}@{}".format(letter_order[idx], band)
                print(raster_entry.ref)
                raster_entries.append(raster_entry)

        #output_raster_path = os.path.join(tempfile.mkdtemp(),"OUTPUT.tif")
        #output_raster_path = parameters['OUTPUT']
        output_raster_path = self.parameterAsOutputLayer(
            parameters, 'OUTPUT', context)

        tc = QgsCoordinateTransformContext(
            QgsProject.instance().transformContext())

        print('extent', sample_raster.extent())
        print('widht', sample_raster.width())
        print('height', sample_raster.height())
        print(type(sample_raster.extent()))

        calc = QgsRasterCalculator(parameters['FORMULA'], output_raster_path,
                                   'GTiff', sample_raster.extent(),
                                   sample_raster.width(),
                                   sample_raster.height(), raster_entries, tc)

        print("COPERNICUSRASTERCALC",
              parameters['FORMULA'], output_raster_path, 'GTiff',
              sample_raster.extent(), sample_raster.width(),
              sample_raster.height(), raster_entries, tc)
        #return results

        if calc.processCalculation() == 0:
            rasterCalcError = "No error"
            results = {'ERROR': '', 'OUTPUT': output_raster_path}
        else:
            rasterCalcError = calc.lastError()
            results = {'OUTPUT': '', 'ERROR': rasterCalcError}

        return results
Esempio n. 17
0
    def calc_ndbi(self):

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

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

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

        expression = '({0} - {1})/({0} + {1})'.format(swir.ref, ir.ref)

        calc = QgsRasterCalculator(expression, self.output, "GTiff",
                                   self.nir.extent(), self.nir.width(),
                                   self.nir.height(), entries)
        calc.processCalculation()
Esempio n. 18
0
    def calc_gvmi(self):
        lyr1 = self.getNir()
        lyr2 = self.getB12()
        output = os.path.join(self.dlg.le_output.text(),"gvmi.tif")

        entries = []
        #nir band
        ras1 = QgsRasterCalculatorEntry()
        ras1.ref = 'nir'
        ras1.raster = lyr1
        ras1.bandNumber = 1
        entries.append(ras1)
        #b12 band#
        ras2 = QgsRasterCalculatorEntry()
        ras2.ref = 'b12'
        ras2.raster = lyr2
        ras2.bandNumber = 1
        entries.append( ras2 )
        calc = QgsRasterCalculator( '(("nir" + 0.1) - ("b12" + 0.02)) / (("nir" + 0.1) + ("b12" + 0.02))', \
        output, 'GTiff', lyr1.extent(), lyr1.width(), lyr1.height(), entries )
        calc.processCalculation()
        self.iface.messageBar().pushMessage("GVMI Output Created Successfully", level=Qgis.Success, duration=3)  
Esempio n. 19
0
    def calc_ndsi(self):
        lyr1 = self.getB11()
        lyr2 = self.getGreen()
        output = os.path.join(self.dlg.le_output.text(),"ndsi.tif")

        entries = []
        #b11 band
        ras1 = QgsRasterCalculatorEntry()
        ras1.ref = 'b11'
        ras1.raster = lyr1
        ras1.bandNumber = 1
        entries.append(ras1)
        #b12 band#
        ras2 = QgsRasterCalculatorEntry()
        ras2.ref = 'green'
        ras2.raster = lyr2
        ras2.bandNumber = 1
        entries.append( ras2 )
        calc = QgsRasterCalculator( '( "green" - "b11" ) / ( "green" + "b11" )', \
        output, 'GTiff', lyr1.extent(), lyr1.width(), lyr1.height(), entries )
        calc.processCalculation() 
        self.iface.messageBar().pushMessage("NDSI Output Created Successfully", level=Qgis.Success, duration=3)
Esempio n. 20
0
    def calc_gci(self):
        lyr1 = self.getNir()
        lyr2 = self.getGreen()
        output = os.path.join(self.dlg.le_output.text(),"gci.tif")

        entries = []
        #nir band
        ras1 = QgsRasterCalculatorEntry()
        ras1.ref = 'nir'
        ras1.raster = lyr1
        ras1.bandNumber = 1
        entries.append(ras1)
        #green band
        ras2 = QgsRasterCalculatorEntry()
        ras2.ref = 'green'
        ras2.raster = lyr2
        ras2.bandNumber = 1
        entries.append( ras2 )
        calc = QgsRasterCalculator( '"nir" / "green" - 1', \
        output, 'GTiff', lyr1.extent(), lyr1.width(), lyr1.height(), entries )
        calc.processCalculation()
        self.iface.messageBar().pushMessage("GCI Output Created Successfully", level=Qgis.Success, duration=3)
Esempio n. 21
0
    def calc_savi(self):
        lyr1 = self.getRed()
        lyr2 = self.getNir()
        output = os.path.join(self.dlg.le_output.text(),"savi.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 )
        calc = QgsRasterCalculator( '(("nir" - "red") / ("nir" + "red" + 0.5)) * (1 + 0.5)', \
        output, 'GTiff', lyr1.extent(), lyr1.width(), lyr1.height(), entries )
        calc.processCalculation()
        self.iface.messageBar().pushMessage("SAVI Output Created Successfully", level=Qgis.Success, duration=3)
Esempio n. 22
0
    def calc_a(self, dir_output, dir_D_10, dir_E0, temp_folder):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_D_10 = dir_D_10
        self.dir_E0 = dir_E0
        self.dir_output_temp = self.path + 'A.tif'

        entries = []

        D_10 = QgsRasterLayer(self.dir_D_10)
        ras = QgsRasterCalculatorEntry()
        ras.ref = '10 - D@1'
        ras.raster = D_10
        ras.bandNumber = 1
        entries.append(ras)

        E0 = QgsRasterLayer(self.dir_E0)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'E0@1'
        ras.raster = E0
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator('"10 - D@1" / "E0@1"',
                                       self.dir_output_temp, 'GTiff',
                                       E0.extent(), E0.width(), E0.height(),
                                       entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator('"10 - D@1" / "E0@1"', self.dir_output,
                                       'GTiff', E0.extent(), E0.width(),
                                       E0.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 23
0
    def calc_ndvi(self, dir_output, dir_bred, dir_bnir, temp_folder):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_bred = dir_bred
        self.dir_bnir = dir_bnir
        self.dir_output_temp = self.path + 'NDVI.tif'

        entries = []

        bred = QgsRasterLayer(self.dir_bred)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'bred@1'
        ras.raster = bred
        ras.bandNumber = 1
        entries.append(ras)

        bnir = QgsRasterLayer(self.dir_bnir)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'bnir@1'
        ras.raster = bnir
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator('(bnir@1 - bred@1)/(bnir@1 + bred@1)',
                                       self.dir_output_temp, 'GTiff',
                                       bnir.extent(), bnir.width(),
                                       bnir.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                '(band5@1 - band4@1)/(band5@1 + band4@1)', self.dir_output,
                'GTiff', bnir.extent(), bnir.width(), bnir.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 24
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
Esempio n. 25
0
    def do_base_calculation(self, band4, band8):
        """Calculates either the NDVI or MSAVI2 index, based on band 4 and 8

        Parameters
        ----------
        band4: QgsRasterLayer
        band8: QgsRasterLayer

        Returns
        -------

        """
        entries = []
        ras4 = QgsRasterCalculatorEntry()
        ras4.ref = 'ras@4'
        ras4.raster = band4
        ras4.bandNumber = 1
        entries.append(ras4)

        ras8 = QgsRasterCalculatorEntry()
        ras8.ref = 'ras@8'
        ras8.raster = band8
        ras8.bandNumber = 1
        entries.append(ras8)

        if self.dlg.RBNdviIndex.isChecked():
            calc = QgsRasterCalculator('(ras@8 - ras@4) / (ras@4+ras@8)*100',
                                       self.path + "raster_output.tif",
                                       'GTiff', band4.extent(), band4.width(),
                                       band4.height(), entries)
            calc.processCalculation()
        elif self.dlg.RBMsavi2Index.isChecked():
            calc = QgsRasterCalculator(
                '(2 * ras@8 + 1 - sqrt((2 * ras@8 + 1) ^ 2 - 8 * (ras@8 - ras@4))) / 2*100',
                self.path + "raster_output.tif", 'GTiff', band4.extent(),
                band4.width(), band4.height(), entries)
            calc.processCalculation()
Esempio n. 26
0
    def executeCalculations(self):
        for root, dirs, files in os.walk(self.rootDir):
            for dir in dirs:
                newDir = self.rootDir + '/' + dir
                print("------------------------------")
                print("SCANNING DIRECTORY: " + newDir)
                #Variables needed for raster calculation
                rasIndex = 1
                ras = []
                entries = []
                rlayers = []
                for subRoot, subDirs, subFiles in os.walk(newDir):
                    #print("Subfiles of directory: " + str(subFiles))
                    for fileName in subFiles:
                        if (fileName.endswith(".tif")
                                and fileName[len(fileName) - 5] != "A"
                                and fileName[len(fileName) - 7] != "B"):
                            print("Evaluating SRB TIF file of band " +
                                  fileName[len(fileName) - 5] + ": " +
                                  fileName)

                            #Figure out properties of file
                            tifFile = newDir + '/' + fileName  # + ".tif"
                            bandNumber = fileName[len(fileName) - 5]

                            #Create a raster layer
                            rlayer = QgsRasterLayer(tifFile,
                                                    "Band" + bandNumber)
                            if not rlayer.isValid():
                                print("Layer failed to load!")
                                continue
                            rlayers.append(rlayer)

                            #Create a raster calculator entry
                            ref = 'lyr@' + str(rasIndex)
                            ras = QgsRasterCalculatorEntry()
                            ras.ref = ref
                            ras.raster = rlayer
                            ras.bandNumber = 1
                            entries.append(ras)
                            rasIndex += 1

                if (len(rlayers) > 0 and len(entries) > 0):
                    #Obtain desired output path
                    outDir = self.obtainOutDir(dir)

                    #Calculate average for this directory
                    self.calculateAvgAndOutput(rlayers, entries, outDir)
Esempio n. 27
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)
Esempio n. 28
0
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 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 qgs_map_calculator(self, rasterLayer, temp_path, red, green, blue):
        entries = []
        # Define 3 bands

        rasterFilterQgs = '( temp@1 = ' + str(red) + 'AND temp@2 = ' + str(
            green) + 'AND temp@3 = ' + str(blue) + ') * 1'
        for i in range(3):
            ent = QgsRasterCalculatorEntry()
            ent.ref = 'temp@' + str(i + 1)
            ent.raster = rasterLayer
            ent.bandNumber = i + 1
            entries.append(ent)
        file = temp_path + '/temp_qgs.tif'
        calc = QgsRasterCalculator(rasterFilterQgs, file, 'GTiff',
                                   rasterLayer.extent(), rasterLayer.width(),
                                   rasterLayer.height(), entries)
        calc.processCalculation()
        return file
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. 32
0
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. 33
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)
Esempio n. 34
0
    def processSlopeHighpassAlgorithm(self, INPUT_CUTOFF, INPUT_SLOPE,
                                      INPUT_EXTENT, OUTPUT_FILE, feedback):
        if (os.path.isfile(OUTPUT_FILE)):
            return 0

        ras = QgsRasterCalculatorEntry()
        ras.ref = 'slope@1'
        ras.raster = INPUT_SLOPE
        ras.bandNumber = 1

        entries = [ras]

        calc = QgsRasterCalculator('slope@1 >= {}'.format(INPUT_CUTOFF),
                                   OUTPUT_FILE, 'GTiff', INPUT_EXTENT,
                                   ras.raster.width(), ras.raster.height(),
                                   entries)

        return calc.processCalculation()
Esempio n. 35
0
def raster_calculator_from_config(qgs_raster_layers, expression_alias, expression_template, qgs_raster_base_layer, output_raster, band=1):
    """
    Apply raster calculator using layers name.

    :param qgs_raster_layers: A list with QgsRasterLayer.
    :param expression_alias: A list with expression alias. Example: ['v', 's', 'a', 'r', 'e'].
    :param expression_template: A string with expression template. Example: '1 + (100 * "{v}") + (30 * "{s}")+ (10 * "{a}") + (5 * "{r}") + (2 * "{e}")'.
    :param qgs_raster_base_layer: A QgsRasterLayer to extract geotransform.
    :param output_raster: A string with output raster path.
    :param band: A int with band number to perform raster calculator.
    :return: A string with status message.
    """
    if len(qgs_raster_layers) != len(expression_alias):
        raise ValueError(u'Layers count({}) differ from expression alias ({})'.format(len(qgs_raster_layers), len(expression_alias)))

    entries = []
    alias = {}
    elements_idx = 0

    if not qgs_raster_base_layer or not qgs_raster_base_layer.isValid():
        raise ValueError(u'Base layer "{}" does not exist or is not valid'.format(qgs_raster_base_layer))

    for layer in qgs_raster_layers:
        layer_name = layer.name()
        if not layer.isValid():
            result = 6
            msg = u'Layer "{}" not valid.'.format(layer_name)
            return result, msg
        else:
            ref = layer_name + unicode('@' + str(band))
            entry = QgsRasterCalculatorEntry()
            entry.ref = ref
            entry.raster = layer
            entry.bandNumber = band
            entries.append(entry)

            alias[expression_alias[elements_idx]] = ref
            elements_idx += 1

    expression = expression_template.format(**alias)
    __logger.info(u'Running raster calculator with expression: {}...'.format(expression))
    return raster_calculator(entries, qgs_raster_base_layer, output_raster, expression)
Esempio n. 36
0
    def calc_11_ckecil(self, dir_output, dir_pv, temp_folder,
                       val_tir2emissivitys, val_tir2emissivityv,
                       val_geometrical):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_pv = dir_pv
        self.dir_output_temp = self.path + '11 - c kecil.tif'

        self.val_tir2emissivitys = val_tir2emissivitys
        self.val_tir2emissivityv = val_tir2emissivityv
        self.val_geometrical = val_geometrical

        entries = []

        pv = QgsRasterLayer(self.dir_pv)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'Pv@1'
        ras.raster = pv
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator(
                '( 1 - ' + str(self.val_tir2emissivitys) + ' ) * ' +
                str(self.val_tir2emissivityv) + ' * ' +
                str(self.val_geometrical) + ' * ( 1 - "Pv@1" )',
                self.dir_output_temp, 'GTiff', pv.extent(), pv.width(),
                pv.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                '( 1 - ' + str(self.val_tir2emissivitys) + ' ) * ' +
                str(self.val_tir2emissivityv) + ' * ' +
                str(self.val_geometrical) + ' * ( 1 - "Pv@1" )',
                self.dir_output, 'GTiff', pv.extent(), pv.width(), pv.height(),
                entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 37
0
    def calc_pv(self, dir_output, dir_ndvi, temp_folder, val_ndvis, val_ndviv):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_ndvi = dir_ndvi
        self.dir_output_temp = self.path + 'Pv.tif'

        self.val_ndvis = val_ndvis
        self.val_ndviv = val_ndviv

        entries = []

        ndvi = QgsRasterLayer(self.dir_ndvi)
        ras = QgsRasterCalculatorEntry()
        ras.ref = 'ndvi@1'
        ras.raster = ndvi
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator(
                '( ( "ndvi@1" - ' + str(self.val_ndvis) + ' ) / ( ' +
                str(self.val_ndviv) + ' - ' + str(self.val_ndvis) +
                ' ) ) * ( ( "ndvi@1" - ' + str(self.val_ndvis) + ' ) / ( ' +
                str(self.val_ndviv) + ' - ' + str(self.val_ndvis) + ' ) )',
                self.dir_output_temp, 'GTiff', ndvi.extent(), ndvi.width(),
                ndvi.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                '( ( "ndvi@1" - ' + str(self.val_ndvis) + ' ) / ( ' +
                str(self.val_ndviv) + ' - ' + str(self.val_ndvis) +
                ' ) ) * ( ( "ndvi@1" - ' + str(self.val_ndvis) + ' ) / ( ' +
                str(self.val_ndviv) + ' - ' + str(self.val_ndvis) + ' ) )',
                self.dir_output, 'GTiff', ndvi.extent(), ndvi.width(),
                ndvi.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 38
0
    def calc_11_bt(self, dir_output, dir_toa_11, temp_folder, val_l_tir2_k1,
                   val_l_tir2_k2):
        self.dir_output = dir_output
        self.path = os.path.join(str(Path(dir_output).parent), 'temp_folder',
                                 '')

        self.temp_folder = temp_folder
        self.dir_toa_11 = dir_toa_11
        self.dir_output_temp = self.path + '11 - BT.tif'

        self.val_l_tir2_k1 = val_l_tir2_k1
        self.val_l_tir2_k2 = val_l_tir2_k2

        entries = []

        toa_11 = QgsRasterLayer(self.dir_toa_11)
        ras = QgsRasterCalculatorEntry()
        ras.ref = '10 - TOA@1'
        ras.raster = toa_11
        ras.bandNumber = 1
        entries.append(ras)

        if self.temp_folder == 'yes':
            calc = QgsRasterCalculator(
                str(self.val_l_tir2_k2) + ' / ln ( ( ' +
                str(self.val_l_tir2_k1) + ' / "10 - TOA@1" ) + 1) ',
                self.dir_output_temp, 'GTiff', toa_11.extent(), toa_11.width(),
                toa_11.height(), entries)
            calc.processCalculation()
        elif self.temp_folder == 'no':
            calc = QgsRasterCalculator(
                str(self.val_l_tir2_k2) + ' / ln ( ( ' +
                str(self.val_l_tir2_k1) + ' / "10 - TOA@1" ) + 1) ',
                self.dir_output, 'GTiff', toa_11.extent(), toa_11.width(),
                toa_11.height(), entries)
            calc.processCalculation()
            iface.addRasterLayer(str(self.dir_output))
Esempio n. 39
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. 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 = {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}
Esempio n. 41
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. 42
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()