可以编写可通过QGIS中的Python控制台运行的独立pyqgis脚本。进行一些调整,即可使您的独立脚本通过处理框架运行。这具有几个优点。首先,获取用户输入和写入输出文件要容易得多,因为Processing Framework为这些提供了标准化的用户界面。其次,将脚本放入“处理工具箱”中还可以使其成为任何“处理模型”的一部分,或作为具有多个输入的批处理作业运行。本教程将展示如何编写自定义python脚本,该脚本可以作为QGIS中Processing框架的一部分。

注意

在QGIS3中彻底修改了Processing API。请参考本指南以获取最佳做法和提示。

任务概述

我们的脚本将根据用户选择的字段执行溶解操作。它还将为溶解的特征求和另一个字段的值。在示例中,我们将基于CONTINENT属性分解世界shapefile并求和POP_EST字段以计算溶解区域中的总人口。

获取数据

我们将使用 自然地球的Admin 0-国家数据集。

下载Admin 0-国家shapefile。。

资料来源[NATURALEARTH]

为了方便起见,您可以直接从下面下载包含以上图层的地理包:

ne_global.gpkg

程序

  1. 在“ QGIS浏览器面板”中,找到保存下载数据的目录。展开zipgpkg 条目,然后选择ne_10m_admin_0_countries图层。将图层拖到画布上。

  2. 转到处理‣工具箱。单击工具栏中的“脚本”按钮,然后选择“从模板创建新脚本”。

  3. 该模板包含处理框架将其识别为处理脚本并管理输入/输出所需的所有样板代码。让我们开始根据需要定制示例模板。首先将类名从更改ExampleProcessingAlgorithmDissolveProcessingAlgorithm。此名称也需要在createInstance方法中更新。在该类中添加一个文档字符串,以解释该算法的作用。

  4. 向下滚动时,您将看到为脚本分配名称,组,描述等的方法。更改返回值的名称的方法是dissolve_with_sum显示名的方法,方法和的groupId方法 。将shortHelpString方法的返回值更改为将显示给用户的描述。单击保存按钮。Dissolve with Sumscripts

  5. 命名脚本dissolve_with_sum并将其保存在配置文件‣默认‣处理‣脚本文件夹下的默认位置。

  6. 现在,我们将定义脚本的输入。模板已经包含INPUT矢量层和OUTPUT层的定义。我们将添加2个新输入,允许用户选择DISSOLVE_FIELDSUM_FIELD。在该initAlgorithm方法的顶部和下面的代码中添加一个新的导入。单击运行按钮以预览更改。

    from qgis.core import QgsProcessingParameterFieldself.addParameter(        QgsProcessingParameterField(                self.DISSOLVE_FIELD,                'Choose Dissolve Field',                '',                self.INPUT))self.addParameter(        QgsProcessingParameterField(                self.SUM_FIELD,                'Choose Sum Field',                '',                self.INPUT))

  1. 您将看到带有新定义的输入的“用总和溶解”对话框。选择ne_10m_admin_0_countries图层作为Input layer`。由于溶解字段和求和字段都是基于输入层进行过滤的,因此它们将被输入层中的现有字段预先填充。单击关闭按钮。

  2. 现在,我们定义了用于在该processAlgorithm方法中处理数据的自定义逻辑。该方法通过了名为的字典parameters。它包含用户已选择的输入。有一些帮助程序方法,使您可以接受这些输入并创建适当的对象。我们首先使用parameterAsSourceparameterAsString方法获得输入。接下来,我们要创建一个特征接收器,在其中写入输出。QGIS3有一个新的类QgsFeatureSink,它是创建可以接受新功能的对象的首选方法。输出仅需要2个字段-一个用于溶解字段的值,另一个用于所选字段的总和。

    from PyQt5.QtCore import QVariantfrom qgis.core import QgsField, QgsFieldssource = self.parameterAsSource(        parameters,        self.INPUT,        context)dissolve_field = self.parameterAsString(        parameters,        self.DISSOLVE_FIELD,        context)sum_field = self.parameterAsString(        parameters,        self.SUM_FIELD,        context)fields = QgsFields()fields.append(QgsField(dissolve_field, QVariant.String))fields.append(QgsField('SUM_' + sum_field, QVariant.Double))(sink, dest_id) = self.parameterAsSink(        parameters,        self.OUTPUT,        context, fields, source.wkbType(), source.sourceCrs())

  1. 现在,我们将准备输入功能,并创建一个字典来保存dissolve_field中的唯一值和sum_field中的值之和。注意使用feedback.pushInfo()方法与用户交流状态。

    feedback.pushInfo('Extracting unique values from dissolve_field and computing sum')features = source.getFeatures()unique_values = set(f[dissolve_field] for f in features)# Get Indices of dissolve field and sum fielddissolveIdx = source.fields().indexFromName(dissolve_field)sumIdx = source.fields().indexFromName(sum_field)# Find all unique values for the given dissolve_field and# sum the corresponding values from the sum_fieldsum_unique_values = {}attrs = [{dissolve_field: f[dissolveIdx], sum_field: f[sumIdx]} for f in source.getFeatures()]for unique_value in unique_values:        val_list = [ f_attr[sum_field] for f_attr in attrs if f_attr[dissolve_field] == unique_value]        sum_unique_values[unique_value] = sum(val_list)

  1. 接下来,我们将native:dissolve在输入层上调用内置处理算法以生成分解的几何图形。一旦有了可溶的几何形状,我们便会遍历可溶算法的输出,并创建要添加到输出中的新特征。最后,我们返回dest_idFeatureSink作为输出。现在脚本已准备就绪。单击运行按钮。

注意

请注意,使用parameters[self.INPUT]可以直接从参数字典中获取输入层,而无需将其定义为源。由于我们将输入对象传递给算法而不进行任何操作,因此没有必要将其定义为源。

from qgis.core import QgsFeature# Running the processing dissolve algorithmfeedback.pushInfo('Dissolving features')dissolved_layer = processing.run("native:dissolve", {        'INPUT': parameters[self.INPUT],        'FIELD': dissolve_field,        'OUTPUT': 'memory:'        }, context=context, feedback=feedback)['OUTPUT']# Read the dissolved layer and create output featuresfor f in dissolved_layer.getFeatures():        new_feature =  QgsFeature()        # Set geometry to dissolved geometry        new_feature.setGeometry(f.geometry())        # Set attributes from sum_unique_values dictionary that we had computed        new_feature.setAttributes([f[dissolve_field], sum_unique_values[f[dissolve_field]]])        sink.addFeature(new_feature, QgsFeatureSink.FastInsert)return {self.OUTPUT: dest_id}

  1. 在“用总和溶解”对话框中,选择ne_10m_admin_0_countries作为“输入”层,CONTINENT“溶解”字段和POP_EST“总和”字段。点击运行。

  2. 处理完成后,单击“关闭”按钮,然后切换到QGIS主窗口。

  3. 您将看到每个大陆具有一个要素的已分解输出层,以及该大陆各个国家的总人口合计。

  4. 编写处理脚本的另一个优点是,处理框架中的方法知道图层选择,并自动过滤输入以仅使用所选功能。发生这种情况是因为我们将输入定义为QgsProcessingParameterFeatureSource。特征源允许使用包含矢量要素的任何对象,而不仅仅是矢量图层,因此,当图层中有选定要素并要求Processing使用选定要素时,输入将作为QgsProcessingFeatureSource包含选定要素的对象传递到脚本中而不是完整的矢量层。这是此功能的快速演示。假设我们只想溶解某些大洲。让我们使用“表达式”工具的“选择”功能来创建选择。

  5. 输入以下表达式以选择北美和南美的要素,然后单击“选择”。

    "CONTINENT" = 'North America' OR "CONTINENT" = 'South America'

  1. 您将看到以黄色突出显示的所选功能。找到该dissolve_with_sum脚本,然后双击以运行它。

  2. 在“用总和溶解”对话框中,选择ne_10m_admin_0_countries作为输入层。这次,请确保选中“仅所选功能”框。选择SUBREGION作为“溶解”字段和POP_EST“求和”字段。

  3. 处理完成后,单击“关闭”,然后切换回QGIS主窗口。您会注意到一个新图层,其中仅溶解了选定的要素。单击“标识”按钮,然后单击某个功能以检查并验证脚本是否正常运行。

以下是完整的脚本供参考。您可以修改它以满足您的需求。

# -*- coding: utf-8 -*-"""****************************************************************************                                                                         **   This program is free software; you can redistribute it and/or modify  **   it under the terms of the GNU General Public License as published by  **   the Free Software Foundation; either version 2 of the License, or     **   (at your option) any later version.                                   **                                                                         ****************************************************************************"""from PyQt5.QtCore import QCoreApplication, QVariantfrom qgis.core import (QgsProcessing,                       QgsFeatureSink,                       QgsFeature,                       QgsField,                       QgsFields,                       QgsProcessingException,                       QgsProcessingAlgorithm,                       QgsProcessingParameterFeatureSource,                       QgsProcessingParameterFeatureSink,                       QgsProcessingParameterField,                       )import processingclass DissolveProcessingAlgorithm(QgsProcessingAlgorithm):    """    Dissolve algorithm that dissolves features based on selected    attribute and summarizes the selected field by cumputing the    sum of dissolved features.    """    INPUT = 'INPUT'    OUTPUT = 'OUTPUT'    DISSOLVE_FIELD = 'dissolve_field'    SUM_FIELD = 'sum_field'    def tr(self, string):        """        Returns a translatable string with the self.tr() function.        """        return QCoreApplication.translate('Processing', string)    def createInstance(self):        return DissolveProcessingAlgorithm()    def name(self):        """        Returns the algorithm name, used for identifying the algorithm. This        string should be fixed for the algorithm, and must not be localised.        The name should be unique within each provider. Names should contain        lowercase alphanumeric characters only and no spaces or other        formatting characters.        """        return 'dissolve_with_sum'    def displayName(self):        """        Returns the translated algorithm name, which should be used for any        user-visible display of the algorithm name.        """        return self.tr('Dissolve with Sum')    def group(self):        """        Returns the name of the group this algorithm belongs to. This string        should be localised.        """        return self.tr('scripts')    def groupId(self):        """        Returns the unique ID of the group this algorithm belongs to. This        string should be fixed for the algorithm, and must not be localised.        The group id should be unique within each provider. Group id should        contain lowercase alphanumeric characters only and no spaces or other        formatting characters.        """        return 'scripts'    def shortHelpString(self):        """        Returns a localised short helper string for the algorithm. This string        should provide a basic description about what the algorithm does and the        parameters and outputs associated with it..        """        return self.tr("Dissolves selected features and creates and sums values of features that were dissolved")    def initAlgorithm(self, config=None):        """        Here we define the inputs and output of the algorithm, along        with some other properties.        """        # We add the input vector features source. It can have any kind of        # geometry.        self.addParameter(            QgsProcessingParameterFeatureSource(                self.INPUT,                self.tr('Input layer'),                [QgsProcessing.TypeVectorAnyGeometry]            )        )        self.addParameter(            QgsProcessingParameterField(                self.DISSOLVE_FIELD,                'Choose Dissolve Field',                '',                self.INPUT))        self.addParameter(            QgsProcessingParameterField(                self.SUM_FIELD,                'Choose Sum Field',                '',                self.INPUT))        # We add a feature sink in which to store our processed features (this        # usually takes the form of a newly created vector layer when the        # algorithm is run in QGIS).        self.addParameter(            QgsProcessingParameterFeatureSink(                self.OUTPUT,                self.tr('Output layer')            )        )    def processAlgorithm(self, parameters, context, feedback):        """        Here is where the processing itself takes place.        """        source = self.parameterAsSource(            parameters,            self.INPUT,            context        )        dissolve_field = self.parameterAsString(            parameters,            self.DISSOLVE_FIELD,            context)        sum_field = self.parameterAsString(            parameters,            self.SUM_FIELD,            context)                fields = QgsFields()        fields.append(QgsField(dissolve_field, QVariant.String))        fields.append(QgsField('SUM_' + sum_field, QVariant.Double))                (sink, dest_id) = self.parameterAsSink(            parameters,            self.OUTPUT,            context, fields, source.wkbType(), source.sourceCrs())                # Create a dictionary to hold the unique values from the         # dissolve_field and the sum of the values from the sum_field        feedback.pushInfo('Extracting unique values from dissolve_field and computing sum')        features = source.getFeatures()        unique_values = set(f[dissolve_field] for f in features)        # Get Indices of dissolve field and sum field        dissolveIdx = source.fields().indexFromName(dissolve_field)        sumIdx = source.fields().indexFromName(sum_field)                # Find all unique values for the given dissolve_field and        # sum the corresponding values from the sum_field        sum_unique_values = {}        attrs = [{dissolve_field: f[dissolveIdx], sum_field: f[sumIdx]}                for f in source.getFeatures()]        for unique_value in unique_values:            val_list = [ f_attr[sum_field]                 for f_attr in attrs if f_attr[dissolve_field] == unique_value]            sum_unique_values[unique_value] = sum(val_list)                # Running the processing dissolve algorithm        feedback.pushInfo('Dissolving features')        dissolved_layer = processing.run("native:dissolve", {            'INPUT': parameters[self.INPUT],            'FIELD': dissolve_field,            'OUTPUT': 'memory:'        }, context=context, feedback=feedback)['OUTPUT']                # Read the dissolved layer and create output features        for f in dissolved_layer.getFeatures():            new_feature =  QgsFeature()            # Set geometry to dissolved geometry            new_feature.setGeometry(f.geometry())            # Set attributes from sum_unique_values dictionary that we had computed            new_feature.setAttributes([f[dissolve_field], sum_unique_values[f[dissolve_field]]])            sink.addFeature(new_feature, QgsFeatureSink.FastInsert)                return {self.OUTPUT: dest_id}

END

点击下方“阅读原文”查看更多

python脚本编写_【PyQGIS】编写用于处理框架(QGIS3)的Python脚本相关推荐

  1. python hack库_这里有123个黑客必备的Python工具!

    123个Python渗透测试工具,当然不仅于渗透~ 如果你想参与漏洞研究.逆向工程和渗透,我建议你时候用Python语言.Python已经有很多完善可用的库,我将在这里把他们列出来. 这个清单里的工具 ...

  2. python 欢迎自己程序编写_神操作!一句查询让Python帮忙自己写程序

    卧槽,神操作!一句查询让Python帮忙自己写程序 对于很多初入Python编程的同学们而言,对于Python程序的编写,往往会十分生疏,学会了Python的语法,但是转头就忘了,或者是想实现一个基础 ...

  3. 知道经纬度用python画路线图_神级程序员教你用Python如何画一个中国地图!(好好玩)...

    为什么是Python 先来聊聊为什么做数据分析一定要用 Python 或 R 语言.编程语言这么多种, Java , PHP 都很成熟,但是为什么在最近热火的数据分析领域,很多人选择用 Python ...

  4. python网络安全设计_专为渗透测试人员设计的 Python 工具大合集

    如果你对漏洞挖掘.逆向工程分析或渗透测试感兴趣的话,我第一个要推荐给你的就是Python编程语言.Python不仅语法简单上手容易,而且它还有大量功能强大的库和程序可供我们使用.在这篇文章中,我们会给 ...

  5. 420集的python教程下载_微软官方发布了最新420集Python教程,这教程简直就是编程界福利...

    泰国清迈-2014 年 10 月 22 日: 微软主页 clos Austria, Tyrol, Axamer Lizum, hosting village of 近日,微软上线了一套 Python ...

  6. python软件工程师_为什么每个软件工程师都应该学习Python?

    python软件工程师 大家好,如果您经常关注我的博客 ,或者在HackerNoon上阅读我的文章,那么您可能想知道为什么我要写一篇文章告诉人们学习Python ? 几年前,我不是要您更喜欢Java吗 ...

  7. python 模糊匹配_很冷门,但非常实用的 Python 库

    Python 是一个很棒的语言.它是世界上发展最快的编程语言之一.它一次又一次地证明了在开发人员职位中和跨行业的数据科学职位中的实用性.整个 Python 及其库的生态系统使它成为全世界用户(初学者和 ...

  8. python log函数_求你别再花大价钱学 Python 之爬虫实战

    引子 Python 基本概念 Python 优势和劣势 优势 Python 的劣势 Python 安装设置 Python 基本语法 程序例子 Python 基本语法 Python 爬虫实现 爬虫相关 ...

  9. python 生成空白矩阵_3个用于数据科学的顶级Python库

    用这些库把Python变成一个科学数据分析和建模工具. image by Opensource.com Python许多吸引人的特点如效率.代码可读性和速度使它成为数据科学爱好者的首选编程语言.对于希 ...

  10. python 功能 代码_挑战“不可能”的代码:你不知道的Python功能

    本文转载自公众号"读芯术"(ID:AI_Discovery) Python看似简单,但实则变化万千,笔者总都能看到一些代码以近乎不可能的方式呈现.这些功能很精妙,以至于我无法想象没 ...

最新文章

  1. Java并发学习二:编译优化带来的有序性问题导致的并发Bug
  2. ISCW实验:配置Cisco IOS EASY ××× Server和Cisco ××× Client
  3. sudo重定向失败解决方法
  4. 暖通空调系统计量表选型与应用
  5. ipython和pylab模式_为什么要使用IPython?
  6. div iframe 显示html,IE中iframe标签显示在DIV之上的问题解决方案
  7. C语言中的空字符'\0'
  8. POJ_3090.Visible Lattice Points
  9. C#曲线分析平台的制作(一,ajax+json前后台数据传递)
  10. 微信小程序开发及开发中遇到的问题小总结
  11. [RK3288][Android6.0] Audio录音HAL层的数据读取流程分析
  12. [YNOI2017]由乃的商场之旅 莫队
  13. 2015年SaaS细分领域部分代表公司盘点 融资额近40亿
  14. tkinter-button详解
  15. Leetcode PHP题解--D70 784. Letter Case Permutation
  16. USB中CDC-ECM的了解和配置
  17. Matlab实现频域滤波——二维傅里叶变换、低通、高通
  18. Gremlins.js – 模拟用户随机操作的 JS 测试库
  19. fundamentals of computer graphics
  20. 三个方法让你播音主持正确发声

热门文章

  1. 经历能让人变得更理智更成熟
  2. 【Sql Server】DateBase-SQL安全
  3. Shiro第一个程序:官方快速入门程序Qucickstart详解教程
  4. Camera系列规格参数
  5. 提示和技巧:光线跟踪最佳实践
  6. 实用的Linux 安装 zip unzip
  7. CSS flex 用法
  8. python xlrd 的merged_cells 里面四个参数的含义
  9. Ubuntu 系统安装Visual Studio Code
  10. android源码下载方法 批量下载 基于windows os