I created a script to loop through the Clip Raster By Mask function.

I assign my personal files to the variables and use a nested for loop to iterate through the feature ID numbers in my selected shapefile. This will export a single image for each feature in my shapefile and save it in a folder with the name of each image corresponding to it's feature ID number. It works the way I want it to. The problem is it only works sometimes (maybe 20%) and is very weak when it does work. I can not do anything else on my computer if it starts working correctly. How can I strengthen this script and get it to work 100% or point me in the direction of the problem.

    import os

    layer = qgis.utils.iface.activeLayer()
    input_imagery = '-imagery I'm referencing-'
    input_shape = 'shapefile I'm referecncin-'
    dir_name = '-path to saved file-'
    format = 'tif'

    for format_number in range(283500, 401807):
         base_filename = str(format_number)
         output_file = os.path.join(dir_name, base_filename + "." + format)
         layer.selectByExpression(" \"TARGET_FID\" = '{}' 
         for feat in layer.getFeatures(" \"TARGET_FID\" = '{}' 
             processing.run("gdal:cliprasterbymasklayer", {'INPUT' : 
                'MASK' : QgsProcessingFeatureSourceDefinition(input_shape, True),
                'NODATA' : None,
                'ALPHA_BAND' : True,
                'CROP_TO_CUTLINE' : True,
                'KEEP_RESOLUTION' : True,
                'OPTIONS' : '',
                'DATA_TYPE' : 0,
                'OUTPUT' : output_file})         
  • Please Edit the question to contain the code as ASCII text. – Vince Jan 9 at 16:53

Your Answer

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

Browse other questions tagged or ask your own question.