0

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)
PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Aug 6, 2023 at 6:44

1 Answer 1

2

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')
answered Aug 6, 2023 at 10:49
2
  • Which DATA_TYPE should I use for double type of pixels. Commented 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. Commented Aug 7, 2023 at 11:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.