def runProcessingNativeIntersect(inputLayer, overlayLayer): processing.algorithmHelp("native:intersection") rez = processing.run( "native:intersection", { 'INPUT': inputLayer, 'OVERLAY': overlayLayer, 'INPUT_FIELDS': [], 'OVERLAY_FIELDS': [], 'OVERLAY_FIELDS_PREFIX': '', 'OUTPUT': 'TEMPORARY_OUTPUT' }) return rez['OUTPUT']
def runProcessingNativeIntersectSkipInvalid(inputLayer, overlayLayer): context = dataobjects.createContext() context.setInvalidGeometryCheck(QgsFeatureRequest.GeometrySkipInvalid) processing.algorithmHelp("native:intersection") return processing.run("native:intersection", { 'INPUT': inputLayer, 'OVERLAY': overlayLayer, 'INPUT_FIELDS': [], 'OVERLAY_FIELDS': [], 'OVERLAY_FIELDS_PREFIX': '', 'OUTPUT': 'TEMPORARY_OUTPUT' }, context=context)
def run_qgis_algorithm(algorithm_id, algorithm_parameters): import sys import qgis.utils from qgis.core import ( QgsApplication, QgsProcessingFeedback, QgsVectorLayer, QgsProcessingProvider, QgsProcessingRegistry, ) from qgis.analysis import QgsNativeAlgorithms # See https://gis.stackexchange.com/a/155852/4972 for details about the prefix QgsApplication.setPrefixPath('/usr', True) qgs = QgsApplication([], False) qgs.initQgis() # # Append the path where processing plugin can be found sys.path.append('/usr/share/qgis/python/plugins/') import processing from processing.core.Processing import Processing Processing.initialize() QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) print('You are using QGIS version: %s ', qgis.utils.Qgis.QGIS_VERSION) print('You are running: %s ', algorithm_id) provider = NDVIProvider() provider.loadAlgorithms() QgsApplication.processingRegistry().addProvider(provider) # Checking if the algorithm is added # last_alg = QgsApplication.processingRegistry().algorithms()[-1] # print(last_alg.name()) # print(last_alg.id()) # last_alg = QgsApplication.processingRegistry().algorithms()[-2] # print(last_alg.name()) # print(last_alg.id()) # Show help for the algorithm processing.algorithmHelp(algorithm_id) print('Running algorithm') result = processing.run(algorithm_id, algorithm_parameters) print('### Result:') print(result) qgs.exitQgis() return result
def runAlgorithm(algOrName, onFinish, *args, **kwargs): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = QgsApplication.processingRegistry().algorithmById(algOrName) if alg is None: # fix_print_with_import print('Error: Algorithm not found\n') QgsMessageLog.logMessage(Processing.tr('Error: Algorithm {0} not found\n').format(algOrName), Processing.tr("Processing")) return # hack - remove when getCopy is removed provider = alg.provider() alg = alg.getCopy() #hack pt2 alg.setProvider(provider) if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in list(args[0].items()): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue # fix_print_with_import print('Error: Wrong parameter value %s for parameter %s.' % (value, name)) QgsMessageLog.logMessage( Processing.tr('Error: Wrong parameter value {0} for parameter {1}.').format(value, name), Processing.tr("Processing")) QgsMessageLog.logMessage(Processing.tr('Error in {0}. Wrong parameter value {1} for parameter {2}.').format( alg.name(), value, name ), Processing.tr("Processing"), QgsMessageLog.CRITICAL ) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setDefaultValue(): # fix_print_with_import print('Error: Missing parameter value for parameter %s.' % param.name) QgsMessageLog.logMessage( Processing.tr('Error: Missing parameter value for parameter {0}.').format(param.name), Processing.tr("Processing")) return else: if len(args) != alg.getVisibleParametersCount() + alg.getVisibleOutputsCount(): # fix_print_with_import print('Error: Wrong number of parameters') QgsMessageLog.logMessage(Processing.tr('Error: Wrong number of parameters'), Processing.tr("Processing")) processing.algorithmHelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): # fix_print_with_import print('Error: Wrong parameter value: ' + str(args[i])) QgsMessageLog.logMessage(Processing.tr('Error: Wrong parameter value: ') + str(args[i]), Processing.tr("Processing")) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): # fix_print_with_import print('Error: Wrong output value: ' + str(args[i])) QgsMessageLog.logMessage(Processing.tr('Error: Wrong output value: ') + str(args[i]), Processing.tr("Processing")) return i = i + 1 context = None if kwargs is not None and 'context' in list(kwargs.keys()): context = kwargs["context"] else: context = dataobjects.createContext() msg = alg._checkParameterValuesBeforeExecuting(context) if msg: # fix_print_with_import print('Unable to execute algorithm\n' + str(msg)) QgsMessageLog.logMessage(Processing.tr('Unable to execute algorithm\n{0}').format(msg), Processing.tr("Processing")) return if not alg.checkInputCRS(context): print('Warning: Not all input layers use the same CRS.\n' + 'This can cause unexpected results.') QgsMessageLog.logMessage( Processing.tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'), Processing.tr("Processing")) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. overrideCursor = False if iface is not None: cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True feedback = None if kwargs is not None and "feedback" in list(kwargs.keys()): feedback = kwargs["feedback"] elif iface is not None: feedback = MessageBarProgress(alg.displayName()) ret = execute(alg, context, feedback) if ret: if onFinish is not None: onFinish(alg, context, feedback) else: QgsMessageLog.logMessage(Processing.tr("There were errors executing the algorithm."), Processing.tr("Processing")) if overrideCursor: QApplication.restoreOverrideCursor() if isinstance(feedback, MessageBarProgress): feedback.close() return alg
def runAlgorithm(algOrName, onFinish, *args, **kwargs): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = QgsApplication.processingRegistry().algorithmById(algOrName) if alg is None: # fix_print_with_import print('Error: Algorithm not found\n') QgsMessageLog.logMessage(Processing.tr('Error: Algorithm {0} not found\n').format(algOrName), Processing.tr("Processing")) return alg = alg.getCopy() if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in list(args[0].items()): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue # fix_print_with_import print('Error: Wrong parameter value %s for parameter %s.' % (value, name)) QgsMessageLog.logMessage( Processing.tr('Error: Wrong parameter value {0} for parameter {1}.').format(value, name), Processing.tr("Processing")) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing.tr('Error in {0}. Wrong parameter value {1} for parameter {2}.').format( alg.name(), value, name ) ) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setDefaultValue(): # fix_print_with_import print('Error: Missing parameter value for parameter %s.' % param.name) QgsMessageLog.logMessage( Processing.tr('Error: Missing parameter value for parameter {0}.').format(param.name), Processing.tr("Processing")) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing.tr('Error in {0}. Missing parameter value for parameter {1}.').format( alg.name(), param.name) ) return else: if len(args) != alg.getVisibleParametersCount() + alg.getVisibleOutputsCount(): # fix_print_with_import print('Error: Wrong number of parameters') QgsMessageLog.logMessage(Processing.tr('Error: Wrong number of parameters'), Processing.tr("Processing")) processing.algorithmHelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): # fix_print_with_import print('Error: Wrong parameter value: ' + str(args[i])) QgsMessageLog.logMessage(Processing.tr('Error: Wrong parameter value: ') + str(args[i]), Processing.tr("Processing")) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): # fix_print_with_import print('Error: Wrong output value: ' + str(args[i])) QgsMessageLog.logMessage(Processing.tr('Error: Wrong output value: ') + str(args[i]), Processing.tr("Processing")) return i = i + 1 msg = alg._checkParameterValuesBeforeExecuting() if msg: # fix_print_with_import print('Unable to execute algorithm\n' + str(msg)) QgsMessageLog.logMessage(Processing.tr('Unable to execute algorithm\n{0}').format(msg), Processing.tr("Processing")) return if not alg.checkInputCRS(): print('Warning: Not all input layers use the same CRS.\n' + 'This can cause unexpected results.') QgsMessageLog.logMessage( Processing.tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'), Processing.tr("Processing")) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. overrideCursor = False if iface is not None: cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True feedback = None if kwargs is not None and "feedback" in list(kwargs.keys()): feedback = kwargs["feedback"] elif iface is not None: feedback = MessageBarProgress(alg.displayName()) ret = execute(alg, feedback) if ret: if onFinish is not None: onFinish(alg, feedback) else: QgsMessageLog.logMessage(Processing.tr("There were errors executing the algorithm."), Processing.tr("Processing")) if overrideCursor: QApplication.restoreOverrideCursor() if isinstance(feedback, MessageBarProgress): feedback.close() return alg
def runAlgorithm(algOrName, onFinish, *args, **kwargs): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = QgsApplication.processingRegistry().algorithmById(algOrName) if alg is None: # fix_print_with_import print('Error: Algorithm not found\n') QgsMessageLog.logMessage(Processing.tr('Error: Algorithm {0} not found\n').format(algOrName), Processing.tr("Processing")) return parameters = {} if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. for (name, value) in list(args[0].items()): param = alg.parameterDefinition(name) if param: parameters[param.name()] = value continue # fix_print_with_import print('Error: Wrong parameter value %s for parameter %s.' % (value, name)) QgsMessageLog.logMessage( Processing.tr('Error: Wrong parameter value {0} for parameter {1}.').format(value, name), Processing.tr("Processing")) QgsMessageLog.logMessage(Processing.tr('Error in {0}. Wrong parameter value {1} for parameter {2}.').format( alg.name(), value, name ), Processing.tr("Processing"), QgsMessageLog.CRITICAL ) return # check for any manadatory parameters which were not specified for param in alg.parameterDefinitions(): if param.name() not in parameters: if not param.flags() & QgsProcessingParameterDefinition.FlagOptional: # fix_print_with_import print('Error: Missing parameter value for parameter %s.' % param.name()) QgsMessageLog.logMessage( Processing.tr('Error: Missing parameter value for parameter {0}.').format(param.name()), Processing.tr("Processing")) return else: if len(args) != alg.countVisibleParameters(): # fix_print_with_import print('Error: Wrong number of parameters') QgsMessageLog.logMessage(Processing.tr('Error: Wrong number of parameters'), Processing.tr("Processing")) processing.algorithmHelp(algOrName) return i = 0 for param in alg.parameterDefinitions(): if not param.flags() & QgsProcessingParameterDefinition.FlagHidden: if not True: # TODO param.setValue(args[i]): # fix_print_with_import print('Error: Wrong parameter value: ' + str(args[i])) QgsMessageLog.logMessage(Processing.tr('Error: Wrong parameter value: ') + str(args[i]), Processing.tr("Processing")) return else: parameters[param.name()] = args[i] i = i + 1 for output in alg.outputs: if not output.flags() & QgsProcessingParameterDefinition.FlagHidden: if not output.setValue(args[i]): # fix_print_with_import print('Error: Wrong output value: ' + str(args[i])) QgsMessageLog.logMessage(Processing.tr('Error: Wrong output value: ') + str(args[i]), Processing.tr("Processing")) return i = i + 1 context = None if kwargs is not None and 'context' in list(kwargs.keys()): context = kwargs["context"] else: context = dataobjects.createContext() ok, msg = alg.checkParameterValues(parameters, context) if not ok: # fix_print_with_import print('Unable to execute algorithm\n' + str(msg)) QgsMessageLog.logMessage(Processing.tr('Unable to execute algorithm\n{0}').format(msg), Processing.tr("Processing")) return if not alg.validateInputCrs(parameters, context): print('Warning: Not all input layers use the same CRS.\n' + 'This can cause unexpected results.') QgsMessageLog.logMessage( Processing.tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'), Processing.tr("Processing")) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. overrideCursor = False if iface is not None: cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True feedback = None if kwargs is not None and "feedback" in list(kwargs.keys()): feedback = kwargs["feedback"] elif iface is not None: feedback = MessageBarProgress(alg.displayName()) ret, results = execute(alg, parameters, context, feedback) if ret: if onFinish is not None: onFinish(alg, context, feedback) else: QgsMessageLog.logMessage(Processing.tr("There were errors executing the algorithm."), Processing.tr("Processing")) if overrideCursor: QApplication.restoreOverrideCursor() if isinstance(feedback, MessageBarProgress): feedback.close() return results
def despeckeleGamma(dlg, conf, dir_raster_src, dir_dest, rasterName, gammaName, extension_input_raster): # Calcul despeckele option Gamma li = layerList() messInfo(dlg, "Calcul du despeckele Gamma.") messInfo(dlg, "") rasterPath = dir_raster_src + os.sep + rasterName + extension_input_raster gammaPath = dir_dest + os.sep + gammaName + EXT_RASTER radius = dlg.spinBoxRadius.value() nb_looks = dlg.doubleSpinBoxLooks.value() # Suppression du fichier de sortie si il existe if os.path.exists(gammaPath): try: os.remove(gammaPath) except: QMessageBox.information( None, "Attention !!!", gammaPath + " ne peut pas être effacé. Vérifiez que le fichier n'est pas verrouillé par un autre utilisateur ou que le fichier peut être effacé manuellement (droits d'écriture sur le répertoire).", QMessageBox.Ok, QMessageBox.NoButton) messErreur(dlg, gammaPath + " ne peut pas être effacé.") return None # Calcul if conf.rbOTB.isChecked(): # Despeckele Gamma par OTB try: #processing.algorithmHelp("otb:Despeckle") #processing.runalg('otb:despecklegammamap', rasterPath, '128', 0, radius, nb_looks, gammaPath) parameters = { "in": rasterPath, "out": gammaPath, "filter": 'gammamap', "filter.gammamap.rad": radius, "filter.gammamap.nblooks": nb_looks, "outputpixeltype": 2, "ram": 128 } processing.run('otb:Despeckle', parameters) except: messErreur(dlg, "Erreur de traitement sur otb:Despeckle Gamma.") return None # Fin OTB else: # Despeckele Gamma par GRASS entries = [] raster = li[rasterName] extent = raster.extent() height = raster.height() width = raster.width() try: # En attente de faire fonctionner le despeckle avec GRASS !!! print("DEBUG lancement grass:despeckle Gamma") processing.algorithmHelp("grass:i.despeckle") #processing.runalg('grass:i.despeckle', rasterPath, 'gamma', radius, nb_looks, gammaPath) print("DEBUG fin grass:despeckle Gamma") except: messErreur(dlg, "Erreur de traitement sur grass:despeckle.") return None # Fin GRASS if os.path.exists(gammaPath): gamma = QgsRasterLayer(gammaPath, gammaName) else: QMessageBox.information( None, "Attention !!!", gammaPath + " n'a pas été créé. Vérifiez que le fichier n'est pas verrouillé par un autre utilisateur ou que le fichier peut être effacé manuellement (droits d'écriture sur le répertoire).", QMessageBox.Ok, QMessageBox.NoButton) messErreur(dlg, gammaPath + " n'a pas été créé.") return None if not gamma.isValid(): messErreur(dlg, gammaPath + " ne peut pas être chargé.") return None return gamma
def computeNdwi2(dlg, conf, dir_raster_src, dir_dest, rasterName, ndwi2Name, extension_input_raster): # Calcul despeckele indice Ndwi2 li = layerList() messInfo(dlg, "Calcul du NDWI2.") messInfo(dlg, "") rasterPath = dir_raster_src + os.sep + rasterName + extension_input_raster ndwi2Path = dir_dest + os.sep + ndwi2Name + EXT_RASTER # Test si c'est une image multibande cols, rows, bands = getGeometryImage(rasterPath) if bands < 4: QMessageBox.information( None, "Attention !!!", ndwi2Path + " ne peut pas être créé. L'image rasterraster d'entrée n'a pas un nombre de bande suffisant.", QMessageBox.Ok, QMessageBox.NoButton) messErreur(dlg, ndwi2Path + " ne peut pas être créé.") return None # Selection des bandes pour le calcul du NDWI2 num_channel_green = 0 num_channel_nir = 0 d = conf.channelOrderDic key = "Green" if key in conf.channelOrderDic.keys(): num_channel_green = int(conf.channelOrderDic[key]) key = "NIR" if key in conf.channelOrderDic.keys(): num_channel_nir = int(conf.channelOrderDic[key]) if (num_channel_green == 0 or num_channel_nir == 0): QMessageBox.information( None, "Attention !!!", ndviPath + " ne peut pas être créé. NDVI needs Green and NIR channels to be computed).", QMessageBox.Ok, QMessageBox.NoButton) messErreur(dlg, ndviPath + " ne peut pas être créé.") return None # Suppression du fichier de sortie si il existe if os.path.exists(ndwi2Path): try: os.remove(ndwi2Path) except: QMessageBox.information( None, "Attention !!!", ndwi2Path + " ne peut pas être effacé. Vérifiez que le fichier n'est pas verrouillé par un autre utilisateur ou que le fichier peut être effacé manuellement (droits d'écriture sur le répertoire).", QMessageBox.Ok, QMessageBox.NoButton) messErreur(dlg, ndwi2Path + " ne peut pas être effacé.") return None # Calcul if conf.rbOTB.isChecked(): # Calculatrice raster OTB try: expression = '(im1b%s - im1b%s)/(im1b%s + im1b%s)' % ( str(num_channel_green), str(num_channel_nir), str(num_channel_green), str(num_channel_nir)) processing.algorithmHelp("otb:BandMath") #processing.runalg('otb:bandmath', rasterPath, '128',expression, ndwi2Path) parameters = { "il": [rasterPath], "out": ndwi2Path, "exp": expression, "outputpixeltype": 2, "ram": 128 } processing.run('otb:BandMath', parameters) except: messErreur(dlg, "Erreur de traitement sur otb:BandMath ndwi2.") return None # Fin OTB else: # Calculatrice raster QGIS entries = [] raster = li[rasterName] extent = raster.extent() height = raster.height() width = raster.width() b_green = QgsRasterCalculatorEntry() b_green.ref = 'b@%s' % (str(num_channel_green)) b_green.raster = raster b_green.bandNumber = num_channel_green entries.append(b_green) b_nir = QgsRasterCalculatorEntry() b_nir.ref = 'b@%s' % (str(num_channel_nir)) b_nir.raster = raster b_nir.bandNumber = num_channel_nir entries.append(b_nir) expression = '(b@%s - b@%s)/(b@%s + b@%s)' % ( str(num_channel_green), str(num_channel_nir), str(num_channel_green), str(num_channel_nir)) calc = QgsRasterCalculator(expression, ndwi2Path, FORMAT_IMA, extent, width, height, entries) ret = calc.processCalculation() if ret != 0: QMessageBox.information( None, "Attention !!!", " Erreur d'exécution, cela peut être du à une insuffisance mémoire, image trop volumineuse.", QMessageBox.Ok, QMessageBox.NoButton) messErreur(dlg, "Erreur lors du lancement de QgsRasterCalculator.") return None # Fin QGIS if os.path.exists(ndwi2Path): ndwi2 = QgsRasterLayer(ndwi2Path, ndwi2Name) else: QMessageBox.information( None, "Attention !!!", ndwi2Path + " n'a pas été créé. Vérifiez que le fichier n'est pas verrouillé par un autre utilisateur ou que le fichier peut être effacé manuellement (droits d'écriture sur le répertoire).", QMessageBox.Ok, QMessageBox.NoButton) messErreur(dlg, ndwi2Path + " n'a pas été créé.") return None if not ndwi2.isValid(): messErreur(dlg, ndwi2Path + " ne peut pas être chargé.") return None return ndwi2
""" import sys from qgis.core import (QgsApplication, QgsProcessingFeedback, QgsVectorLayer) # See https://gis.stackexchange.com/a/155852/4972 for details about the prefix QgsApplication.setPrefixPath('C:/OSGeo4W64/apps/', True) qgs = QgsApplication([], False) qgs.initQgis() # Append the path where processing plugin can be found sys.path.append('qgis\python\plugins') import processing from processing.core.Processing import Processing Processing.initialize() ##layer2 = QgsVectorLayer('/path/to/geodata/lines_2.shp', 'layer 2', 'ogr') # You can see what parameters are needed by the algorithm processing.algorithmHelp("qgis:distancetonearesthub") '''params = { 'INPUT' : layer1, 'OVERLAY' : layer2, 'OUTPUT' : '/path/to/output_layer.gpkg|layername=output' } feedback = QgsProcessingFeedback() res = processing.run('qgis:union', params, feedback=feedback) res['OUTPUT'] # Access your output layer'''
def runAlgorithm(algOrName, onFinish, *args, **kwargs): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = QgsApplication.processingRegistry().algorithmById(algOrName) if alg is None: # fix_print_with_import print('Error: Algorithm not found\n') QgsMessageLog.logMessage( Processing.tr('Error: Algorithm {0} not found\n').format( algOrName), Processing.tr("Processing")) return parameters = {} if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. for (name, value) in list(args[0].items()): param = alg.parameterDefinition(name) if param: parameters[param.name()] = value continue # fix_print_with_import print('Error: Wrong parameter value %s for parameter %s.' % (value, name)) QgsMessageLog.logMessage( Processing.tr( 'Error: Wrong parameter value {0} for parameter {1}.'). format(value, name), Processing.tr("Processing")) QgsMessageLog.logMessage( Processing. tr('Error in {0}. Wrong parameter value {1} for parameter {2}.' ).format(alg.name(), value, name), Processing.tr("Processing"), QgsMessageLog.CRITICAL) return # check for any manadatory parameters which were not specified for param in alg.parameterDefinitions(): if param.name() not in parameters: if not param.flags( ) & QgsProcessingParameterDefinition.FlagOptional: # fix_print_with_import print( 'Error: Missing parameter value for parameter %s.' % param.name()) QgsMessageLog.logMessage( Processing. tr('Error: Missing parameter value for parameter {0}.' ).format(param.name()), Processing.tr("Processing")) return else: if len(args) != alg.countVisibleParameters(): # fix_print_with_import print('Error: Wrong number of parameters') QgsMessageLog.logMessage( Processing.tr('Error: Wrong number of parameters'), Processing.tr("Processing")) processing.algorithmHelp(algOrName) return i = 0 for param in alg.parameterDefinitions(): if not param.flags( ) & QgsProcessingParameterDefinition.FlagHidden: if not True: # TODO param.setValue(args[i]): # fix_print_with_import print('Error: Wrong parameter value: ' + str(args[i])) QgsMessageLog.logMessage( Processing.tr('Error: Wrong parameter value: ') + str(args[i]), Processing.tr("Processing")) return else: parameters[param.name()] = args[i] i = i + 1 for output in alg.outputs: if not output.flags( ) & QgsProcessingParameterDefinition.FlagHidden: if not output.setValue(args[i]): # fix_print_with_import print('Error: Wrong output value: ' + str(args[i])) QgsMessageLog.logMessage( Processing.tr('Error: Wrong output value: ') + str(args[i]), Processing.tr("Processing")) return i = i + 1 context = None if kwargs is not None and 'context' in list(kwargs.keys()): context = kwargs["context"] else: context = dataobjects.createContext() ok, msg = alg.checkParameterValues(parameters, context) if not ok: # fix_print_with_import print('Unable to execute algorithm\n' + str(msg)) QgsMessageLog.logMessage( Processing.tr('Unable to execute algorithm\n{0}').format(msg), Processing.tr("Processing")) return if not alg.validateInputCrs(parameters, context): print('Warning: Not all input layers use the same CRS.\n' + 'This can cause unexpected results.') QgsMessageLog.logMessage( Processing. tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.' ), Processing.tr("Processing")) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. overrideCursor = False if iface is not None: cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True feedback = None if kwargs is not None and "feedback" in list(kwargs.keys()): feedback = kwargs["feedback"] elif iface is not None: feedback = MessageBarProgress(alg.displayName()) ret, results = execute(alg, parameters, context, feedback) if ret: if onFinish is not None: onFinish(alg, context, feedback) else: QgsMessageLog.logMessage( Processing.tr("There were errors executing the algorithm."), Processing.tr("Processing")) if overrideCursor: QApplication.restoreOverrideCursor() if isinstance(feedback, MessageBarProgress): feedback.close() return results
def exportRaster(layer, count, layersFolder, feedback, iface, matchCRS): feedback.showFeedback("Exporting %s to PNG..." % layer.name()) name_ts = (safeName(layer.name()) + unicode(count) + unicode(int(time.time()))) # We need to create a new file to export style piped_file = os.path.join(tempfile.gettempdir(), name_ts + '_piped.tif') piped_extent = layer.extent() piped_width = layer.height() piped_height = layer.width() piped_crs = layer.crs() piped_renderer = layer.renderer() piped_provider = layer.dataProvider() pipe = QgsRasterPipe() pipe.set(piped_provider.clone()) pipe.set(piped_renderer.clone()) file_writer = QgsRasterFileWriter(piped_file) file_writer.writeRaster(pipe, piped_height, -1, piped_extent, piped_crs) # Export layer as PNG out_raster = os.path.join(layersFolder, safeName(layer.name()) + "_" + unicode(count) + ".png") projectCRS = iface.mapCanvas().mapSettings().destinationCrs() if not (matchCRS and layer.crs() == projectCRS): # Extent of the layer in EPSG:3857 crsSrc = layer.crs() crsDest = QgsCoordinateReferenceSystem(3857) try: xform = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance()) except: xform = QgsCoordinateTransform(crsSrc, crsDest) extentRep = xform.transformBoundingBox(layer.extent()) extentRepNew = ','.join([unicode(extentRep.xMinimum()), unicode(extentRep.xMaximum()), unicode(extentRep.yMinimum()), unicode(extentRep.yMaximum())]) # Reproject in 3857 piped_3857 = os.path.join(tempfile.gettempdir(), name_ts + '_piped_3857.tif') qgis_version = Qgis.QGIS_VERSION old_stdout = sys.stdout sys.stdout = mystdout = StringIO() try: processing.algorithmHelp("gdal:warpreproject") except: pass sys.stdout = old_stdout params = { "INPUT": piped_file, "SOURCE_CRS": layer.crs().authid(), "TARGET_CRS": "EPSG:3857", "NODATA": 0, "TARGET_RESOLUTION": 0, "RESAMPLING": 2, "TARGET_EXTENT": extentRepNew, "EXT_CRS": "EPSG:3857", "TARGET_EXTENT_CRS": "EPSG:3857", "DATA_TYPE": 0, "COMPRESS": 4, "JPEGCOMPRESSION": 75, "ZLEVEL": 6, "PREDICTOR": 1, "TILED": False, "BIGTIFF": 0, "TFW": False, "MULTITHREADING": False, "COPY_SUBDATASETS": False, "EXTRA": "", "OUTPUT": piped_3857 } warpArgs = {} lines = mystdout.getvalue() for count, line in enumerate(lines.split("\n")): if count != 0 and ":" in line: try: k = line.split(":")[0] warpArgs[k] = params[k] except: pass try: processing.run("gdal:warpreproject", warpArgs) except: shutil.copyfile(piped_file, piped_3857) try: processing.run("gdal:translate", {"INPUT": piped_3857, "OUTSIZE": 100, "OUTSIZE_PERC": True, "NODATA": 0, "EXPAND": 0, "TARGET_CRS": "", "PROJWIN": extentRepNew, "SDS": False, "DATA_TYPE": 0, "COMPRESS": 4, "JPEGCOMPRESSION": 75, "ZLEVEL": 6, "PREDICTOR": 1, "TILED": False, "BIGTIFF": 0, "TFW": False, "COPY_SUBDATASETS": False, "OPTIONS": "", "OUTPUT": out_raster}) except: shutil.copyfile(piped_3857, out_raster) else: srcExtent = ','.join([unicode(piped_extent.xMinimum()), unicode(piped_extent.xMaximum()), unicode(piped_extent.yMinimum()), unicode(piped_extent.yMaximum())]) processing.run("gdal:translate", {"INPUT": piped_file, "OUTSIZE": 100, "OUTSIZE_PERC": True, "NODATA": 0, "EXPAND": 0, "TARGET_CRS": "", "PROJWIN": srcExtent, "SDS": False, "DATA_TYPE": 0, "COMPRESS": 4, "JPEGCOMPRESSION": 75, "ZLEVEL": 6, "PREDICTOR": 1, "TILED": False, "BIGTIFF": 0, "TFW": False, "COPY_SUBDATASETS": False, "OPTIONS": "", "OUTPUT": out_raster})
iface.addRasterLayer(os.path.join(diretorio, "dados/BR_SRTM.tif")) # Para acessa layer por nome: rlayer = QgsProject.instance().mapLayersByName('BR_SRTM')[0] # quantos algoritos temos? len(QgsApplication.processingRegistry().algorithms()) # quais sao eles? pprint(QgsApplication.processingRegistry().algorithms()[0:10]) # usando processing import processing # Conhecendo mais sobre o algoritmo processing.algorithmHelp("qgis:reprojectlayer") # executando projectResult = processing.run('qgis:reprojectlayer', { 'INPUT': uf, 'TARGET_CRS': 'EPSG:102033', 'OUTPUT': "memory:ufProjected" }) projectResult['OUTPUT'] ufProjected = QgsProject.instance().addMapLayer(projectResult['OUTPUT']) # vendo CRS ufProjected.crs().authid() # processando e carregando # hillshade