Monday, 9 April 2018

python - Programmatically finding polygons which are >90% overlapped by another vector polygon layer using QGIS?


Example layers


I'm trying to figure out how to use python to extract the polygons in one vector that are overlapped by >90% by another vector. I would then like to have a vector/map that will only show those polygons. The example picture shows my layers. I want all the grey polygons that are > 90% red.


I need to do this all via python (or similarly automated methods). I have ~1000 maps to process the same way.



Answer



Next code works in my Python Console of QGIS. It produces a memory layer with polygons which are > 90% overlapped by red areas.



mapcanvas = iface.mapCanvas()

layers = mapcanvas.layers()

#for polygon_intersects
feats_lyr1 = [ feat for feat in layers[0].getFeatures() ]

#for xwRcl
feats_lyr2 = [ feat for feat in layers[1].getFeatures() ]


selected_feats = []

for i, feat1 in enumerate(feats_lyr1):
area1 = 0
area2 = 0
for j, feat2 in enumerate(feats_lyr2):
if feat1.geometry().intersects(feat2.geometry()):
area = feat1.geometry().intersection(feat2.geometry()).area()
print i, j, area, feat2.attribute('class')
if feat2.attribute('class') == 1:

area1 += area
else:
area2 += area
crit = area1/(area1 + area2)
print crit
if crit > 0.9:
selected_feats.append(feat1)

epsg = layers[0].crs().postgisSrid()


uri = "Polygon?crs=epsg:" + str(epsg) + "&field=id:integer""&index=yes"

mem_layer = QgsVectorLayer(uri,
"mem_layer",
"memory")

prov = mem_layer.dataProvider()

for i, feat in enumerate(selected_feats):
feat.setAttributes([i])


prov.addFeatures(selected_feats)

QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

I tried out the code with these two vector layers:


enter image description here


After running the code at the Python Console of QGIS, for corroborating results, there were printed the indexes i, j of involved features, intersection areas, attribute of field in polygons_intersects (1 for red areas and 2 for gray areas) and the overlapping criterion.


0 0 9454207.56892 1
0 1 17429206.7906 2

0 2 10326705.2376 2
0 4 40775341.6814 1
0 5 26342803.0964 2
0 7 11875753.3216 2
0.432253120382
1 6 1198411.02558 2
1 7 1545489.96614 2
1 10 27511427.9909 1
0.90930850584
2 7 750262.940888 2

2 8 12012343.5859 1
0.941213972294
3 6 23321277.5158 2
0.0

The created memory layer (green features) can be observed at the next image. It was as expected.


enter image description here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...