I have one raster and one vector layer and I need to clip raster by each specific feature (polygon) from vector layer. So basically I need array of vector layers.
Only answers I found is to mask by whole vector layer.
Is there a way to do that in python console?
I tried with
alg_name = 'gdal:cliprasterbymasklayer'
params = {'INPUT': rl[0],
'MASK': boulder.geometry().boundingBox(),
'NODATA': 255.0,
'ALPHA_BAND': False,
'CROP_TO_CUTLINE': True,
'KEEP_RESOLUTION': True,
'OPTIONS': '-of GTiff -co COMPRESS=LZW',
'DATA_TYPE': 0, # Byte
'OUTPUT': 'test',
}
result = processing.run(alg_name, params, feedback=feedback)
1 Answer 1
You can iterate over the features in your mask layer and use the materialize method to create an in-memory vector layer containing each feature in turn, and use that as the 'MASK'
parameter for the clip algorithm.
import os
output_folder = r'Path/To/Destination/Folder'
raster_layer = QgsProject.instance().mapLayersByName('Name_of_raster_layer')[0]
mask_layer = QgsProject.instance().mapLayersByName('Name_of_vector_layer')[0]
for ft in mask_layer.getFeatures():
temp_lyr = mask_layer.materialize(QgsFeatureRequest([ft.id()]))
output_path = os.path.join(output_folder, f'Clipped_raster_{ft.id()}.tif')
params = {'INPUT':raster_layer,
'MASK':temp_lyr,
'SOURCE_CRS':None,
'TARGET_CRS':None,
'TARGET_EXTENT':None,
'NODATA':None,
'ALPHA_BAND':False,
'CROP_TO_CUTLINE':True,
'KEEP_RESOLUTION':False,
'SET_RESOLUTION':False,
'X_RESOLUTION':None,
'Y_RESOLUTION':None,
'MULTITHREADING':False,
'OPTIONS':'',
'DATA_TYPE':0,
'EXTRA':'-co COMPRESS=LZW',
'OUTPUT':output_path}
processing.run("gdal:cliprasterbymasklayer", params)
print('Done')
-
Which DATA_TYPE should I use for double type of pixels.Tomislav Muic– Tomislav Muic2023年08月06日 11:43:18 +00:00Commented Aug 6, 2023 at 11:43
-
@Tomislav Muic, if you need to explicitly specify the data type, then I guess Float32 (6) is probably what you want. But I suggest to put
0
for the'DATA_TYPE'
parameter- that will tell the algorithm to use the input raster data type.Ben W– Ben W2023年08月07日 11:28:25 +00:00Commented Aug 7, 2023 at 11:28