I have a line map of buildings in a city. I was able to correctly polygonize the buildings in QGIS with the Polygonize processing algorithm. All the holes/islands became features as expected. Now I need to select and remove all features that are completely surrounded by other (one or more) features. Examples shown in red on the image:
These are not part of buildings, but inner yards.
3 Answers
You can use for example this python script to highlight or delete the features that are completely within another feature.
layer = iface.activeLayer() #or the layer you want to use
features_a = layer.getFeatures()
features_b = [feat for feat in layer.getFeatures()]
within_list = list()
for feat_a in features_a:
for feat_b in features_b:
if feat_b.id() != feat_a.id():
if feat_b.geometry().within(feat_a.geometry()):
within_list.append(feat_b.id())
To highlight the features you can use:
layer.setSelectedFeatures(within_list)
And to delete the highlighted features use:
caps = layer.dataProvider().capabilities()
if caps & QgsVectorDataProvider.DeleteFeatures:
res = layer.dataProvider().deleteFeatures(within_list)
As a test result I get for example:
But before you execute this script please save your qgis file because if you want to process a large file this script probably crashes your qgis.
-
Thanks for the idea. As the original picture of mine shows I have a lot of cases when more polygons surround a quasi island, so they are not completely within another polygon.– csandorCommented Sep 29, 2015 at 19:23
an alternative is to use "vector > geoprocessing tools > dissolve" (--Dissolve all-- in the list of dissolve fields), then select the polygons that are "within" the dissolved polygons using the "spatial query" plugin.
-
Thanks for this. My next issue here is how to dissolve a large dataset based on touching geometries.– csandorCommented Sep 29, 2015 at 20:17
-
@csandor You can't dissolve those geometries as well based on a common or shared attribute?– SaultDonCommented Sep 29, 2015 at 21:57
-
@csandor see my edit. As for the size, I've successfully used dissolve with hundred thousands of polygons– radouxjuCommented Sep 30, 2015 at 10:39
You can also duplicate layer and then make spatial query with "touches" between them. Works with prepared data.