Reputation: 41
I have a Raster and a Polygon (5 Polygons in it, Name "Gitter") Shapefile. I would like to cut the Raster with the each Polygon in a different file. Every Polygon has an attribute "id", from 1 to 5.
I choose the tool cut raster with layermask as a batch process. At the mask layer, i choose fill values by expression, but how the expression is right. I have tried 'Gitter' "id"= @row_number or $currentfeature or 'Gitter'$currentfeature. Nothing worked.
Upvotes: 0
Views: 261
Reputation:
I have a bit of experience with QGIS and Python. I remember once I was testing what you needed, with the difference that I didn't mind naming the raster files with an attribute of the vector function. If your 'id' attribute is the same as the 'id' of the feature, you can try using the vector iterator button and you can set a file prefix that will be followed by the id of the mask feature. Here you can find more info about this: Vector iterator button.
If your id field is not the same as the feature id, then you can open the QGIS python console and paste this code replacing the file paths and field name.
from os import path
import processing
vector_layer_path = 'vector/path' # replace vector/path with the full path of the vector layer, remember the file extensions
raster_layer_path = 'raster/path' # replace raster/path with the full path of the raster layer, remember the file extensions
field = 'name_of_your_field' # replace name_of_your_field with the field that have the file names for the output rasters
output_folder = 'folder/path' # replace folder/path with the path where the output rasters will be stored
project = QgsProject().instance()
vector_layer = QgsVectorLayer(vector_layer_path, '', "ogr")
raster_layer = QgsRasterLayer(raster_layer_path, '')
project.addMapLayer(vector_layer)
vector_features = vector_layer.getFeatures()
for feature in vector_features:
vector_layer.select(feature.id())
processing.run('gdal:cliprasterbymasklayer', {
'INPUT': raster_layer_path,
'MASK': QgsProcessingFeatureSourceDefinition(vector_layer.id(), True),
'KEEP_RESOLUTION': True,
'OUTPUT': path.join(output_folder, str(feature[field]) + '.tiff')
})
vector_layer.removeSelection()
Upvotes: 0