[GIS] Clipping raster with multiple polygons and naming the resulting rasters

clipqgisraster

I am trying to split a single-band raster (land cover) into smaller parts representing administrative units which are into another shapefile, containing their name as an attribute.

U I did this using SAGA "clip raster with polygon" (in QGIS 2.18) to split the raster and then naming the resulting rasters one by one (by hand) with the name of the administrative unit.

enter image description here

The problem is, I now need to do this process over ±2000 polygons, so doing it by hand is the last resort options.

I tried different options:
a) Using SAGA "clip raster with polygon", iterate over the polygon layer. Works good, but cannot specify an attribute to use a name.

b) Batch-process SAGA "clip raster with polygon" using individual administrative polygons, named after their administrative ID. Works fine, the name of the resulting rasters is as I want it, but the process is long and boring (batch-processing with 2000 rows, filled in part by hand, see image).

enter image description here

So, is there a way of speeding up the process? Is it possible to iterate over a layer, specifying an attribute to use as a name for the resulting layers? Is it possible to auto-fill the batch-processing window with layers open in the "layers panel"?

Best Answer

Your question is quite similar to this one, but it does not say how to automate the separation of the files, so I will answer:

import glob
import fiona
from subprocess import Popen

with fiona.open('polygons.shp', 'r') as dst_in:
    for index, feature in enumerate(dst_in):
        with fiona.open('separated/polygon{}.shp'.format(index), 'w', **dst_in.meta) as dst_out:
            dst_out.write(feature)

polygons = glob.glob('separated/*.shp')  ## Retrieve all the .shp files

for polygon in polygons:
    feat = fiona.open(polygon, 'r')
    name = feat['properties']['Name_of_your_attribute']  
    command = 'gdalwarp -dstnodata -9999 -cutline {} ' \
              '-crop_to_cutline -of GTiff ./input.tiff ./outputraster/{}.tiff'.format(polygon, name )
    Popen(command, shell=True)

This code separates the polygons to different files and then clips the raster with GDAL

Related Question