美文网首页
QGIS python 调用GIS功能

QGIS python 调用GIS功能

作者: 吵吵人 | 来源:发表于2024-02-02 19:24 被阅读0次

    QGIS 中文学习手册:https://www.osgeo.cn/qgisdoc/docs/user_manual/index.html
    前提:已经下载并安装QGIS
    ● qgis环境配置:
    ○ 设置PYTHONPATH为QGIS自带的python路径即可(其他脚本中配置):
    /Applications/QGIS-LTR.app/Contents/MacOS/bin/python3.8
    可用以下语句在QGIS软件中查看路径:

    QStandardPaths.standardLocations(QStandardPaths.AppDataLocation)
    

    ○ 脚本开头需要初始化QGIS资源,以下语句查询路径:

    QgsApplication.prefixPath()
    

    ○ 按步骤配置依然不成功可以试试重装QGIS(血泪教训)

    # @Time : 2023/2/17 15:26
    # @Comment : 独立脚本调用GIS功能
    
    # 1. 环境配置
    from qgis.core import *
    from qgis.PyQt.QtGui import QColor
    from PyQt5.QtCore import *
    import sys
    
    process_path = '/Applications/QGIS-LTR.app/Contents/Resources/python/plugins'
    if process_path not in sys.path:
        sys.path.append(process_path)
    
    QgsApplication.setPrefixPath(r"/Applications/QGIS-LTR.app/Contents/MacOS", True)
    qgs = QgsApplication([], False)
    qgs.initQgis()
    
    from processing.core.Processing import Processing
    
    Processing.initialize()
    import processing
    
    # 2. 加载数据
    data_source = r"XX.shp"
    data_output = r"XX.shp"
    image_output = r"XX.png"
    fileInfo = QFileInfo(data_source)
    if fileInfo.exists():
        print("File exists; Path is correct")
    
    dlr_layer = QgsVectorLayer(data_source, "dlr_layer", "ogr")
    if not dlr_layer.isValid():
        print("Layer failed to load!")
    else:
        QgsProject.instance().addMapLayer(dlr_layer)
        print("Layer loaded successfully!")
    
        # 3. 调用工具箱
    parameter_buffer = {
        'INPUT': dlr_layer,
        'DISTANCE': 0.001,
        'SEGMENTS': 5,
        'DISSOLVE': True,
        'OUTPUT': data_output,
        'END_CAP_STYLE': 0,
        'JOIN_STYLE': 0,
        'MITER_LIMIT': 2
    }
    dlr_buffer = processing.run("native:buffer", parameter_buffer)
    print('file save to:', data_output)
    
    # 4. 可视化输出
    dlr_buffer_layer = QgsVectorLayer(data_output, "dlr_buffer_layer", "ogr")
    if not dlr_buffer_layer.isValid():
        print("Layer failed to load!")
    else:
        QgsProject.instance().addMapLayer(dlr_buffer_layer)
        print("Layer loaded successfully!")
    
    settings = QgsMapSettings()
    settings.setLayers([dlr_buffer_layer])
    settings.setBackgroundColor(QColor(255, 255, 255))
    settings.setOutputSize(QSize(1000, 800))
    settings.setExtent(dlr_layer.extent())
    settings.setOutputDpi(500)
    
    render = QgsMapRendererParallelJob(settings)
    
    
    def finished():
        img = render.renderedImage()
        img.save(image_output, "png")
        print('image save to:', image_output)
    
    
    render.finished.connect(finished)
    render.start()
    render.waitForFinished()
    
    # 5. 退出QGIS
    qgs.exitQgis()
    
    

    相关文章

      网友评论

          本文标题:QGIS python 调用GIS功能

          本文链接:https://www.haomeiwen.com/subject/ixytadtx.html