如何在Python(使用qgis和PyQt5包)或QGIS的Python控制台中的独立脚本中运行“最低成本路径”算法?

问题描述 投票:0回答:1

我有一个矢量文件(点形状文件)。在这个向量中,有 4 个点。我想获得这些点之间的最低成本路径。我有一个栅格文件(实际上是坡度),我想将其用作成本栅格图层。我按照这篇文章得到了结果:https://greggsaldutti-jr.medium.com/multiple-step-least-cost-path-analysis-with-qgis-and-python-892feef692f6#:~:text= LCP%20分析%20是%20a%20GIS,然后%20be%20使用%20进行%20可视化.

我直接使用QGIS获取两个向量点。现在我想获得循环内超过 2 个向量点的最短路径。

我在 QGIS 中尝试了使用 python 的独立脚本和 Python 控制台。两者都不起作用。有人可以帮我解决这个问题吗?

import pandas as pd
import numpy as np
import os

#importing the necessary libraries
import sys
from qgis import processing
from qgis.analysis import QgsNativeAlgorithms
from qgis.core import *
from PyQt5.QtCore import QVariant 
from qgis.analysis import QgsNativeAlgorithms
#from processing.core.Processing import Processing
from qgis.gui import *
from qgis.PyQt.QtWidgets import *
#import processing
from qgis.analysis import QgsNativeAlgorithms

#setting working directory
path="/path/to/vector/file/ALBA-1.shp"
rast_fp="/path/to/raster/file/slope.tif"
output_path="path/to/OUTPUT/"

def lcp_series(points, rast_fp, output_path):
   
    '''
    A function that runs least cost path analysis algorithim on a series of points. 
    points: a path to shapefile containing a layer with  points
    rast_fp: a file path to a cost raster
    out_path: a file path where results should be saved
    The to and from points require a column 'order' with the ordered points 1..2..3..etc.
    This uses the Cost distance analysis:Least Cost Path plugin algorithm, but allows a stepwise calculation, 
    eg, A to B, B to C, etc.
    '''
    
    #read in points vector
    points = QgsVectorLayer(points, "points", "ogr")
    QgsProject.instance().addMapLayer(points)
    
    #read in raster layer
    rast = QgsRasterLayer(rast_fp, 'rast')
    QgsProject.instance().addMapLayer(rast)

    #retrieve points as feature
    iterFrom = points.getFeatures()
    
    #start iteration counts
    i = 1
    j = 2

    for feature in iterFrom: 
      #create and name virtual origin layer
        from_temp_layer = points.materialize(QgsFeatureRequest().setFilterFids(points.selectedFeatureIds()))
        from_temp_layer.setName('from_temp_layer')
      #create and name virtual destinatoin layer
        to_temp_layer = points.materialize(QgsFeatureRequest().setFilterFids(points.selectedFeatureIds()))
        to_temp_layer.setName('to_temp_layer')    
      
      #call i feature and create a point, set as origin
        if feature['Cable_Poin'] == i :
            from_pt = feature
        #get feature from poitns    
        iterTwo = points.getFeatures()
        #call j feature and create a point, set as destination
        for feat in iterTwo :
            if feat['Cable_Poin'] == j:
                to_pt = feat
        #create empty temp layers
        from_vpr = from_temp_layer.dataProvider()
        to_vpr = to_temp_layer.dataProvider()
        
        #populate empty temp layers with points: origin
        from_vpr.addFeatures([from_pt])
        from_temp_layer.updateExtents()
        #populate empty temp layers with points: destination  
        to_vpr.addFeatures([to_pt])
        to_temp_layer.updateExtents()
        
        #run algorithm 
        processing.runAndLoadResults("Cost distance analysis:Least Cost Path", 
        {'BOOLEAN_FIND_LEAST_PATH_TO_ALL_ENDS' : False, 
        'BOOLEAN_OUTPUT_LINEAR_REFERENCE' : False, 
        'INPUT_COST_RASTER' : rast,
        'INPUT_END_LAYER' : to_temp_layer,
        'INPUT_RASTER_BAND' : 1, 
        'INPUT_START_LAYER' : from_temp_layer,
        'OUTPUT' : output_path + str(i) + "_" + str(j) 
        })
        #reset counts
        i = i +1
        j = j+ 1

我得到的错误是

{
    "name": "AttributeError",
    "message": "module 'qgis.processing' has no attribute 'run'",
    "stack": "---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[8], line 37
     34 to_temp_layer.updateExtents()
     36 #run algorithm 
---> 37 processing.run(\"qgis:leastcostpath\", 
     38 {'BOOLEAN_FIND_LEAST_PATH_TO_ALL_ENDS' : False, 
     39 'BOOLEAN_OUTPUT_LINEAR_REFERENCE' : False, 
     40 'INPUT_COST_RASTER' : rast,
     41 'INPUT_END_LAYER' : to_temp_layer,
     42 'INPUT_RASTER_BAND' : 1, 
     43 'INPUT_START_LAYER' : from_temp_layer,
     44 'OUTPUT' : output_path + str(i) + \"_\" + str(j) 
     45 })
     46 #reset counts
     47 i = i +1

AttributeError: module 'qgis.processing' has no attribute 'run'"
}

我可以进口加工。在这种情况下,找不到算法。

python-3.x pyqt5 qgis pyqgis
1个回答
0
投票

我建议您确保 QGIS 处理框架在脚本开始时已初始化。另外,请注意,对于 QGIS 3.x,调用处理算法的正确方法是通过

processing.run()
processing.runAndLoadResults()
函数。

还请尝试包含错误处理以捕获处理算法抛出的异常并在此处分享。这可以帮助调试和理解脚本执行时出现的问题。

© www.soinside.com 2019 - 2024. All rights reserved.