2

I have a raster which I want to do a clip with a vector layer (polygon) using its atttribute values.
What I have done so far is the folliwing:

from qgis.core import *
from qgis.gui import *
import processing   
from processing.core.Processing import Processing

VECTOR = QgsVectorLayer('MyShapefile.shp','MyShapefile','ogr') 
RASTER = QgsRasterLayer('MyRaster','MyRaster')
row_info = VECTOR.getFeatures()
for row in row_info:
   row_name = row['NAME_FIELD']
   clip = processing.runalg("gdalogr:cliprasterbymasklayer", RASTER, VECTOR, '0', False, True, True, 2, 0, 1, 1, 1, False, 2, False, "", 'OUTPUT\Clip_{}.format(row_name)')

I have to use a 'select features' using NAME_FIELD value but I can't find how to iterate throw values, select each value , clip according to that value and go to the next value to clip again.

I am using Python Editor in QGIS 2.18

1

I guess, you want to iterate features in VECTOR layer and clip RASTER layer by each feature's geometry, seperately. To do that, you have to select each feature in the for loop. If any feature(s) is selected, Processing tools typically operate only on/by that feature(s).

Try following lines:

from qgis.core import *
from qgis.gui import *
import processing   
from processing.core.Processing import Processing

VECTOR = QgsVectorLayer('MyShapefile.shp','MyShapefile','ogr') 
RASTER = QgsRasterLayer('MyRaster','MyRaster')
row_info = VECTOR.getFeatures()
for row in row_info:
   row_name = row['NAME_FIELD']

   VECTOR.setSelectedFeatures([row.id()]) # ADD THIS LINE

   clip = processing.runalg("gdalogr:cliprasterbymasklayer", RASTER, VECTOR, '0', False, True, True, 2, 0, 1, 1, 1, False, 2, False, "", 'OUTPUT\Clip_{}.format(row_name)')
  • Thank you Kadir, I have added that line of code, it runs (execfile(u'c:/user....)but output is empty. – RMP Aug 21 '18 at 20:22
1

Instead of selecting the polygon try to filter it. So use VECTOR.setSubsetString and don't forget on the end of Loop to clear the filter with VECTOR.setSubsetString ('')

from qgis.core import *
from qgis.gui import *
import processing   
from processing.core.Processing import Processing

VECTOR = QgsVectorLayer('MyShapefile.shp','MyShapefile','ogr') 
RASTER = QgsRasterLayer('MyRaster','MyRaster')
row_info = VECTOR.getFeatures()
for row in row_info:
row_name = row['NAME_FIELD']
    output_file = "d:\\path_to_save\\" + "cliped_" + str(row['NAME_FIELD']) + ".tif"

    VECTOR.setSubsetString("NAME_FIELD=" + str(row['NAME_FIELD']))

    clip = processing.runalg("gdalogr:cliprasterbymasklayer", RASTER, VECTOR, '0', False, True, True, 2, 0, 1, 1, 1, False, 2, False, "", output_file)

    VECTOR.setSubsetString('')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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