9

I have a layer with MultiPolygons. Some of them have parts less than five m2 which I want to delete.

The QgsGeometry class has methods: parts() and deletePart(self, partNum: int). On parts() I can apply area() to get the area. https://qgis.org/pyqgis/master/core/QgsGeometry.html

What I am missing, is a method to get the partNum.

Can someone point me in the right direction?

Here is the code I came up so far. But I doubt that the index of the list asGeometryCollection is the same as the numPart index. Alternatively, I could create a new geometry, and loop over the parts, and if a part is > 5, add the part to the new geometry.

# Minimum area threshold
minimum_area = 5

# Loop through all the features in the layer
for feature in layer.getFeatures():
    # Retrieve the multipolygon geometry
    geometry = feature.geometry()
    geom = geometry.asGeometryCollection()
    numParts = len(geom)
    # loop over parts and numParts ( same index ??)
    for part, numPart in zip(geometry.parts(), range(numParts)):
        if part.area() < minimum_area:
            geometry.deletePart(numPart)
1

1 Answer 1

11

You can make a new part list from the MultiPolygon instead of deleting the parts.

layer = iface.activeLayer()

# Minimum area threshold
minimum_area = 2000

layer.startEditing()

# Loop through all the features in the layer
for feature in layer.getFeatures():

    # get polygons collection from geometry
    geoms = feature.geometry().asGeometryCollection()

    # filter the parts      
    filtered_geoms= [g.asPolygon() for g in geoms if g.area() > minimum_area]

    # build a new multipolygon
    new_geom = QgsGeometry.fromMultiPolygonXY(filtered_geoms)
    
    # change the geometry
    layer.changeGeometry(feature.id(), new_geom)

# layer.commitChanges()

Test the script. If it meets your need, uncomment the last line. It saves the changes to the data source.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.