I have many polygon layers, each layer containing many polygons with inner rings. I know that you can delete a ring manually with QGIS (Edit -> Delete ring). I need the python equivalent to automatically process all my polygon layers.
This blog posts tells how to do it with SQL in PostGIS http://geospatial.commons.gc.cuny.edu/2013/11/04/filling-in-holes-with-postgis/
Spatialite has also ExteriorRing function http://www.gaia-gis.it/gaia-sins/spatialite-sql-latest.html so you do not need to have PostGIS installed. Is it necessary for you to do the job with python inside QGIS? The SQL looks like this:
UPDATE my_spatial_table t SET geom = a.geom FROM ( SELECT gid, ST_Collect(ST_MakePolygon(geom)) AS geom FROM ( SELECT gid, ST_NRings(geom) AS nrings, ST_ExteriorRing((ST_Dump(geom)).geom) AS geom FROM my_spatial_table WHERE ST_NRings(geom) > 1 ) s GROUP BY gid, nrings HAVING nrings > COUNT(gid) ) a WHERE t.gid = a.gid;
QGIS offers a tool called
Delete holes that you can call via Python in this way:
import processing vLayer = iface.activeLayer() # Select the layer in QGIS layer tree before calling this outPath = "/path/to/output.shp" processing.runalg( "qgis:deleteholes", vLayer, outPath )
You could iterate through QGIS layers to run such tool on your polygon layers.
You could also access the source code of the tool to see how it works: https://github.com/qgis/QGIS/blob/release-2_14/python/plugins/processing/algs/qgis/DeleteHoles.py Note that the algorithm will change in QGIS v3.0, since there'll be a new
geometry().removeInteriorRings() method: https://github.com/qgis/QGIS/blob/master/python/plugins/processing/algs/qgis/DeleteHoles.py
If you are comfortable using Python, including ArcPy... Try this...
You can read the shapefiles using:
import shapefile # Required plugin is PyShp sf = shapefile.Reader("Path to shapefile...")
'sf' will now contain your shapefile information.
Use ArcPy to find the intersection of polygons. If the interior polygons intersect the larger polygon (which they obviously will), delete the shape.
More information about PyShp could be found here.
More information of ArcPy can be found here, including about the Intersection function