简体   繁体   English

在Python QGIS中查找相邻的多边形

[英]Find neighbouring polygons in Python QGIS

I am using code I found and slightly modified for my purposes. 我正在使用找到的代码,并对其进行了稍微的修改。 The problem is, it is not doing exactly what I want, and I am stuck with what to change to fix it. 问题是,它不能完全满足我的要求,而我坚持要进行更改以修复它。

I am searching for all neighbouring polygons, that share common borded (a line), that is not a point 我正在搜索所有共有多边形(一条线)的非相邻多边形,这不是一个点 在此处输入图片说明

My goal: 135/12 is neigbour with 319/2 135/4, 317 but not with 320/1 我的目标:135/12是neigbour,319/2 135 / 4,317,但不是320/1

What I get in my QGIS table after I run my script 运行脚本后,我在QGIS表中得到的内容

在此处输入图片说明

NEIGBOURS are the neighbouring polygons, NEIGBOURS是相邻的多边形,

SUM is the number of neighbouring polygons SUM是相邻多边形的数量

The code I use also includes 320/1 as a neighbouring polygon. 我使用的代码还包括320/1作为相邻的多边形。 How to fix it? 如何解决?

    from qgis.utils import iface
    from PyQt4.QtCore import QVariant
    _NAME_FIELD = 'Nr'
    _SUM_FIELD = 'calc'
    _NEW_NEIGHBORS_FIELD = 'NEIGHBORS'
    _NEW_SUM_FIELD = 'SUM'
    layer = iface.activeLayer()
    layer.startEditing()
    layer.dataProvider().addAttributes(
            [QgsField(_NEW_NEIGHBORS_FIELD, QVariant.String),
             QgsField(_NEW_SUM_FIELD, QVariant.Int)])
    layer.updateFields()
    feature_dict = {f.id(): f for f in layer.getFeatures()}

    index = QgsSpatialIndex()
    for f in feature_dict.values():
        index.insertFeature(f)
    for f in feature_dict.values():
        print 'Working on %s' % f[_NAME_FIELD]
        geom = f.geometry()

        intersecting_ids = index.intersects(geom.boundingBox())

        neighbors = []
        neighbors_sum = 0
        for intersecting_id in intersecting_ids:
            intersecting_f = feature_dict[intersecting_id]

            if (f != intersecting_f and
                not intersecting_f.geometry().disjoint(geom)):
                neighbors.append(intersecting_f[_NAME_FIELD])
                neighbors_sum += intersecting_f[_SUM_FIELD]
        f[_NEW_NEIGHBORS_FIELD] = ','.join(neighbors)
        f[_NEW_SUM_FIELD] = neighbors_sum
        layer.updateFeature(f)

    layer.commitChanges()
    print 'Processing complete.'

I have found somewhat a workaround for it. 我找到了一些解决方法。 Before using my script, I create a small (for my purposes, 0,01 m was enough) buffer around all joints. 在使用脚本之前,我会在所有关节周围创建一个小的缓冲区(就我的目的而言,0.01 m就足够了)。 Later, I use a Difference tool to remove the buffer areas from my main layer, thus removing not-needed neighbouring polygons. 以后,我使用“差异”工具从主图层中删除缓冲区,从而删除了不需要的相邻多边形。 Using the code now works fine 现在使用代码可以正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM