QGIS批量将面状水系提取中心线

在QGIS中使用Python编程批量提取面状水系的中心线,可以按照以下代码示例进行操作:
# 导入必要的模块
import processing
from qgis.core import QgsProject, QgsVectorLayer

# 加载水系面图层
water_body_layer = QgsProject.instance().mapLayersByName('Water_Body')[0]

# 创建输出目录
output_dir = 'path/to/output/'
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 遍历所有水系面要素
features = water_body_layer.getFeatures()
for feature in features:
    # 获取水系面要素的几何对象
    geom = feature.geometry()
    
    # 提取中心线
    centerline_output = output_dir + f'centerline_{feature.id()}.shp'
    processing.run("native:centroids", {
        'INPUT': QgsProcessingFeatureSourceDefinition(geom.source()),
        'ALL_PARTS': False,
        'OUTPUT': centerline_output
    })

# 加载所有中心线图层(可选)
centerline_layers = []
for filename in os.listdir(output_dir):
    if filename.startswith('centerline_') and filename.endswith('.shp'):
        layer_path = output_dir + filename
        centerline_layer = QgsVectorLayer(layer_path, filename[:-4], 'ogr')
        if centerline_layer.isValid():
            centerline_layers.append(centerline_layer)
            QgsProject.instance().addMapLayer(centerline_layer)

# 注意:上述代码示例假设已经加载了名为"Water_Body"的水系面图层,并将中心线图层保存到指定的输出目录中(请替换为实际路径)。
# 遍历所有水系面要素,并使用QGIS的原生算法"native:centroids"提取中心线。每个中心线图层的文件名格式为"centerline_要素ID.shp"。

# 如需将每个中心线图层加载到QGIS项目中,可以取消注释上述代码段中的相关部分。

请注意,在编程过程中要确保水系面图层已正确加载,并且输出目录等设置与你的系统环境相匹配。此外,对于后续的数据分析和处理,可能需要进一步了解QGIS和Python的相关文档和函数用法。

猜你喜欢

转载自blog.csdn.net/weixin_58851039/article/details/131468744